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