10 // markdownPunctuation holds the ASCII characters that a backslash makes plain.
11 const markdownPunctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
13 // markdownText is the plain text of a Markdown reply and its Telegram entities,
14 // while the conversion builds it. Units counts the UTF-16 code units of text,
15 // the unit of the entity offsets and lengths.
16 type markdownText struct {
22 // markdownSpan is an inline mark of a line: the entity type, the content inside
23 // the marks, the index after the closing mark, and the URL of a link.
24 type markdownSpan struct {
31 // markdownEntities converts the Markdown of a reply to plain text and Telegram
32 // message entities. It knows bold (** and __), italic (* and _),
33 // strikethrough (~~), inline code, fenced code blocks with an optional
34 // language, links [text](url), and ATX headings, which become bold. Lists,
35 // quotes, and tables stay as their text. A mark that does not close stays as
36 // text with no entity, and code holds no entity.
38 // Inline marks do not cross a line break, so a mark that does not close cannot
39 // change the rest of the reply.
40 func markdownEntities(markdown string) (string, []botEntity) {
42 lines := strings.Split(markdown, "\n")
43 for index := 0; index < len(lines); index++ {
49 language, fence := codeFence(line)
50 end := closingFence(lines, index, fence)
51 heading := headingText(line)
55 out.add(strings.Join(lines[index+1:end], "\n"))
59 Length: out.units - start,
70 Length: out.units - start,
77 slices.SortStableFunc(out.entities, func(a, b botEntity) int {
78 if a.Offset != b.Offset {
79 return a.Offset - b.Offset
82 return b.Length - a.Length
85 return out.text.String(), out.entities
89 func (m *markdownText) add(text string) {
90 m.text.WriteString(text)
91 m.units += utf16Units(text)
94 // entity keeps entity, unless it is empty, because Telegram refuses an entity
96 func (m *markdownText) entity(entity botEntity) {
97 if entity.Length > 0 {
98 m.entities = append(m.entities, entity)
102 // inline appends one line of Markdown with its inline marks as entities. A
103 // backslash before an ASCII punctuation character makes the character plain
105 func (m *markdownText) inline(line string) {
108 for index < len(line) {
109 if line[index] == '\\' && index+1 < len(line) && strings.IndexByte(markdownPunctuation, line[index+1]) >= 0 {
110 m.add(line[plain:index])
117 span, found := markSpan(line, index)
123 m.add(line[plain:index])
125 if span.kind == "code" {
128 m.inline(span.content)
134 Length: m.units - start,
145 // codeFence returns the language of a line that opens a fenced code block, and
146 // the fence. The fence is "" when line does not open a block.
147 func codeFence(line string) (string, string) {
148 trimmed := strings.TrimLeft(line, " ")
149 if len(line)-len(trimmed) > 3 || !strings.HasPrefix(trimmed, "```") {
153 run := len(trimmed) - len(strings.TrimLeft(trimmed, "`"))
154 info := strings.TrimSpace(trimmed[run:])
155 if strings.Contains(info, "`") {
159 language, _, _ := strings.Cut(info, " ")
161 return language, trimmed[:run]
164 // closingFence returns the index of the line after index that closes the code
165 // block of fence, or -1 when fence is "" or no line closes it.
166 func closingFence(lines []string, index int, fence string) int {
171 for end := index + 1; end < len(lines); end++ {
172 if closesFence(lines[end], fence) {
180 // closesFence tells if line closes the code block of fence.
181 func closesFence(line, fence string) bool {
182 trimmed := strings.TrimSpace(line)
183 return strings.HasPrefix(trimmed, fence) && strings.Trim(trimmed, "`") == ""
186 // headingText returns the text of an ATX heading line without its marks, or ""
187 // when line is not a heading or has no text.
188 func headingText(line string) string {
189 trimmed := strings.TrimLeft(line, " ")
190 if len(line)-len(trimmed) > 3 {
194 level := len(trimmed) - len(strings.TrimLeft(trimmed, "#"))
195 if level == 0 || level > 6 {
199 rest := trimmed[level:]
200 if rest != "" && rest[0] != ' ' && rest[0] != '\t' {
204 rest = strings.TrimSpace(rest)
205 closed := strings.TrimRight(rest, "#")
206 if closed == "" || strings.HasSuffix(closed, " ") {
207 rest = strings.TrimSpace(closed)
213 // utf16Units returns the number of UTF-16 code units of text.
214 func utf16Units(text string) int {
216 for _, char := range text {
226 // markSpan returns the inline mark that starts at index of line and closes in
227 // line. It returns false when no mark starts there or the mark does not close.
228 func markSpan(line string, index int) (markdownSpan, bool) {
231 return codeSpan(line, index)
233 return linkSpan(line, index)
235 return delimited(line, index, "~~", "strikethrough")
237 double := line[index : index+1]
239 span, found := delimited(line, index, double, "bold")
244 return delimited(line, index, line[index:index+1], "italic")
246 return markdownSpan{}, false
250 // codeSpan returns the inline code that starts at index: a run of backticks,
251 // the code, and a run of the same length. One space on each side of the code
252 // is left out, as in Markdown.
253 func codeSpan(line string, index int) (markdownSpan, bool) {
254 run := backticks(line[index:])
255 for search := index + run; search < len(line); {
256 next := strings.IndexByte(line[search:], '`')
262 length := backticks(line[next:])
264 search = next + length
268 content := line[index+run : next]
269 if strings.TrimSpace(content) == "" {
273 if len(content) > 1 && content[0] == ' ' && content[len(content)-1] == ' ' {
274 content = content[1 : len(content)-1]
284 return markdownSpan{}, false
287 // linkSpan returns the link [text](url) that starts at index. The text can
288 // hold brackets in pairs, and the URL holds no space.
289 func linkSpan(line string, index int) (markdownSpan, bool) {
291 for closing := index; closing < len(line); closing++ {
292 switch line[closing] {
305 rest := line[closing+1:]
306 if closing == index+1 || !strings.HasPrefix(rest, "(") {
307 return markdownSpan{}, false
310 url, _, found := strings.Cut(rest[1:], ")")
311 if !found || url == "" || strings.ContainsAny(url, " \t") {
312 return markdownSpan{}, false
317 content: line[index+1 : closing],
318 end: closing + 2 + len(url) + 1,
323 return markdownSpan{}, false
326 // delimited returns the span of kind between the mark at index and the same
327 // mark later in line. An opening mark is followed by a character that is not a
328 // space, and a closing mark follows one. A single mark is not a part of a
329 // double one. A mark of underscores does not open or close inside a word, so
330 // snake_case stays as text. A code span inside the content is skipped whole.
331 func delimited(line string, index int, mark, kind string) (markdownSpan, bool) {
333 after := index + len(mark)
334 if !strings.HasPrefix(line[index:], mark) || after >= len(line) || isSpace(line[after]) {
335 return markdownSpan{}, false
338 if len(mark) == 1 && (line[after] == char || index > 0 && line[index-1] == char) {
339 return markdownSpan{}, false
342 if char == '_' && index > 0 && wordCharBefore(line[:index]) {
343 return markdownSpan{}, false
346 for closing := after + 1; closing < len(line); closing++ {
348 case line[closing] == '\\':
351 case line[closing] == '`':
352 span, found := codeSpan(line, closing)
354 closing = span.end - 1
358 case !strings.HasPrefix(line[closing:], mark) || isSpace(line[closing-1]):
362 end := closing + len(mark)
363 if len(mark) == 1 && (line[closing-1] == char || end < len(line) && line[end] == char) {
367 if char == '_' && wordChar(line[end:]) {
373 content: line[after:closing],
378 return markdownSpan{}, false
381 // backticks returns the length of the run of backticks at the start of text.
382 func backticks(text string) int {
383 return len(text) - len(strings.TrimLeft(text, "`"))
386 // isSpace tells if char is a space, a tab, or a line break.
387 func isSpace(char byte) bool {
388 return char == ' ' || char == '\t' || char == '\n' || char == '\r'
391 // wordCharBefore tells if the character that ends text is a letter or a digit.
392 func wordCharBefore(text string) bool {
393 char, _ := utf8.DecodeLastRuneInString(text)
394 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))
397 // wordChar tells if the character that starts text is a letter or a digit. An
398 // underscore next to one is a part of a word, such as in snake_case.
399 func wordChar(text string) bool {
400 char, _ := utf8.DecodeRuneInString(text)
401 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))