Skip to main content

teloxide/utils/
markdown.rs

1//! Utils for working with the [Markdown V2 message style][spec].
2//!
3//! [spec]: https://core.telegram.org/bots/api#markdownv2-style
4
5use teloxide_core::types::{User, UserId};
6
7pub(super) const ESCAPE_CHARS: [char; 19] = [
8    '\\', '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!',
9];
10
11/// Applies the bold font style to the string.
12///
13/// Passed string will not be automatically escaped because it can contain
14/// nested markup.
15#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
16              without using its output does nothing useful"]
17pub fn bold(s: &str) -> String {
18    format!("*{s}*")
19}
20
21/// Applies the block quotation style to the string.
22///
23/// Passed string will not be automatically escaped because it can contain
24/// nested markup.
25#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
26              without using its output does nothing useful"]
27pub fn blockquote(s: &str) -> String {
28    format!("**>{}", s.replace('\n', "\n>"))
29}
30
31/// Applies the expandable block quotation style to the string.
32///
33/// Passed string will not be automatically escaped because it can contain
34/// nested markup.
35#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
36              without using its output does nothing useful"]
37pub fn expandable_blockquote(s: &str) -> String {
38    format!("**>{}||", s.replace('\n', "\n>"))
39}
40
41/// Applies the italic font style to the string.
42///
43/// Can be safely used with `utils::markdown::underline()`.
44/// Passed string will not be automatically escaped because it can contain
45/// nested markup.
46#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
47              without using its output does nothing useful"]
48pub fn italic(s: &str) -> String {
49    if s.starts_with("__") && s.ends_with("__") {
50        format!(r"_{}\r__", &s[..s.len() - 1])
51    } else {
52        format!("_{s}_")
53    }
54}
55
56/// Applies the underline font style to the string.
57///
58/// Can be safely used with `utils::markdown::italic()`.
59/// Passed string will not be automatically escaped because it can contain
60/// nested markup.
61#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
62              without using its output does nothing useful"]
63pub fn underline(s: &str) -> String {
64    // In case of ambiguity between italic and underline entities
65    // ‘__’ is always greedily treated from left to right as beginning or end of
66    // underline entity, so instead of ___italic underline___ we should use
67    // ___italic underline_\r__, where \r is a character with code 13, which
68    // will be ignored.
69    if s.starts_with('_') && s.ends_with('_') {
70        format!(r"__{s}\r__")
71    } else {
72        format!("__{s}__")
73    }
74}
75
76/// Applies the strikethrough font style to the string.
77///
78/// Passed string will not be automatically escaped because it can contain
79/// nested markup.
80#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
81              without using its output does nothing useful"]
82pub fn strike(s: &str) -> String {
83    format!("~{s}~")
84}
85
86/// Builds an inline link with an anchor.
87///
88/// Escapes `)` and ``` characters inside the link url.
89#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
90              without using its output does nothing useful"]
91pub fn link(url: &str, text: &str) -> String {
92    format!("[{}]({})", text, escape_link_url(url))
93}
94
95/// Builds an inline user mention link with an anchor.
96#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
97              without using its output does nothing useful"]
98pub fn user_mention(user_id: UserId, text: &str) -> String {
99    link(format!("tg://user?id={user_id}").as_str(), text)
100}
101
102/// Formats the code block.
103///
104/// Escapes ``` and `\` characters inside the block.
105#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
106              without using its output does nothing useful"]
107pub fn code_block(code: &str) -> String {
108    format!("```\n{}\n```", escape_code(code))
109}
110
111/// Formats the code block with a specific language syntax.
112///
113/// Escapes ``` and `\` characters inside the block.
114#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
115              without using its output does nothing useful"]
116pub fn code_block_with_lang(code: &str, lang: &str) -> String {
117    format!("```{}\n{}\n```", escape(lang), escape_code(code))
118}
119
120/// Formats the string as an inline code.
121///
122/// Escapes ``` and `\` characters inside the block.
123#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
124              without using its output does nothing useful"]
125pub fn code_inline(s: &str) -> String {
126    format!("`{}`", escape_code(s))
127}
128
129/// Escapes the string to be shown "as is" within the Telegram [Markdown
130/// v2][spec] message style.
131///
132/// [spec]: https://core.telegram.org/bots/api#markdownv2-style
133#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
134              without using its output does nothing useful"]
135pub fn escape(s: &str) -> String {
136    s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
137        if ESCAPE_CHARS.contains(&c) {
138            s.push('\\');
139        }
140        s.push(c);
141        s
142    })
143}
144
145/// Escapes all markdown special characters specific for the inline link URL
146/// (``` and `)`).
147#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
148              without using its output does nothing useful"]
149pub fn escape_link_url(s: &str) -> String {
150    s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
151        if ['`', ')'].contains(&c) {
152            s.push('\\');
153        }
154        s.push(c);
155        s
156    })
157}
158
159/// Escapes all markdown special characters specific for the code block (``` and
160/// `\`).
161#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
162              without using its output does nothing useful"]
163pub fn escape_code(s: &str) -> String {
164    s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
165        if ['`', '\\'].contains(&c) {
166            s.push('\\');
167        }
168        s.push(c);
169        s
170    })
171}
172
173#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
174              without using its output does nothing useful"]
175pub fn user_mention_or_link(user: &User) -> String {
176    match user.mention() {
177        Some(mention) => escape(&mention),
178        None => link(user.url().as_str(), &escape(&user.full_name())),
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn test_bold() {
188        assert_eq!(bold(" foobar "), "* foobar *");
189        assert_eq!(bold(" _foobar_ "), "* _foobar_ *");
190        assert_eq!(bold("~(`foobar`)~"), "*~(`foobar`)~*");
191    }
192
193    #[test]
194    fn test_italic() {
195        assert_eq!(italic(" foobar "), "_ foobar _");
196        assert_eq!(italic("*foobar*"), "_*foobar*_");
197        assert_eq!(italic("~(foobar)~"), "_~(foobar)~_");
198    }
199
200    #[test]
201    fn test_underline() {
202        assert_eq!(underline(" foobar "), "__ foobar __");
203        assert_eq!(underline("*foobar*"), "__*foobar*__");
204        assert_eq!(underline("~(foobar)~"), "__~(foobar)~__");
205    }
206
207    #[test]
208    fn test_strike() {
209        assert_eq!(strike(" foobar "), "~ foobar ~");
210        assert_eq!(strike("*foobar*"), "~*foobar*~");
211        assert_eq!(strike("*(foobar)*"), "~*(foobar)*~");
212    }
213
214    #[test]
215    fn test_italic_with_underline() {
216        assert_eq!(underline(italic("foobar").as_str()), r"___foobar_\r__");
217        assert_eq!(italic(underline("foobar").as_str()), r"___foobar_\r__");
218    }
219
220    #[test]
221    fn test_link() {
222        assert_eq!(
223            link("https://www.google.com/(`foobar`)", "google"),
224            r"[google](https://www.google.com/(\`foobar\`\))",
225        );
226    }
227
228    #[test]
229    fn test_user_mention() {
230        assert_eq!(
231            user_mention(UserId(123_456_789), "pwner666"),
232            "[pwner666](tg://user?id=123456789)"
233        );
234    }
235
236    #[test]
237    fn test_blockquote() {
238        assert_eq!(blockquote("foobar\n\nfoo\nbar"), "**>foobar\n>\n>foo\n>bar");
239    }
240
241    #[test]
242    fn test_expandable_blockquote() {
243        assert_eq!(expandable_blockquote("foobar\n\nfoo\nbar"), "**>foobar\n>\n>foo\n>bar||");
244    }
245
246    #[test]
247    fn test_code_block() {
248        assert_eq!(
249            code_block("pre-'formatted'\nfixed-width \\code `block`"),
250            "```\npre-'formatted'\nfixed-width \\\\code \\`block\\`\n```"
251        );
252    }
253
254    #[test]
255    fn test_code_block_with_lang() {
256        assert_eq!(
257            code_block_with_lang("pre-'formatted'\nfixed-width \\code `block`", "[python]"),
258            "```\\[python\\]\npre-'formatted'\nfixed-width \\\\code \\`block\\`\n```"
259        );
260    }
261
262    #[test]
263    fn test_code_inline() {
264        assert_eq!(code_inline(" let x = (1, 2, 3); "), "` let x = (1, 2, 3); `");
265        assert_eq!(code_inline("<html>foo</html>"), "`<html>foo</html>`");
266        assert_eq!(code_inline(r" `(code inside code \ )` "), r"` \`(code inside code \\ )\` `");
267    }
268
269    #[test]
270    fn test_escape() {
271        assert_eq!(escape("\\!"), r"\\\!");
272        assert_eq!(escape("* foobar *"), r"\* foobar \*");
273        assert_eq!(
274            escape(r"_ * [ ] ( ) ~ \ ` > # + - = | { } . !"),
275            r"\_ \* \[ \] \( \) \~ \\ \` \> \# \+ \- \= \| \{ \} \. \!",
276        );
277    }
278
279    #[test]
280    fn test_escape_link_url() {
281        assert_eq!(
282            escape_link_url(r"https://en.wikipedia.org/wiki/Development+(Software)"),
283            r"https://en.wikipedia.org/wiki/Development+(Software\)"
284        );
285        assert_eq!(
286            escape_link_url(r"https://en.wikipedia.org/wiki/`"),
287            r"https://en.wikipedia.org/wiki/\`"
288        );
289        assert_eq!(escape_link_url(r"_*[]()~`#+-=|{}.!\"), r"_*[](\)~\`#+-=|{}.!\");
290    }
291
292    #[test]
293    fn test_escape_code() {
294        assert_eq!(escape_code(r"` \code inside the code\ `"), r"\` \\code inside the code\\ \`");
295        assert_eq!(escape_code(r"_*[]()~`#+-=|{}.!\"), r"_*[]()~\`#+-=|{}.!\\");
296    }
297
298    #[test]
299    fn user_mention_link() {
300        let user_with_username = User {
301            id: UserId(0),
302            is_bot: false,
303            first_name: "".to_string(),
304            last_name: None,
305            username: Some("abcd".to_string()),
306            language_code: None,
307            is_premium: false,
308            added_to_attachment_menu: false,
309        };
310        assert_eq!(user_mention_or_link(&user_with_username), "@abcd");
311        // Telegram allows underscores in usernames
312        // https://telegram.org/faq?setln=en#q-what-can-i-use-as-my-username
313        let user_with_username_underscore =
314            User { username: Some("Abcd_Efg".to_string()), ..user_with_username };
315        assert_eq!(user_mention_or_link(&user_with_username_underscore), "@Abcd\\_Efg");
316        let user_without_username = User {
317            id: UserId(123_456_789),
318            is_bot: false,
319            first_name: "Name".to_string(),
320            last_name: None,
321            username: None,
322            language_code: None,
323            is_premium: false,
324            added_to_attachment_menu: false,
325        };
326        assert_eq!(user_mention_or_link(&user_without_username), "[Name](tg://user/?id=123456789)")
327    }
328}