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 := 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, "