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
35 lines := strings.Split(markdown, "\n")
36 for index := 0; index < len(lines); index++ {
42 language, fence := telegramCodeFence(line)
43 end := telegramClosingFence(lines, index, fence)
44 heading := telegramHeadingText(line)
48 out.add(strings.Join(lines[index+1:end], "\n"))
49 out.entity(TelegramEntity{
52 Length: out.units - start,
60 out.entity(TelegramEntity{
63 Length: out.units - start,
70 slices.SortStableFunc(out.entities, func(a, b TelegramEntity) int {
71 if a.Offset != b.Offset {
72 return a.Offset - b.Offset
75 return b.Length - a.Length
78 return out.text.String(), out.entities
81 // telegramEscapeTags writes each & of markdown outside inline code and fenced
82 // code blocks as & and each < as <. Rich Markdown reads raw HTML and
83 // HTML entities in prose, and it does not read a backslash before < as an
84 // escape. With the entities, it shows a tag name and an entity that the model
85 // wrote in prose as text.
86 func telegramEscapeTags(markdown string) string {
87 return telegramRewriteProse(markdown, telegramTagEscaper.Replace)
90 // telegramUnescapeTags gives back the Markdown that telegramEscapeTags escaped.
91 // It is exact, because after the escape each & outside code starts & or
92 // <. It also works on a part of telegramSplitRich, because a part has the
93 // same code as the text that it comes from.
94 func telegramUnescapeTags(markdown string) string {
95 return telegramRewriteProse(markdown, telegramTagUnescaper.Replace)
98 // telegramCodeFence returns the language of a line that opens a fenced code
99 // block, and the fence. The fence is "" when line does not open a block.
100 func telegramCodeFence(line string) (string, string) {
101 trimmed := strings.TrimLeft(line, " ")
102 if len(line)-len(trimmed) > 3 || !strings.HasPrefix(trimmed, "```") {
106 run := len(trimmed) - len(strings.TrimLeft(trimmed, "`"))
107 info := strings.TrimSpace(trimmed[run:])
108 if strings.Contains(info, "`") {
112 language, _, _ := strings.Cut(info, " ")
114 return language, trimmed[:run]
117 // telegramClosesFence tells if line closes the code block of fence.
118 func telegramClosesFence(line, fence string) bool {
119 trimmed := strings.TrimSpace(line)
120 return strings.HasPrefix(trimmed, fence) && strings.Trim(trimmed, "`") == ""
123 // telegramUTF16Units returns the number of UTF-16 code units of text.
124 func telegramUTF16Units(text string) int {
126 for _, char := range text {
136 // TelegramMarkdownText is the plain text of a Markdown reply and its Telegram
137 // entities, while the conversion builds it. Units counts the UTF-16 code units
138 // of text, the unit of the entity offsets and lengths.
139 type TelegramMarkdownText struct {
142 entities []TelegramEntity
146 func (m *TelegramMarkdownText) add(text string) {
147 m.text.WriteString(text)
149 m.units += telegramUTF16Units(text)
152 // entity keeps entity, unless it is empty, because Telegram refuses an entity
154 func (m *TelegramMarkdownText) entity(entity TelegramEntity) {
155 if entity.Length > 0 {
156 m.entities = append(m.entities, entity)
160 // inline appends one line of Markdown with its inline marks as entities. A
161 // backslash before an ASCII punctuation character makes the character plain
163 func (m *TelegramMarkdownText) inline(line string) {
166 for index < len(line) {
167 if line[index] == '\\' && index+1 < len(line) && strings.IndexByte(telegramMarkdownPunctuation, line[index+1]) >= 0 {
168 m.add(line[plain:index])
176 span, found := telegramMarkSpan(line, index)
182 m.add(line[plain:index])
185 if span.kind == "code" {
188 m.inline(span.content)
191 m.entity(TelegramEntity{
194 Length: m.units - start,
205 // TelegramMarkdownSpan is an inline mark of a line: the entity type, the
206 // content inside the marks, the index after the closing mark, and the URL of a
208 type TelegramMarkdownSpan struct {
215 // telegramClosingFence returns the index of the line after index that closes
216 // the code block of fence, or -1 when fence is "" or no line closes it.
217 func telegramClosingFence(lines []string, index int, fence string) int {
222 for end := index + 1; end < len(lines); end++ {
223 if telegramClosesFence(lines[end], fence) {
231 // telegramHeadingText returns the text of an ATX heading line without its
232 // marks, or "" when line is not a heading or has no text.
233 func telegramHeadingText(line string) string {
234 trimmed := strings.TrimLeft(line, " ")
235 if len(line)-len(trimmed) > 3 {
239 level := len(trimmed) - len(strings.TrimLeft(trimmed, "#"))
240 if level == 0 || level > 6 {
244 rest := trimmed[level:]
245 if rest != "" && rest[0] != ' ' && rest[0] != '\t' {
249 rest = strings.TrimSpace(rest)
250 closed := strings.TrimRight(rest, "#")
251 if closed == "" || strings.HasSuffix(closed, " ") {
252 rest = strings.TrimSpace(closed)
258 // telegramRewriteProse returns markdown with rewrite applied to each part of a
259 // line outside inline code and fenced code blocks. A code block that does not
260 // close runs to the end, as in Markdown.
261 func telegramRewriteProse(markdown string, rewrite func(string) string) string {
262 var out strings.Builder
264 lines := strings.Split(markdown, "\n")
265 for index := 0; index < len(lines); index++ {
267 out.WriteString("\n")
271 _, fence := telegramCodeFence(line)
273 telegramRewriteLineProse(&out, line, rewrite)
278 end := telegramClosingFence(lines, index, fence)
283 out.WriteString(strings.Join(lines[index:end+1], "\n"))
291 // telegramRewriteLineProse writes line to out with rewrite applied to each part
292 // outside inline code. A backtick after a backslash opens no code. A run of
293 // backticks that opens no inline code stays as text whole, as in Markdown.
294 func telegramRewriteLineProse(out *strings.Builder, line string, rewrite func(string) string) {
296 for index := 0; index < len(line); {
299 if index+1 < len(line) && strings.IndexByte(telegramMarkdownPunctuation, line[index+1]) >= 0 {
304 end := index + telegramBackticks(line[index:])
305 span, found := telegramCodeSpan(line, index)
310 out.WriteString(rewrite(line[prose:index]))
311 out.WriteString(line[index:end])
322 out.WriteString(rewrite(line[prose:]))
325 // telegramMarkSpan returns the inline mark that starts at index of line and
326 // closes in line. It returns false when no mark starts there or the mark does
328 func telegramMarkSpan(line string, index int) (TelegramMarkdownSpan, bool) {
331 return telegramCodeSpan(line, index)
333 return telegramLinkSpan(line, index)
335 return telegramDelimited(line, index, "~~", "strikethrough")
337 double := line[index : index+1]
339 span, found := telegramDelimited(line, index, double, "bold")
344 return telegramDelimited(line, index, line[index:index+1], "italic")
346 return TelegramMarkdownSpan{}, false
350 // telegramCodeSpan returns the inline code that starts at index: a run of
351 // backticks, the code, and a run of the same length. One space on each side of
352 // the code is left out, as in Markdown.
353 func telegramCodeSpan(line string, index int) (TelegramMarkdownSpan, bool) {
354 run := telegramBackticks(line[index:])
355 for search := index + run; search < len(line); {
356 next := strings.IndexByte(line[search:], '`')
362 length := telegramBackticks(line[next:])
364 search = next + length
368 content := line[index+run : next]
369 if strings.TrimSpace(content) == "" {
373 if len(content) > 1 && content[0] == ' ' && content[len(content)-1] == ' ' {
374 content = content[1 : len(content)-1]
377 return TelegramMarkdownSpan{
384 return TelegramMarkdownSpan{}, false
387 // telegramLinkSpan returns the link [text](url) that starts at index. The text
388 // can hold brackets in pairs, and the URL holds no space.
389 func telegramLinkSpan(line string, index int) (TelegramMarkdownSpan, bool) {
391 for closing := index; closing < len(line); closing++ {
392 switch line[closing] {
405 rest := line[closing+1:]
406 if closing == index+1 || !strings.HasPrefix(rest, "(") {
407 return TelegramMarkdownSpan{}, false
410 url, _, found := strings.Cut(rest[1:], ")")
411 if !found || url == "" || strings.ContainsAny(url, " \t") {
412 return TelegramMarkdownSpan{}, false
415 return TelegramMarkdownSpan{
417 content: line[index+1 : closing],
418 end: closing + 2 + len(url) + 1,
423 return TelegramMarkdownSpan{}, false
426 // telegramDelimited returns the span of kind between the mark at index and the
427 // same mark later in line. An opening mark is followed by a character that is
428 // not a space, and a closing mark follows one. A single mark is not a part of a
429 // double one. A mark of underscores does not open or close inside a word, so
430 // snake_case stays as text. A code span inside the content is skipped whole.
431 func telegramDelimited(line string, index int, mark, kind string) (TelegramMarkdownSpan, bool) {
433 after := index + len(mark)
434 if !strings.HasPrefix(line[index:], mark) || after >= len(line) || telegramIsSpace(line[after]) {
435 return TelegramMarkdownSpan{}, false
438 if len(mark) == 1 && (line[after] == char || index > 0 && line[index-1] == char) {
439 return TelegramMarkdownSpan{}, false
442 if char == '_' && index > 0 && telegramWordCharBefore(line[:index]) {
443 return TelegramMarkdownSpan{}, false
446 for closing := after + 1; closing < len(line); closing++ {
448 case line[closing] == '\\':
451 case line[closing] == '`':
452 span, found := telegramCodeSpan(line, closing)
454 closing = span.end - 1
458 case !strings.HasPrefix(line[closing:], mark) || telegramIsSpace(line[closing-1]):
462 end := closing + len(mark)
463 if len(mark) == 1 && (line[closing-1] == char || end < len(line) && line[end] == char) {
467 if char == '_' && telegramWordChar(line[end:]) {
471 return TelegramMarkdownSpan{
473 content: line[after:closing],
478 return TelegramMarkdownSpan{}, false
481 // telegramBackticks returns the length of the run of backticks at the start of
483 func telegramBackticks(text string) int {
484 return len(text) - len(strings.TrimLeft(text, "`"))
487 // telegramIsSpace tells if char is a space, a tab, or a line break.
488 func telegramIsSpace(char byte) bool {
489 return char == ' ' || char == '\t' || char == '\n' || char == '\r'
492 // telegramWordCharBefore tells if the character that ends text is a letter or a
494 func telegramWordCharBefore(text string) bool {
495 char, _ := utf8.DecodeLastRuneInString(text)
496 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))
499 // telegramWordChar tells if the character that starts text is a letter or a
500 // digit. An underscore next to one is a part of a word, such as in snake_case.
501 func telegramWordChar(text string) bool {
502 char, _ := utf8.DecodeRuneInString(text)
503 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))