10 // telegramMarkdownPunctuation holds the ASCII characters that a backslash makes
12 const telegramMarkdownPunctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
15 // telegramTagEscaper writes the characters that rich Markdown reads as HTML
17 telegramTagEscaper = strings.NewReplacer("&", "&", "<", "<")
19 // telegramTagUnescaper reverses telegramTagEscaper.
20 telegramTagUnescaper = strings.NewReplacer("&", "&", "<", "<")
23 // telegramMarkdownEntities converts the Markdown of a reply to plain text and
24 // Telegram message entities. It knows bold (** and __), italic (* and _),
25 // strikethrough (~~), inline code, fenced code blocks with an optional
26 // language, links [text](url), and ATX headings, which become bold. Lists,
27 // quotes, and tables stay as their text. A mark that does not close stays as
28 // text with no entity, and code holds no entity.
30 // Inline marks do not cross a line break, so a mark that does not close cannot
31 // change the rest of the reply.
32 func telegramMarkdownEntities(markdown string) (string, []TelegramEntity) {
33 var out TelegramMarkdownText
34 lines := strings.Split(markdown, "\n")
35 for index := 0; index < len(lines); index++ {
41 language, fence := telegramCodeFence(line)
42 end := telegramClosingFence(lines, index, fence)
43 heading := telegramHeadingText(line)
47 out.add(strings.Join(lines[index+1:end], "\n"))
48 out.entity(TelegramEntity{
51 Length: out.units - start,
59 out.entity(TelegramEntity{
62 Length: out.units - start,
69 slices.SortStableFunc(out.entities, func(a, b TelegramEntity) int {
70 if a.Offset != b.Offset {
71 return a.Offset - b.Offset
74 return b.Length - a.Length
77 return out.text.String(), out.entities
80 // telegramEscapeTags writes each & of markdown outside inline code and fenced
81 // code blocks as & and each < as <. Rich Markdown reads raw HTML and
82 // HTML entities in prose, and it does not read a backslash before < as an
83 // escape. With the entities, it shows a tag name and an entity that the model
84 // wrote in prose as text.
85 func telegramEscapeTags(markdown string) string {
86 return telegramRewriteProse(markdown, telegramTagEscaper.Replace)
89 // telegramUnescapeTags gives back the Markdown that telegramEscapeTags escaped.
90 // It is exact, because after the escape each & outside code starts & or
91 // <. It also works on a part of telegramSplitRich, because a part has the
92 // same code as the text that it comes from.
93 func telegramUnescapeTags(markdown string) string {
94 return telegramRewriteProse(markdown, telegramTagUnescaper.Replace)
97 // telegramCodeFence returns the language of a line that opens a fenced code
98 // block, and the fence. The fence is "" when line does not open a block.
99 func telegramCodeFence(line string) (string, string) {
100 trimmed := strings.TrimLeft(line, " ")
101 if len(line)-len(trimmed) > 3 || !strings.HasPrefix(trimmed, "```") {
105 run := len(trimmed) - len(strings.TrimLeft(trimmed, "`"))
106 info := strings.TrimSpace(trimmed[run:])
107 if strings.Contains(info, "`") {
111 language, _, _ := strings.Cut(info, " ")
113 return language, trimmed[:run]
116 // telegramClosesFence tells if line closes the code block of fence.
117 func telegramClosesFence(line, fence string) bool {
118 trimmed := strings.TrimSpace(line)
119 return strings.HasPrefix(trimmed, fence) && strings.Trim(trimmed, "`") == ""
122 // telegramUTF16Units returns the number of UTF-16 code units of text.
123 func telegramUTF16Units(text string) int {
125 for _, char := range text {
135 // TelegramMarkdownText is the plain text of a Markdown reply and its Telegram
136 // entities, while the conversion builds it. Units counts the UTF-16 code units
137 // of text, the unit of the entity offsets and lengths.
138 type TelegramMarkdownText struct {
141 entities []TelegramEntity
145 func (m *TelegramMarkdownText) add(text string) {
146 m.text.WriteString(text)
147 m.units += telegramUTF16Units(text)
150 // entity keeps entity, unless it is empty, because Telegram refuses an entity
152 func (m *TelegramMarkdownText) entity(entity TelegramEntity) {
153 if entity.Length > 0 {
154 m.entities = append(m.entities, entity)
158 // inline appends one line of Markdown with its inline marks as entities. A
159 // backslash before an ASCII punctuation character makes the character plain
161 func (m *TelegramMarkdownText) inline(line string) {
164 for index < len(line) {
165 if line[index] == '\\' && index+1 < len(line) && strings.IndexByte(telegramMarkdownPunctuation, line[index+1]) >= 0 {
166 m.add(line[plain:index])
173 span, found := telegramMarkSpan(line, index)
179 m.add(line[plain:index])
181 if span.kind == "code" {
184 m.inline(span.content)
187 m.entity(TelegramEntity{
190 Length: m.units - start,
201 // TelegramMarkdownSpan is an inline mark of a line: the entity type, the
202 // content inside the marks, the index after the closing mark, and the URL of a
204 type TelegramMarkdownSpan struct {
211 // telegramClosingFence returns the index of the line after index that closes
212 // the code block of fence, or -1 when fence is "" or no line closes it.
213 func telegramClosingFence(lines []string, index int, fence string) int {
218 for end := index + 1; end < len(lines); end++ {
219 if telegramClosesFence(lines[end], fence) {
227 // telegramHeadingText returns the text of an ATX heading line without its
228 // marks, or "" when line is not a heading or has no text.
229 func telegramHeadingText(line string) string {
230 trimmed := strings.TrimLeft(line, " ")
231 if len(line)-len(trimmed) > 3 {
235 level := len(trimmed) - len(strings.TrimLeft(trimmed, "#"))
236 if level == 0 || level > 6 {
240 rest := trimmed[level:]
241 if rest != "" && rest[0] != ' ' && rest[0] != '\t' {
245 rest = strings.TrimSpace(rest)
246 closed := strings.TrimRight(rest, "#")
247 if closed == "" || strings.HasSuffix(closed, " ") {
248 rest = strings.TrimSpace(closed)
254 // telegramRewriteProse returns markdown with rewrite applied to each part of a
255 // line outside inline code and fenced code blocks. A code block that does not
256 // close runs to the end, as in Markdown.
257 func telegramRewriteProse(markdown string, rewrite func(string) string) string {
258 var out strings.Builder
259 lines := strings.Split(markdown, "\n")
260 for index := 0; index < len(lines); index++ {
262 out.WriteString("\n")
266 _, fence := telegramCodeFence(line)
268 telegramRewriteLineProse(&out, line, rewrite)
272 end := telegramClosingFence(lines, index, fence)
277 out.WriteString(strings.Join(lines[index:end+1], "\n"))
284 // telegramRewriteLineProse writes line to out with rewrite applied to each part
285 // outside inline code. A backtick after a backslash opens no code. A run of
286 // backticks that opens no inline code stays as text whole, as in Markdown.
287 func telegramRewriteLineProse(out *strings.Builder, line string, rewrite func(string) string) {
289 for index := 0; index < len(line); {
292 if index+1 < len(line) && strings.IndexByte(telegramMarkdownPunctuation, line[index+1]) >= 0 {
297 end := index + telegramBackticks(line[index:])
298 span, found := telegramCodeSpan(line, index)
303 out.WriteString(rewrite(line[prose:index]))
304 out.WriteString(line[index:end])
314 out.WriteString(rewrite(line[prose:]))
317 // telegramMarkSpan returns the inline mark that starts at index of line and
318 // closes in line. It returns false when no mark starts there or the mark does
320 func telegramMarkSpan(line string, index int) (TelegramMarkdownSpan, bool) {
323 return telegramCodeSpan(line, index)
325 return telegramLinkSpan(line, index)
327 return telegramDelimited(line, index, "~~", "strikethrough")
329 double := line[index : index+1]
331 span, found := telegramDelimited(line, index, double, "bold")
336 return telegramDelimited(line, index, line[index:index+1], "italic")
338 return TelegramMarkdownSpan{}, false
342 // telegramCodeSpan returns the inline code that starts at index: a run of
343 // backticks, the code, and a run of the same length. One space on each side of
344 // the code is left out, as in Markdown.
345 func telegramCodeSpan(line string, index int) (TelegramMarkdownSpan, bool) {
346 run := telegramBackticks(line[index:])
347 for search := index + run; search < len(line); {
348 next := strings.IndexByte(line[search:], '`')
354 length := telegramBackticks(line[next:])
356 search = next + length
360 content := line[index+run : next]
361 if strings.TrimSpace(content) == "" {
365 if len(content) > 1 && content[0] == ' ' && content[len(content)-1] == ' ' {
366 content = content[1 : len(content)-1]
369 return TelegramMarkdownSpan{
376 return TelegramMarkdownSpan{}, false
379 // telegramLinkSpan returns the link [text](url) that starts at index. The text
380 // can hold brackets in pairs, and the URL holds no space.
381 func telegramLinkSpan(line string, index int) (TelegramMarkdownSpan, bool) {
383 for closing := index; closing < len(line); closing++ {
384 switch line[closing] {
397 rest := line[closing+1:]
398 if closing == index+1 || !strings.HasPrefix(rest, "(") {
399 return TelegramMarkdownSpan{}, false
402 url, _, found := strings.Cut(rest[1:], ")")
403 if !found || url == "" || strings.ContainsAny(url, " \t") {
404 return TelegramMarkdownSpan{}, false
407 return TelegramMarkdownSpan{
409 content: line[index+1 : closing],
410 end: closing + 2 + len(url) + 1,
415 return TelegramMarkdownSpan{}, false
418 // telegramDelimited returns the span of kind between the mark at index and the
419 // same mark later in line. An opening mark is followed by a character that is
420 // not a space, and a closing mark follows one. A single mark is not a part of a
421 // double one. A mark of underscores does not open or close inside a word, so
422 // snake_case stays as text. A code span inside the content is skipped whole.
423 func telegramDelimited(line string, index int, mark, kind string) (TelegramMarkdownSpan, bool) {
425 after := index + len(mark)
426 if !strings.HasPrefix(line[index:], mark) || after >= len(line) || telegramIsSpace(line[after]) {
427 return TelegramMarkdownSpan{}, false
430 if len(mark) == 1 && (line[after] == char || index > 0 && line[index-1] == char) {
431 return TelegramMarkdownSpan{}, false
434 if char == '_' && index > 0 && telegramWordCharBefore(line[:index]) {
435 return TelegramMarkdownSpan{}, false
438 for closing := after + 1; closing < len(line); closing++ {
440 case line[closing] == '\\':
443 case line[closing] == '`':
444 span, found := telegramCodeSpan(line, closing)
446 closing = span.end - 1
450 case !strings.HasPrefix(line[closing:], mark) || telegramIsSpace(line[closing-1]):
454 end := closing + len(mark)
455 if len(mark) == 1 && (line[closing-1] == char || end < len(line) && line[end] == char) {
459 if char == '_' && telegramWordChar(line[end:]) {
463 return TelegramMarkdownSpan{
465 content: line[after:closing],
470 return TelegramMarkdownSpan{}, false
473 // telegramBackticks returns the length of the run of backticks at the start of
475 func telegramBackticks(text string) int {
476 return len(text) - len(strings.TrimLeft(text, "`"))
479 // telegramIsSpace tells if char is a space, a tab, or a line break.
480 func telegramIsSpace(char byte) bool {
481 return char == ' ' || char == '\t' || char == '\n' || char == '\r'
484 // telegramWordCharBefore tells if the character that ends text is a letter or a
486 func telegramWordCharBefore(text string) bool {
487 char, _ := utf8.DecodeLastRuneInString(text)
488 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))
491 // telegramWordChar tells if the character that starts text is a letter or a
492 // digit. An underscore next to one is a part of a word, such as in snake_case.
493 func telegramWordChar(text string) bool {
494 char, _ := utf8.DecodeRuneInString(text)
495 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))