10 // telegramMarkdownPunctuation holds the ASCII characters that a backslash makes
12 const telegramMarkdownPunctuation = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
14 // telegramMarkdownEntities converts the Markdown of a reply to plain text and
15 // Telegram message entities. It knows bold (** and __), italic (* and _),
16 // strikethrough (~~), inline code, fenced code blocks with an optional
17 // language, links [text](url), and ATX headings, which become bold. Lists,
18 // quotes, and tables stay as their text. A mark that does not close stays as
19 // text with no entity, and code holds no entity.
21 // Inline marks do not cross a line break, so a mark that does not close cannot
22 // change the rest of the reply.
23 func telegramMarkdownEntities(markdown string) (string, []TelegramEntity) {
24 var out TelegramMarkdownText
25 lines := strings.Split(markdown, "\n")
26 for index := 0; index < len(lines); index++ {
32 language, fence := telegramCodeFence(line)
33 end := telegramClosingFence(lines, index, fence)
34 heading := telegramHeadingText(line)
38 out.add(strings.Join(lines[index+1:end], "\n"))
39 out.entity(TelegramEntity{
42 Length: out.units - start,
50 out.entity(TelegramEntity{
53 Length: out.units - start,
60 slices.SortStableFunc(out.entities, func(a, b TelegramEntity) int {
61 if a.Offset != b.Offset {
62 return a.Offset - b.Offset
65 return b.Length - a.Length
68 return out.text.String(), out.entities
71 // telegramCodeFence returns the language of a line that opens a fenced code
72 // block, and the fence. The fence is "" when line does not open a block.
73 func telegramCodeFence(line string) (string, string) {
74 trimmed := strings.TrimLeft(line, " ")
75 if len(line)-len(trimmed) > 3 || !strings.HasPrefix(trimmed, "```") {
79 run := len(trimmed) - len(strings.TrimLeft(trimmed, "`"))
80 info := strings.TrimSpace(trimmed[run:])
81 if strings.Contains(info, "`") {
85 language, _, _ := strings.Cut(info, " ")
87 return language, trimmed[:run]
90 // telegramClosesFence tells if line closes the code block of fence.
91 func telegramClosesFence(line, fence string) bool {
92 trimmed := strings.TrimSpace(line)
93 return strings.HasPrefix(trimmed, fence) && strings.Trim(trimmed, "`") == ""
96 // telegramUTF16Units returns the number of UTF-16 code units of text.
97 func telegramUTF16Units(text string) int {
99 for _, char := range text {
109 // TelegramMarkdownText is the plain text of a Markdown reply and its Telegram
110 // entities, while the conversion builds it. Units counts the UTF-16 code units
111 // of text, the unit of the entity offsets and lengths.
112 type TelegramMarkdownText struct {
115 entities []TelegramEntity
119 func (m *TelegramMarkdownText) add(text string) {
120 m.text.WriteString(text)
121 m.units += telegramUTF16Units(text)
124 // entity keeps entity, unless it is empty, because Telegram refuses an entity
126 func (m *TelegramMarkdownText) entity(entity TelegramEntity) {
127 if entity.Length > 0 {
128 m.entities = append(m.entities, entity)
132 // inline appends one line of Markdown with its inline marks as entities. A
133 // backslash before an ASCII punctuation character makes the character plain
135 func (m *TelegramMarkdownText) inline(line string) {
138 for index < len(line) {
139 if line[index] == '\\' && index+1 < len(line) && strings.IndexByte(telegramMarkdownPunctuation, line[index+1]) >= 0 {
140 m.add(line[plain:index])
147 span, found := telegramMarkSpan(line, index)
153 m.add(line[plain:index])
155 if span.kind == "code" {
158 m.inline(span.content)
161 m.entity(TelegramEntity{
164 Length: m.units - start,
175 // TelegramMarkdownSpan is an inline mark of a line: the entity type, the
176 // content inside the marks, the index after the closing mark, and the URL of a
178 type TelegramMarkdownSpan struct {
185 // telegramClosingFence returns the index of the line after index that closes
186 // the code block of fence, or -1 when fence is "" or no line closes it.
187 func telegramClosingFence(lines []string, index int, fence string) int {
192 for end := index + 1; end < len(lines); end++ {
193 if telegramClosesFence(lines[end], fence) {
201 // telegramHeadingText returns the text of an ATX heading line without its
202 // marks, or "" when line is not a heading or has no text.
203 func telegramHeadingText(line string) string {
204 trimmed := strings.TrimLeft(line, " ")
205 if len(line)-len(trimmed) > 3 {
209 level := len(trimmed) - len(strings.TrimLeft(trimmed, "#"))
210 if level == 0 || level > 6 {
214 rest := trimmed[level:]
215 if rest != "" && rest[0] != ' ' && rest[0] != '\t' {
219 rest = strings.TrimSpace(rest)
220 closed := strings.TrimRight(rest, "#")
221 if closed == "" || strings.HasSuffix(closed, " ") {
222 rest = strings.TrimSpace(closed)
228 // telegramMarkSpan returns the inline mark that starts at index of line and
229 // closes in line. It returns false when no mark starts there or the mark does
231 func telegramMarkSpan(line string, index int) (TelegramMarkdownSpan, bool) {
234 return telegramCodeSpan(line, index)
236 return telegramLinkSpan(line, index)
238 return telegramDelimited(line, index, "~~", "strikethrough")
240 double := line[index : index+1]
242 span, found := telegramDelimited(line, index, double, "bold")
247 return telegramDelimited(line, index, line[index:index+1], "italic")
249 return TelegramMarkdownSpan{}, false
253 // telegramCodeSpan returns the inline code that starts at index: a run of
254 // backticks, the code, and a run of the same length. One space on each side of
255 // the code is left out, as in Markdown.
256 func telegramCodeSpan(line string, index int) (TelegramMarkdownSpan, bool) {
257 run := telegramBackticks(line[index:])
258 for search := index + run; search < len(line); {
259 next := strings.IndexByte(line[search:], '`')
265 length := telegramBackticks(line[next:])
267 search = next + length
271 content := line[index+run : next]
272 if strings.TrimSpace(content) == "" {
276 if len(content) > 1 && content[0] == ' ' && content[len(content)-1] == ' ' {
277 content = content[1 : len(content)-1]
280 return TelegramMarkdownSpan{
287 return TelegramMarkdownSpan{}, false
290 // telegramLinkSpan returns the link [text](url) that starts at index. The text
291 // can hold brackets in pairs, and the URL holds no space.
292 func telegramLinkSpan(line string, index int) (TelegramMarkdownSpan, bool) {
294 for closing := index; closing < len(line); closing++ {
295 switch line[closing] {
308 rest := line[closing+1:]
309 if closing == index+1 || !strings.HasPrefix(rest, "(") {
310 return TelegramMarkdownSpan{}, false
313 url, _, found := strings.Cut(rest[1:], ")")
314 if !found || url == "" || strings.ContainsAny(url, " \t") {
315 return TelegramMarkdownSpan{}, false
318 return TelegramMarkdownSpan{
320 content: line[index+1 : closing],
321 end: closing + 2 + len(url) + 1,
326 return TelegramMarkdownSpan{}, false
329 // telegramDelimited returns the span of kind between the mark at index and the
330 // same mark later in line. An opening mark is followed by a character that is
331 // not a space, and a closing mark follows one. A single mark is not a part of a
332 // double one. A mark of underscores does not open or close inside a word, so
333 // snake_case stays as text. A code span inside the content is skipped whole.
334 func telegramDelimited(line string, index int, mark, kind string) (TelegramMarkdownSpan, bool) {
336 after := index + len(mark)
337 if !strings.HasPrefix(line[index:], mark) || after >= len(line) || telegramIsSpace(line[after]) {
338 return TelegramMarkdownSpan{}, false
341 if len(mark) == 1 && (line[after] == char || index > 0 && line[index-1] == char) {
342 return TelegramMarkdownSpan{}, false
345 if char == '_' && index > 0 && telegramWordCharBefore(line[:index]) {
346 return TelegramMarkdownSpan{}, false
349 for closing := after + 1; closing < len(line); closing++ {
351 case line[closing] == '\\':
354 case line[closing] == '`':
355 span, found := telegramCodeSpan(line, closing)
357 closing = span.end - 1
361 case !strings.HasPrefix(line[closing:], mark) || telegramIsSpace(line[closing-1]):
365 end := closing + len(mark)
366 if len(mark) == 1 && (line[closing-1] == char || end < len(line) && line[end] == char) {
370 if char == '_' && telegramWordChar(line[end:]) {
374 return TelegramMarkdownSpan{
376 content: line[after:closing],
381 return TelegramMarkdownSpan{}, false
384 // telegramBackticks returns the length of the run of backticks at the start of
386 func telegramBackticks(text string) int {
387 return len(text) - len(strings.TrimLeft(text, "`"))
390 // telegramIsSpace tells if char is a space, a tab, or a line break.
391 func telegramIsSpace(char byte) bool {
392 return char == ' ' || char == '\t' || char == '\n' || char == '\r'
395 // telegramWordCharBefore tells if the character that ends text is a letter or a
397 func telegramWordCharBefore(text string) bool {
398 char, _ := utf8.DecodeLastRuneInString(text)
399 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))
402 // telegramWordChar tells if the character that starts text is a letter or a
403 // digit. An underscore next to one is a part of a word, such as in snake_case.
404 func telegramWordChar(text string) bool {
405 char, _ := utf8.DecodeRuneInString(text)
406 return text != "" && (unicode.IsLetter(char) || unicode.IsDigit(char))