package modules import ( "regexp" "strings" "uberbringer/internal/pkg/receipt" ) // Line-level markdown: headings, bullet and numbered items, quotes, code // fences and thematic breaks. var ( mdHeading = regexp.MustCompile(`^\s{0,3}#{1,6}\s+(.*?)(\s+#+)?\s*$`) mdBreak = regexp.MustCompile(`^\s{0,3}([-*_])(\s*([-*_])){2,}\s*$`) mdBullet = regexp.MustCompile(`^\s*[-*+]\s+(\S.*)$`) mdNumbered = regexp.MustCompile(`^\s*\d{1,9}[.)]\s+(\S.*)$`) mdQuote = regexp.MustCompile(`^\s{0,3}>\s?(.*)$`) mdFence = regexp.MustCompile("^\\s{0,3}(```|~~~)") ) // Inline markdown, applied in this order: images, links, code spans and // bare URLs, which are kept as written, then emphasis and strikethrough. var ( mdImage = regexp.MustCompile(`!\[([^\]]*)\]\(([^)\s]*)(\s+"[^"]*")?\)`) mdLink = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)(\s+"[^"]*")?\)`) mdCode = regexp.MustCompile("`([^`]+)`") mdURL = regexp.MustCompile("\\b(?:https?|ftp)://[^\\s<>`\\x{E100}-\\x{E7FF}]+") mdStrong = regexp.MustCompile(`\*\*([^\s*](?:.*?[^\s*])?)\*\*`) mdStrongU = regexp.MustCompile(`\b__([^\s_](?:.*?[^\s_])?)__\b`) mdStrike = regexp.MustCompile(`~~([^\s~](?:.*?[^\s~])?)~~`) mdEmphasis = regexp.MustCompile(`\*([^\s*](?:[^*]*?[^\s*])?)\*`) mdEmphasisU = regexp.MustCompile(`(^|[^\pL\pN_])_([^\s_](?:[^_]*?[^\s_])?)_($|[^\pL\pN_])`) mdEscape = regexp.MustCompile("\\\\([\\\\`*_{}\\[\\]()#+\\-.!>~|])") ) // escapeBase is where markdownInline sets aside escaped ASCII characters, // in the private use area: '*' is escapeBase+'*'. keptBase is where it // numbers the code spans and URLs it keeps as written, up to maxKept. const ( escapeBase = rune(0xE000) keptBase = rune(0xE100) maxKept = 0x700 ) // markdownBody lays out text written in a subset of markdown as elements // that fit inside a box as well as on their own: // // - #, ## and ### headings print as bold lines; // - -, * and + items as a dot list, and 1. items as a numbered list; // - > quotes with "│ " in front; // - lines between ``` fences as written; // - --- as a divider; // - **bold**, __bold__, *italic*, _italic_, `code` and ~~struck~~ text // without the marks; // - [text](url) as its text, with url added to links; // - ![alt](url) as [image: alt]. // // Every other line prints as written, and a run of empty lines as one. func markdownBody(text string) (elements []receipt.Element, links []Link) { var ( para []string list *receipt.Element fence []string inFence bool blankRun bool ) flushPara := func() { if len(para) > 0 { elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(para, "\n")}) para = nil } } flushList := func() { if list != nil { elements = append(elements, *list) list = nil } } flush := func() { flushPara() flushList() } inline := func(s string) string { s, found := markdownInline(s) links = append(links, found...) return s } addItem := func(bullet, item string) { item = inline(item) if strings.TrimSpace(item) == "" { return } if list != nil && (list.Bullet != bullet || len(list.Items) == receipt.MaxItems) { flushList() } flushPara() if list == nil { list = &receipt.Element{Type: receipt.TypeList, Bullet: bullet} } list.Items = append(list.Items, item) } for _, line := range strings.Split(text, "\n") { if inFence { if mdFence.MatchString(line) { inFence = false elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(fence, "\n"), Wrap: boolPtr(false)}) fence = nil continue } fence = append(fence, line) continue } if strings.TrimSpace(line) == "" { flush() if !blankRun && len(elements) > 0 { elements = append(elements, receipt.Element{Type: receipt.TypeFeed}) } blankRun = true continue } blankRun = false switch { case mdFence.MatchString(line): flush() inFence = true case mdBreak.MatchString(line): flush() elements = append(elements, receipt.Element{Type: receipt.TypeRule}) case mdHeading.MatchString(line): flush() heading := inline(mdHeading.FindStringSubmatch(line)[1]) elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: heading, Bold: true}) case mdBullet.MatchString(line): addItem("dot", mdBullet.FindStringSubmatch(line)[1]) case mdNumbered.MatchString(line): addItem("number", mdNumbered.FindStringSubmatch(line)[1]) case mdQuote.MatchString(line): flushList() para = append(para, "│ "+inline(mdQuote.FindStringSubmatch(line)[1])) default: flushList() para = append(para, inline(line)) } } if inFence && len(fence) > 0 { elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: strings.Join(fence, "\n"), Wrap: boolPtr(false)}) } flush() // A trailing empty line prints nothing useful. for len(elements) > 0 && elements[len(elements)-1].Type == receipt.TypeFeed { elements = elements[:len(elements)-1] } return elements, links } // markdownInline removes the inline marks from s and returns the http and // https links it names. func markdownInline(s string) (string, []Link) { // The characters that number what is kept as written are dropped from // the text first, so that none is taken for a number; no code page // prints them. s = strings.Map(func(r rune) rune { if r >= keptBase && r < keptBase+maxKept { return -1 } return r }, s) // Escaped characters are set aside, so that they are not read as marks. s = mdEscape.ReplaceAllStringFunc(s, func(m string) string { return string(escapeBase + rune(m[1])) }) s = mdImage.ReplaceAllStringFunc(s, func(m string) string { alt := strings.TrimSpace(mdImage.FindStringSubmatch(m)[1]) if alt == "" { return "[image]" } return "[image: " + alt + "]" }) var links []Link s = mdLink.ReplaceAllStringFunc(s, func(m string) string { parts := mdLink.FindStringSubmatch(m) text, target := parts[1], parts[2] if webURL(target) { links = append(links, Link{Label: restoreEscapes(text), URL: target}) } return text }) // Code spans, without their backticks, and bare URLs are set aside, // so that marks inside them, as in __init__.py, print as written. var kept []string keep := func(text string) string { if len(kept) == maxKept { return text } kept = append(kept, text) return string(keptBase + rune(len(kept)-1)) } s = mdCode.ReplaceAllStringFunc(s, func(m string) string { return keep(m[1 : len(m)-1]) }) s = mdURL.ReplaceAllStringFunc(s, func(m string) string { url, rest := trimURL(m) return keep(url) + rest }) s = mdStrong.ReplaceAllString(s, "$1") s = mdStrongU.ReplaceAllString(s, "$1") s = mdStrike.ReplaceAllString(s, "$1") s = mdEmphasis.ReplaceAllString(s, "$1") // Twice: a match takes the character after it, which the next one // may need before it. for range 2 { s = mdEmphasisU.ReplaceAllString(s, "$1$2$3") } return restoreEscapes(restoreKept(s, kept)), links } // trimURL splits the punctuation that ends a sentence, or closes emphasis, // off the end of a bare URL, as GitHub's autolinks do: trailing . , : ; ! // ? ' " _ * and ~, and a ) that has no ( in the URL to close. The same // marks inside the URL stay part of it. It returns the URL and what // followed it. func trimURL(m string) (url, rest string) { url = m for url != "" { last := url[len(url)-1] switch { case strings.IndexByte(".,:;!?'\"_*~", last) >= 0: case last == ')' && strings.Count(url, ")") > strings.Count(url, "("): default: return url, m[len(url):] } url = url[:len(url)-1] } return url, m } // restoreKept puts back the code spans and URLs markdownInline set aside // in kept. func restoreKept(s string, kept []string) string { if len(kept) == 0 { return s } var b strings.Builder for _, r := range s { if i := int(r - keptBase); r >= keptBase && i < len(kept) { b.WriteString(kept[i]) continue } b.WriteRune(r) } return b.String() } // restoreEscapes puts back the characters markdownInline set aside. func restoreEscapes(s string) string { return strings.Map(func(r rune) rune { if r >= escapeBase && r < escapeBase+0x80 { return r - escapeBase } return r }, s) } func boolPtr(b bool) *bool { return &b }