package format import ( "errors" "fmt" "html" "regexp" "strconv" "strings" "unicode" ) // maxHeadingLevel is the maximum valid HTML heading level. const maxHeadingLevel = 6 var ( markdownHeadingRegex = regexp.MustCompile(`(?m)^#{1,6}\s+`) markdownBoldRegex = regexp.MustCompile(`\*{1,2}(.+?)\*{1,2}`) markdownItalicRegex = regexp.MustCompile(`_{1,2}(.+?)_{1,2}`) markdownBoldHTMLRegex = regexp.MustCompile(`\*\*(.+?)\*\*`) markdownItalicStarHTMLRegex = regexp.MustCompile(`\*([^*].*?)\*`) markdownItalicUnderHTMLRegex = regexp.MustCompile(`_([^_].*?)_`) markdownStrongUnderHTMLRegex = regexp.MustCompile(`__(.+?)__`) markdownCodeRegex = regexp.MustCompile("`(.+?)`") markdownLinkRegex = regexp.MustCompile(`\[(.+?)\]\(.+?\)`) markdownImageRegex = regexp.MustCompile(`!\[(.+?)\]\(.+?\)`) markdownListRegex = regexp.MustCompile(`(?m)^\s*[-+*]\s+`) markdownHRRegex = regexp.MustCompile(`(?m)^\s*[-*_]{3,}\s*$`) htmlTagRegex = regexp.MustCompile(`<[^>]+>`) mismatchedStrongEmRegex = regexp.MustCompile(`(.+?)`) mismatchedEmStrongRegex = regexp.MustCompile(`(.+?)`) ErrUnsupportedFormat = errors.New("unsupported format conversion") ) // ConvertFormat converts a message body from one format to another. // // Supported formats: "text", "markdown", "html". // Conversions: // - markdown → text: strips markdown formatting, returns plain text // - html → text: strips HTML tags, returns plain text // - text → markdown: escapes special characters for safe markdown inclusion // - text → html: escapes HTML entities // - markdown → html: converts basic markdown to HTML // - html → markdown: converts basic HTML to markdown // - any → same format: returns body unchanged // // Parameters: // - body: the message body to convert. // - from: the source format. // - targetFormat: the desired output format. // // Returns: // - string: the converted body. // - error: an error if the conversion is unsupported. func ConvertFormat(body, from, targetFormat string) (string, error) { if from == targetFormat { return body, nil } switch from { case "markdown": switch targetFormat { case "text": return markdownToText(body), nil case "html": return markdownToHTML(body), nil } case "html": switch targetFormat { case "text": return htmlToText(body), nil case "markdown": return htmlToMarkdown(body), nil } case "text": switch targetFormat { case "markdown": return textToMarkdown(body), nil case "html": return textToHTML(body), nil } } return "", fmt.Errorf("%w: %s → %s", ErrUnsupportedFormat, from, targetFormat) } // markdownToText strips markdown formatting from the body and returns plain text. // // Parameters: // - body: the markdown text. // // Returns: // - string: the plain text. func markdownToText(body string) string { const ( astPlaceholder = "\x00AST\x00" undPlaceholder = "\x00UND\x00" ) text := body text = markdownHeadingRegex.ReplaceAllString(text, "") text = strings.ReplaceAll(text, `\*`, astPlaceholder) text = strings.ReplaceAll(text, `\_`, undPlaceholder) text = markdownBoldRegex.ReplaceAllString(text, "$1") text = markdownItalicRegex.ReplaceAllString(text, "$1") text = markdownCodeRegex.ReplaceAllString(text, "$1") text = markdownImageRegex.ReplaceAllString(text, "$1") text = markdownLinkRegex.ReplaceAllString(text, "$1") text = markdownListRegex.ReplaceAllString(text, "") text = markdownHRRegex.ReplaceAllString(text, "") text = strings.ReplaceAll(text, astPlaceholder, "*") text = strings.ReplaceAll(text, undPlaceholder, "_") text = strings.TrimSpace(text) return text } // markdownToHTML converts basic markdown to HTML. // // Parameters: // - body: the markdown text. // // Returns: // - string: the HTML text. func markdownToHTML(body string) string { lines := strings.Split(body, "\n") var htmlBuilder strings.Builder for _, line := range lines { trimmed := strings.TrimSpace(line) if trimmed == "" { htmlBuilder.WriteString("
") continue } if strings.HasPrefix(trimmed, "#") { level := 0 for _, c := range trimmed { if c == '#' { level++ } else { break } } if level <= maxHeadingLevel && (level < len(trimmed) && unicode.IsSpace(rune(trimmed[level]))) { htmlBuilder.WriteString("") text := strings.TrimSpace(trimmed[level:]) text = applyInlineFormatting(text) htmlBuilder.WriteString(text) htmlBuilder.WriteString("") continue } } htmlBuilder.WriteString("

") text := trimmed text = applyInlineFormatting(text) htmlBuilder.WriteString(text) htmlBuilder.WriteString("

") } return htmlBuilder.String() } // htmlToText strips HTML tags from the body and returns plain text. // // Parameters: // - body: the HTML text. // // Returns: // - string: the plain text. func htmlToText(body string) string { text := htmlTagRegex.ReplaceAllString(body, "") text = html.UnescapeString(text) text = strings.TrimSpace(text) return text } // htmlToMarkdown converts basic HTML to markdown. // // Parameters: // - body: the HTML text. // // Returns: // - string: the markdown text. func htmlToMarkdown(body string) string { var lastHref string text := htmlTagRegex.ReplaceAllStringFunc(body, func(tag string) string { lower := strings.ToLower(tag) switch { case strings.HasPrefix(lower, "", lower == "": return "**" case lower == "", lower == "": return "_" case strings.HasPrefix(lower, " 2 && (lower[2] == ' ' || lower[2] == '>')): if idx := strings.Index(lower, `href="`); idx != -1 { start := idx + len(`href="`) end := strings.Index(lower[start:], `"`) if end != -1 { lastHref = tag[start : start+end] } } else if idx := strings.Index(lower, `href='`); idx != -1 { start := idx + len(`href='`) end := strings.Index(lower[start:], `'`) if end != -1 { lastHref = tag[start : start+end] } } return "[" case lower == "": href := lastHref lastHref = "" if href != "" { return "](" + href + ")" } return "]" case strings.HasPrefix(lower, " 7 && (lower[7] == '>' || lower[7] == ' ')), strings.HasPrefix(lower, " 2 && (lower[2] == '>' || lower[2] == ' ')): return "**" case strings.HasPrefix(lower, " 3 && (lower[3] == '>' || lower[3] == ' ')), strings.HasPrefix(lower, " 2 && (lower[2] == '>' || lower[2] == ' ')): return "_" case lower == "

": return "\n\n" case strings.HasPrefix(lower, "$1") if newText != text { changed = true text = newText } newText = markdownItalicStarHTMLRegex.ReplaceAllString(text, "$1") if newText != text { changed = true text = newText } newText = markdownStrongUnderHTMLRegex.ReplaceAllString(text, "$1") if newText != text { changed = true text = newText } newText = markdownItalicUnderHTMLRegex.ReplaceAllString(text, "$1") if newText != text { changed = true text = newText } } text = strings.ReplaceAll(text, "\x00AST\x00", "*") text = strings.ReplaceAll(text, "\x00UND\x00", "_") text = mismatchedStrongEmRegex.ReplaceAllString(text, `$1`) text = mismatchedEmStrongRegex.ReplaceAllString(text, `$1`) return text }