| 1 | package format |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "html" |
| 7 | "regexp" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "unicode" |
| 11 | ) |
| 12 | |
| 13 | // maxHeadingLevel is the maximum valid HTML heading level. |
| 14 | const maxHeadingLevel = 6 |
| 15 | |
| 16 | var ( |
| 17 | markdownHeadingRegex = regexp.MustCompile(`(?m)^#{1,6}\s+`) |
| 18 | markdownBoldRegex = regexp.MustCompile(`\*{1,2}(.+?)\*{1,2}`) |
| 19 | markdownItalicRegex = regexp.MustCompile(`_{1,2}(.+?)_{1,2}`) |
| 20 | markdownBoldHTMLRegex = regexp.MustCompile(`\*\*(.+?)\*\*`) |
| 21 | markdownItalicStarHTMLRegex = regexp.MustCompile(`\*([^*].*?)\*`) |
| 22 | markdownItalicUnderHTMLRegex = regexp.MustCompile(`_([^_].*?)_`) |
| 23 | markdownStrongUnderHTMLRegex = regexp.MustCompile(`__(.+?)__`) |
| 24 | markdownCodeRegex = regexp.MustCompile("`(.+?)`") |
| 25 | markdownLinkRegex = regexp.MustCompile(`\[(.+?)\]\(.+?\)`) |
| 26 | markdownImageRegex = regexp.MustCompile(`!\[(.+?)\]\(.+?\)`) |
| 27 | markdownListRegex = regexp.MustCompile(`(?m)^\s*[-+*]\s+`) |
| 28 | markdownHRRegex = regexp.MustCompile(`(?m)^\s*[-*_]{3,}\s*$`) |
| 29 | htmlTagRegex = regexp.MustCompile(`<[^>]+>`) |
| 30 | mismatchedStrongEmRegex = regexp.MustCompile(`<strong><em>(.+?)</strong></em>`) |
| 31 | mismatchedEmStrongRegex = regexp.MustCompile(`<em><strong>(.+?)</em></strong>`) |
| 32 | ErrUnsupportedFormat = errors.New("unsupported format conversion") |
| 33 | ) |
| 34 | |
| 35 | // ConvertFormat converts a message body from one format to another. |
| 36 | // |
| 37 | // Supported formats: "text", "markdown", "html". |
| 38 | // Conversions: |
| 39 | // - markdown → text: strips markdown formatting, returns plain text |
| 40 | // - html → text: strips HTML tags, returns plain text |
| 41 | // - text → markdown: escapes special characters for safe markdown inclusion |
| 42 | // - text → html: escapes HTML entities |
| 43 | // - markdown → html: converts basic markdown to HTML |
| 44 | // - html → markdown: converts basic HTML to markdown |
| 45 | // - any → same format: returns body unchanged |
| 46 | // |
| 47 | // Parameters: |
| 48 | // - body: the message body to convert. |
| 49 | // - from: the source format. |
| 50 | // - targetFormat: the desired output format. |
| 51 | // |
| 52 | // Returns: |
| 53 | // - string: the converted body. |
| 54 | // - error: an error if the conversion is unsupported. |
| 55 | func ConvertFormat(body, from, targetFormat string) (string, error) { |
| 56 | if from == targetFormat { |
| 57 | return body, nil |
| 58 | } |
| 59 | |
| 60 | switch from { |
| 61 | case "markdown": |
| 62 | switch targetFormat { |
| 63 | case "text": |
| 64 | return markdownToText(body), nil |
| 65 | case "html": |
| 66 | return markdownToHTML(body), nil |
| 67 | } |
| 68 | case "html": |
| 69 | switch targetFormat { |
| 70 | case "text": |
| 71 | return htmlToText(body), nil |
| 72 | case "markdown": |
| 73 | return htmlToMarkdown(body), nil |
| 74 | } |
| 75 | case "text": |
| 76 | switch targetFormat { |
| 77 | case "markdown": |
| 78 | return textToMarkdown(body), nil |
| 79 | case "html": |
| 80 | return textToHTML(body), nil |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return "", fmt.Errorf("%w: %s → %s", ErrUnsupportedFormat, from, targetFormat) |
| 85 | } |
| 86 | |
| 87 | // markdownToText strips markdown formatting from the body and returns plain text. |
| 88 | // |
| 89 | // Parameters: |
| 90 | // - body: the markdown text. |
| 91 | // |
| 92 | // Returns: |
| 93 | // - string: the plain text. |
| 94 | func markdownToText(body string) string { |
| 95 | const ( |
| 96 | astPlaceholder = "\x00AST\x00" |
| 97 | undPlaceholder = "\x00UND\x00" |
| 98 | ) |
| 99 | |
| 100 | text := body |
| 101 | text = markdownHeadingRegex.ReplaceAllString(text, "") |
| 102 | text = strings.ReplaceAll(text, `\*`, astPlaceholder) |
| 103 | text = strings.ReplaceAll(text, `\_`, undPlaceholder) |
| 104 | text = markdownBoldRegex.ReplaceAllString(text, "$1") |
| 105 | text = markdownItalicRegex.ReplaceAllString(text, "$1") |
| 106 | text = markdownCodeRegex.ReplaceAllString(text, "$1") |
| 107 | text = markdownImageRegex.ReplaceAllString(text, "$1") |
| 108 | text = markdownLinkRegex.ReplaceAllString(text, "$1") |
| 109 | text = markdownListRegex.ReplaceAllString(text, "") |
| 110 | text = markdownHRRegex.ReplaceAllString(text, "") |
| 111 | text = strings.ReplaceAll(text, astPlaceholder, "*") |
| 112 | text = strings.ReplaceAll(text, undPlaceholder, "_") |
| 113 | text = strings.TrimSpace(text) |
| 114 | |
| 115 | return text |
| 116 | } |
| 117 | |
| 118 | // markdownToHTML converts basic markdown to HTML. |
| 119 | // |
| 120 | // Parameters: |
| 121 | // - body: the markdown text. |
| 122 | // |
| 123 | // Returns: |
| 124 | // - string: the HTML text. |
| 125 | func markdownToHTML(body string) string { |
| 126 | lines := strings.Split(body, "\n") |
| 127 | |
| 128 | var htmlBuilder strings.Builder |
| 129 | |
| 130 | for _, line := range lines { |
| 131 | trimmed := strings.TrimSpace(line) |
| 132 | if trimmed == "" { |
| 133 | htmlBuilder.WriteString("<br>") |
| 134 | |
| 135 | continue |
| 136 | } |
| 137 | |
| 138 | if strings.HasPrefix(trimmed, "#") { |
| 139 | level := 0 |
| 140 | |
| 141 | for _, c := range trimmed { |
| 142 | if c == '#' { |
| 143 | level++ |
| 144 | } else { |
| 145 | break |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | if level <= maxHeadingLevel && (level < len(trimmed) && unicode.IsSpace(rune(trimmed[level]))) { |
| 150 | htmlBuilder.WriteString("<h") |
| 151 | htmlBuilder.WriteString(strconv.Itoa(level)) |
| 152 | htmlBuilder.WriteString(">") |
| 153 | |
| 154 | text := strings.TrimSpace(trimmed[level:]) |
| 155 | text = applyInlineFormatting(text) |
| 156 | htmlBuilder.WriteString(text) |
| 157 | |
| 158 | htmlBuilder.WriteString("</h") |
| 159 | htmlBuilder.WriteString(strconv.Itoa(level)) |
| 160 | htmlBuilder.WriteString(">") |
| 161 | |
| 162 | continue |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | htmlBuilder.WriteString("<p>") |
| 167 | |
| 168 | text := trimmed |
| 169 | text = applyInlineFormatting(text) |
| 170 | htmlBuilder.WriteString(text) |
| 171 | htmlBuilder.WriteString("</p>") |
| 172 | } |
| 173 | |
| 174 | return htmlBuilder.String() |
| 175 | } |
| 176 | |
| 177 | // htmlToText strips HTML tags from the body and returns plain text. |
| 178 | // |
| 179 | // Parameters: |
| 180 | // - body: the HTML text. |
| 181 | // |
| 182 | // Returns: |
| 183 | // - string: the plain text. |
| 184 | func htmlToText(body string) string { |
| 185 | text := htmlTagRegex.ReplaceAllString(body, "") |
| 186 | text = html.UnescapeString(text) |
| 187 | text = strings.TrimSpace(text) |
| 188 | |
| 189 | return text |
| 190 | } |
| 191 | |
| 192 | // htmlToMarkdown converts basic HTML to markdown. |
| 193 | // |
| 194 | // Parameters: |
| 195 | // - body: the HTML text. |
| 196 | // |
| 197 | // Returns: |
| 198 | // - string: the markdown text. |
| 199 | func htmlToMarkdown(body string) string { |
| 200 | var lastHref string |
| 201 | |
| 202 | text := htmlTagRegex.ReplaceAllStringFunc(body, func(tag string) string { |
| 203 | lower := strings.ToLower(tag) |
| 204 | switch { |
| 205 | case strings.HasPrefix(lower, "<br"): |
| 206 | return "\n" |
| 207 | case lower == "</strong>", lower == "</b>": |
| 208 | return "**" |
| 209 | case lower == "</em>", lower == "</i>": |
| 210 | return "_" |
| 211 | case strings.HasPrefix(lower, "<h1"): |
| 212 | return "# " |
| 213 | case strings.HasPrefix(lower, "<h2"): |
| 214 | return "## " |
| 215 | case strings.HasPrefix(lower, "<h3"): |
| 216 | return "### " |
| 217 | case strings.HasPrefix(lower, "<h4"): |
| 218 | return "#### " |
| 219 | case strings.HasPrefix(lower, "<h5"): |
| 220 | return "##### " |
| 221 | case strings.HasPrefix(lower, "<h6"): |
| 222 | return "###### " |
| 223 | case strings.HasPrefix(lower, "<a") && (len(lower) > 2 && (lower[2] == ' ' || lower[2] == '>')): |
| 224 | if idx := strings.Index(lower, `href="`); idx != -1 { |
| 225 | start := idx + len(`href="`) |
| 226 | |
| 227 | end := strings.Index(lower[start:], `"`) |
| 228 | if end != -1 { |
| 229 | lastHref = tag[start : start+end] |
| 230 | } |
| 231 | } else if idx := strings.Index(lower, `href='`); idx != -1 { |
| 232 | start := idx + len(`href='`) |
| 233 | |
| 234 | end := strings.Index(lower[start:], `'`) |
| 235 | if end != -1 { |
| 236 | lastHref = tag[start : start+end] |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | return "[" |
| 241 | case lower == "</a>": |
| 242 | href := lastHref |
| 243 | lastHref = "" |
| 244 | |
| 245 | if href != "" { |
| 246 | return "](" + href + ")" |
| 247 | } |
| 248 | |
| 249 | return "]" |
| 250 | case strings.HasPrefix(lower, "<strong") && (len(lower) > 7 && (lower[7] == '>' || lower[7] == ' ')), |
| 251 | strings.HasPrefix(lower, "<b") && (len(lower) > 2 && (lower[2] == '>' || lower[2] == ' ')): |
| 252 | return "**" |
| 253 | case strings.HasPrefix(lower, "<em") && (len(lower) > 3 && (lower[3] == '>' || lower[3] == ' ')), |
| 254 | strings.HasPrefix(lower, "<i") && (len(lower) > 2 && (lower[2] == '>' || lower[2] == ' ')): |
| 255 | return "_" |
| 256 | case lower == "</p>": |
| 257 | return "\n\n" |
| 258 | case strings.HasPrefix(lower, "</h1"), strings.HasPrefix(lower, "</h2"), |
| 259 | strings.HasPrefix(lower, "</h3"), strings.HasPrefix(lower, "</h4"), |
| 260 | strings.HasPrefix(lower, "</h5"), strings.HasPrefix(lower, "</h6"): |
| 261 | return "\n" |
| 262 | case strings.HasPrefix(lower, "</"), strings.HasPrefix(lower, "<!"): |
| 263 | return "" |
| 264 | default: |
| 265 | return "" |
| 266 | } |
| 267 | }) |
| 268 | |
| 269 | text = strings.TrimSpace(text) |
| 270 | text = html.UnescapeString(text) |
| 271 | |
| 272 | return text |
| 273 | } |
| 274 | |
| 275 | // textToMarkdown escapes special characters in the body for safe markdown inclusion. |
| 276 | // |
| 277 | // Parameters: |
| 278 | // - body: the plain text. |
| 279 | // |
| 280 | // Returns: |
| 281 | // - string: the escaped markdown text. |
| 282 | func textToMarkdown(body string) string { |
| 283 | text := strings.ReplaceAll(body, "_", "\\_") |
| 284 | text = strings.ReplaceAll(text, "*", "\\*") |
| 285 | text = strings.ReplaceAll(text, "`", "\\`") |
| 286 | text = strings.ReplaceAll(text, "[", "\\[") |
| 287 | |
| 288 | return text |
| 289 | } |
| 290 | |
| 291 | // textToHTML escapes HTML entities in the body. |
| 292 | // |
| 293 | // Parameters: |
| 294 | // - body: the plain text. |
| 295 | // |
| 296 | // Returns: |
| 297 | // - string: the HTML-escaped text. |
| 298 | func textToHTML(body string) string { |
| 299 | return html.EscapeString(body) |
| 300 | } |
| 301 | |
| 302 | // applyInlineFormatting prepares text for emphasis conversion by protecting |
| 303 | // escaped delimiters, running emphasis conversion, then restoring literals. |
| 304 | // |
| 305 | // Parameters: |
| 306 | // - text: the markdown text. |
| 307 | // |
| 308 | // Returns: |
| 309 | // - string: the text with emphasis converted. |
| 310 | func applyInlineFormatting(text string) string { |
| 311 | text = html.EscapeString(text) |
| 312 | text = strings.ReplaceAll(text, `\*`, "\x00AST\x00") |
| 313 | text = strings.ReplaceAll(text, `\_`, "\x00UND\x00") |
| 314 | text = applyEmphasis(text) |
| 315 | text = strings.ReplaceAll(text, "\x00AST\x00", "*") |
| 316 | text = strings.ReplaceAll(text, "\x00UND\x00", "_") |
| 317 | |
| 318 | return text |
| 319 | } |
| 320 | |
| 321 | // applyEmphasis converts markdown emphasis markers to HTML tags. |
| 322 | // |
| 323 | // It iteratively applies bold then italic regex passes until stable, |
| 324 | // then fixes the two possible mismatched-nesting patterns that can |
| 325 | // arise when emphasis markers straddle inserted tags. |
| 326 | // |
| 327 | // Parameters: |
| 328 | // - text: the markdown text. |
| 329 | // |
| 330 | // Returns: |
| 331 | // - string: the HTML text with emphasis tags. |
| 332 | func applyEmphasis(text string) string { |
| 333 | text = strings.ReplaceAll(text, `\*`, "\x00AST\x00") |
| 334 | text = strings.ReplaceAll(text, `\_`, "\x00UND\x00") |
| 335 | |
| 336 | changed := true |
| 337 | for changed { |
| 338 | changed = false |
| 339 | |
| 340 | newText := markdownBoldHTMLRegex.ReplaceAllString(text, "<strong>$1</strong>") |
| 341 | if newText != text { |
| 342 | changed = true |
| 343 | text = newText |
| 344 | } |
| 345 | |
| 346 | newText = markdownItalicStarHTMLRegex.ReplaceAllString(text, "<em>$1</em>") |
| 347 | if newText != text { |
| 348 | changed = true |
| 349 | text = newText |
| 350 | } |
| 351 | |
| 352 | newText = markdownStrongUnderHTMLRegex.ReplaceAllString(text, "<strong>$1</strong>") |
| 353 | if newText != text { |
| 354 | changed = true |
| 355 | text = newText |
| 356 | } |
| 357 | |
| 358 | newText = markdownItalicUnderHTMLRegex.ReplaceAllString(text, "<em>$1</em>") |
| 359 | if newText != text { |
| 360 | changed = true |
| 361 | text = newText |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | text = strings.ReplaceAll(text, "\x00AST\x00", "*") |
| 366 | text = strings.ReplaceAll(text, "\x00UND\x00", "_") |
| 367 | |
| 368 | text = mismatchedStrongEmRegex.ReplaceAllString(text, `<strong><em>$1</em></strong>`) |
| 369 | text = mismatchedEmStrongRegex.ReplaceAllString(text, `<em><strong>$1</strong></em>`) |
| 370 | |
| 371 | return text |
| 372 | } |