Debian Codegraph @

src/parser/autolink.rs

raw
1 use finl_unicode::categories::CharacterCategories;
2 use std::borrow::Cow;
3 use std::str;
4
5 use crate::Arena;
6 use crate::character_set::character_set;
7 use crate::ctype::{isalnum, isalpha, isspace};
8 use crate::nodes::{Node, NodeLink, NodeValue, Sourcepos};
9 use crate::parser::Spx;
10 use crate::parser::inlines::{Subject, make_inline};
11
12 pub(crate) fn process_email_autolinks<'a>(
13 arena: &'a Arena<'a>,
14 node: Node<'a>,
15 contents: &mut Cow<'static, str>,
16 relaxed_autolinks: bool,
17 sourcepos: &mut Sourcepos,
18 spx: &mut Spx,
19 ) {
20 let bytes = contents.as_bytes();
21 let len = contents.len();
22 let mut i = 0;
23
24 while i < len {
25 let mut post_org = None;
26 let mut bracket_opening = 0;
27
28 // cmark-gfm ignores links inside brackets, such as `[[http://example.com]`
29 while i < len {
30 if !relaxed_autolinks {
31 match bytes[i] {
32 b'[' => {
33 bracket_opening += 1;
34 }
35 b']' => {
36 bracket_opening -= 1;
37 }
38 _ => (),
39 }
40
41 if bracket_opening > 0 {
42 i += 1;
43 continue;
44 }
45 }
46
47 if bytes[i] == b'@' {
48 post_org = email_match(arena, contents, i, relaxed_autolinks);
49 if post_org.is_some() {
50 break;
51 }
52 }
53 i += 1;
54 }
55
56 if let Some((post, reverse, skip)) = post_org {
57 i -= reverse;
58 node.insert_after(post);
59
60 let remain = if i + skip < len {
61 let remain = &contents[i + skip..];
62 assert!(!remain.is_empty());
63 Some(remain.to_string())
64 } else {
65 None
66 };
67 let initial_end_col = sourcepos.end.column;
68
69 sourcepos.end.column = spx.consume(i);
70
71 let nsp_end_col = spx.consume(skip);
72
73 contents.to_mut().truncate(i);
74
75 let nsp: Sourcepos = (
76 sourcepos.end.line,
77 sourcepos.end.column + 1,
78 sourcepos.end.line,
79 nsp_end_col,
80 )
81 .into();
82 post.data_mut().sourcepos = nsp;
83 // Inner text gets same sourcepos as link, since there's nothing but
84 // the text.
85 post.first_child().unwrap().data_mut().sourcepos = nsp;
86
87 if let Some(remain) = remain {
88 let mut asp: Sourcepos = (
89 sourcepos.end.line,
90 nsp.end.column + 1,
91 sourcepos.end.line,
92 initial_end_col,
93 )
94 .into();
95 let after = make_inline(arena, NodeValue::Text(remain.into()), asp);
96 post.insert_after(after);
97
98 let after_ast = &mut after.data_mut();
99 let NodeValue::Text(ref mut text) = after_ast.value else {
100 unreachable!();
101 };
102 process_email_autolinks(arena, after, text, relaxed_autolinks, &mut asp, spx);
103 after_ast.sourcepos = asp;
104 }
105
106 return;
107 }
108 }
109 }
110
111 fn email_match<'a>(
112 arena: &'a Arena<'a>,
113 contents: &str,
114 i: usize,
115 relaxed_autolinks: bool,
116 ) -> Option<(Node<'a>, usize, usize)> {
117 const EMAIL_OK_SET: [bool; 256] = character_set!(b".+-_");
118
119 let size = contents.len();
120 let bytes = contents.as_bytes();
121
122 let mut auto_mailto = true;
123 let mut is_xmpp = false;
124 let mut rewind = 0;
125
126 while rewind < i {
127 let c = bytes[i - rewind - 1];
128
129 if isalnum(c) || EMAIL_OK_SET[c as usize] {
130 rewind += 1;
131 continue;
132 }
133
134 if c == b':' {
135 if validate_protocol("mailto", contents, i - rewind - 1) {
136 auto_mailto = false;
137 rewind += 1;
138 continue;
139 }
140
141 if validate_protocol("xmpp", contents, i - rewind - 1) {
142 is_xmpp = true;
143 auto_mailto = false;
144 rewind += 1;
145 continue;
146 }
147 }
148
149 break;
150 }
151
152 if rewind == 0 {
153 return None;
154 }
155
156 let mut link_end = 1;
157 let mut np = 0;
158
159 while link_end < size - i {
160 let c = bytes[i + link_end];
161
162 if isalnum(c) {
163 // empty
164 } else if c == b'@' {
165 return None;
166 } else if c == b'.' && link_end < size - i - 1 && isalnum(bytes[i + link_end + 1]) {
167 np += 1;
168 } else if c == b'/' && is_xmpp {
169 // xmpp allows a `/` in the url
170 } else if c != b'-' && c != b'_' {
171 break;
172 }
173
174 link_end += 1;
175 }
176
177 if link_end < 2
178 || np == 0
179 || (!isalpha(bytes[i + link_end - 1]) && bytes[i + link_end - 1] != b'.')
180 {
181 return None;
182 }
183
184 link_end = autolink_delim(&contents[i..], link_end, relaxed_autolinks);
185 if link_end == 0 {
186 return None;
187 }
188
189 let text = &contents[i - rewind..link_end + i];
190 let url = if auto_mailto {
191 format!("mailto:{text}")
192 } else {
193 text.to_string()
194 };
195
196 let inl = make_inline(
197 arena,
198 NodeValue::Link(Box::new(NodeLink {
199 url,
200 title: String::new(),
201 })),
202 (0, 1, 0, 1).into(),
203 );
204
205 inl.append(make_inline(
206 arena,
207 NodeValue::Text(text.to_string().into()),
208 (0, 1, 0, 1).into(),
209 ));
210 Some((inl, rewind, rewind + link_end))
211 }
212
213 fn validate_protocol(protocol: &str, contents: &str, cursor: usize) -> bool {
214 let size = contents.len();
215 let bytes = contents.as_bytes();
216 let mut rewind = 0;
217
218 while rewind < cursor && isalpha(bytes[cursor - rewind - 1]) {
219 rewind += 1;
220 }
221
222 size - cursor + rewind >= protocol.len() && &contents[cursor - rewind..cursor] == protocol
223 }
224
225 pub fn www_match<'a>(
226 subject: &mut Subject<'a, '_, '_, '_, '_, '_>,
227 ) -> Option<(Node<'a>, usize, usize)> {
228 const WWW_DELIMS: [bool; 256] = character_set!(b"*_~([");
229 let i = subject.scanner.pos;
230 let relaxed_autolinks = subject.options.parse.relaxed_autolinks;
231 let bytes = subject.input.as_bytes();
232
233 if i > 0 && !isspace(bytes[i - 1]) && !WWW_DELIMS[bytes[i - 1] as usize] {
234 return None;
235 }
236
237 if !subject.input[i..].starts_with("www.") {
238 return None;
239 }
240
241 // Skip over "www." for domain validation, but account for its length in the overall link
242 let mut link_end = check_domain(&subject.input[i + 4..], relaxed_autolinks)? + 4;
243
244 while i + link_end < subject.input.len() && !isspace(bytes[i + link_end]) {
245 // basic test to detect whether we're in a normal markdown link - not exhaustive
246 if relaxed_autolinks && bytes[i + link_end - 1] == b']' && bytes[i + link_end] == b'(' {
247 return None;
248 }
249 link_end += 1;
250 }
251
252 link_end = autolink_delim(&subject.input[i..], link_end, relaxed_autolinks);
253
254 let mut url = "http://".to_string();
255 url.push_str(&subject.input[i..link_end + i]);
256
257 let inl = make_inline(
258 subject.arena,
259 NodeValue::Link(Box::new(NodeLink {
260 url,
261 title: String::new(),
262 })),
263 (0, 1, 0, 1).into(),
264 );
265
266 inl.append(make_inline(
267 subject.arena,
268 NodeValue::Text(subject.input[i..link_end + i].to_string().into()),
269 (0, 1, 0, 1).into(),
270 ));
271 Some((inl, 0, link_end))
272 }
273
274 fn check_domain(data: &str, allow_short: bool) -> Option<usize> {
275 let mut np = 0;
276 let mut uscore1 = 0;
277 let mut uscore2 = 0;
278
279 for (i, c) in data.char_indices() {
280 if c == '\\' && i < data.len() - 1 {
281 // Ignore escaped characters per https://github.com/github/cmark-gfm/pull/292.
282 // Not sure I love this, but it tracks upstream ..
283 } else if c == '_' {
284 uscore2 += 1;
285 } else if c == '.' {
286 uscore1 = uscore2;
287 uscore2 = 0;
288 np += 1;
289 } else if !is_valid_hostchar(c) && c != '-' {
290 if uscore1 == 0 && uscore2 == 0 && (allow_short || np > 0) {
291 return Some(i);
292 }
293 return None;
294 }
295 }
296
297 if (uscore1 > 0 || uscore2 > 0) && np <= 10 {
298 None
299 } else if allow_short || np > 0 {
300 Some(data.len())
301 } else {
302 None
303 }
304 }
305
306 fn is_valid_hostchar(ch: char) -> bool {
307 !(ch.is_whitespace() || ch.is_punctuation() || ch.is_symbol())
308 }
309
310 fn autolink_delim(data: &str, mut link_end: usize, relaxed_autolinks: bool) -> usize {
311 const LINK_END_ASSORTMENT: [bool; 256] = character_set!(b"?!.,:*_~'\"");
312 // \u{2069} (Pop Directional Isolate)
313 const LINK_END_UNICODE: [u8; 3] = [0xe2, 0x81, 0xa9];
314
315 let bytes = data.as_bytes();
316 for (i, &b) in bytes.iter().enumerate().take(link_end) {
317 if b == b'<' {
318 link_end = i;
319 break;
320 }
321 }
322
323 while link_end > 0 {
324 let cclose = bytes[link_end - 1];
325
326 // Allow any number of matching parentheses (as recognised in copen/cclose)
327 // at the end of the URL. If there is a greater number of closing
328 // parentheses than opening ones, we remove one character from the end of
329 // the link.
330 let mut copen = if cclose == b')' { Some(b'(') } else { None };
331
332 if relaxed_autolinks && copen.is_none() {
333 // allow balancing of `[]` and `{}` just like `()`
334 copen = if cclose == b']' {
335 Some(b'[')
336 } else if cclose == b'}' {
337 Some(b'{')
338 } else {
339 None
340 };
341 }
342
343 if LINK_END_ASSORTMENT[cclose as usize] {
344 link_end -= 1;
345 } else if cclose == b';' {
346 let mut new_end = link_end - 2;
347
348 while new_end > 0 && isalpha(bytes[new_end]) {
349 new_end -= 1;
350 }
351
352 if new_end < link_end - 2 && bytes[new_end] == b'&' {
353 link_end = new_end;
354 } else {
355 link_end -= 1;
356 }
357 } else if let Some(copen) = copen {
358 let mut opening = 0;
359 let mut closing = 0;
360 for &b in bytes.iter().take(link_end) {
361 if b == copen {
362 opening += 1;
363 } else if b == cclose {
364 closing += 1;
365 }
366 }
367
368 if closing <= opening {
369 break;
370 }
371
372 link_end -= 1;
373 } else if cclose == LINK_END_UNICODE[2] {
374 let slice = &bytes[link_end - LINK_END_UNICODE.len()..link_end];
375
376 if slice == LINK_END_UNICODE {
377 link_end -= LINK_END_UNICODE.len();
378 break;
379 }
380
381 break;
382 } else {
383 break;
384 }
385 }
386
387 link_end
388 }
389
390 pub fn url_match<'a>(
391 subject: &mut Subject<'a, '_, '_, '_, '_, '_>,
392 ) -> Option<(Node<'a>, usize, usize)> {
393 const SCHEMES: [&str; 3] = ["http", "https", "ftp"];
394
395 let i = subject.scanner.pos;
396 let relaxed_autolinks = subject.options.parse.relaxed_autolinks;
397 let bytes = subject.input.as_bytes();
398 let size = subject.input.len();
399
400 if size - i < 4 || bytes[i + 1] != b'/' || bytes[i + 2] != b'/' {
401 return None;
402 }
403
404 let mut rewind = 0;
405 while rewind < i && isalpha(bytes[i - rewind - 1]) {
406 rewind += 1;
407 }
408
409 if !relaxed_autolinks {
410 let scheme = &subject.input[i - rewind..i];
411 let cond = |s: &&str| size - i + rewind >= s.len() && &scheme == s;
412 if !SCHEMES.iter().any(cond) {
413 return None;
414 }
415 }
416
417 let mut link_end = check_domain(&subject.input[i + 3..], relaxed_autolinks)? + 3;
418
419 while link_end < size - i && !isspace(bytes[i + link_end]) {
420 // basic test to detect whether we're in a normal markdown link - not exhaustive
421 if relaxed_autolinks
422 && link_end > 0
423 && bytes[i + link_end - 1] == b']'
424 && bytes[i + link_end] == b'('
425 {
426 return None;
427 }
428 link_end += 1;
429 }
430
431 link_end = autolink_delim(&subject.input[i..], link_end, relaxed_autolinks);
432
433 let url = &subject.input[i - rewind..i + link_end];
434 let inl = make_inline(
435 subject.arena,
436 NodeValue::Link(Box::new(NodeLink {
437 url: url.to_string(),
438 title: String::new(),
439 })),
440 (0, 1, 0, 1).into(),
441 );
442
443 inl.append(make_inline(
444 subject.arena,
445 NodeValue::Text(url.to_string().into()),
446 (0, 1, 0, 1).into(),
447 ));
448 Some((inl, rewind, rewind + link_end))
449 }