-
-
Notifications
You must be signed in to change notification settings - Fork 143
/
inlines.rs
2076 lines (1865 loc) · 70.9 KB
/
inlines.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::arena_tree::Node;
use crate::ctype::{isdigit, ispunct, isspace};
use crate::entity;
use crate::nodes::{
Ast, AstNode, NodeCode, NodeFootnoteReference, NodeLink, NodeMath, NodeValue, NodeWikiLink,
Sourcepos,
};
use crate::parser::autolink;
#[cfg(feature = "shortcodes")]
use crate::parser::shortcodes::NodeShortCode;
use crate::parser::{
unwrap_into_2, unwrap_into_copy, AutolinkType, BrokenLinkReference, Options, ResolvedReference,
};
use crate::scanners;
use crate::strings::{self, is_blank, Case};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ptr;
use std::str;
use typed_arena::Arena;
use unicode_categories::UnicodeCategories;
const MAXBACKTICKS: usize = 80;
const MAX_LINK_LABEL_LENGTH: usize = 1000;
const MAX_MATH_DOLLARS: usize = 2;
pub struct Subject<'a: 'd, 'r, 'o, 'd, 'i, 'c> {
pub arena: &'a Arena<AstNode<'a>>,
options: &'o Options<'c>,
pub input: &'i [u8],
line: usize,
pub pos: usize,
column_offset: isize,
line_offset: usize,
flags: Flags,
pub refmap: &'r mut RefMap,
delimiter_arena: &'d Arena<Delimiter<'a, 'd>>,
last_delimiter: Option<&'d Delimiter<'a, 'd>>,
brackets: Vec<Bracket<'a>>,
within_brackets: bool,
pub backticks: [usize; MAXBACKTICKS + 1],
pub scanned_for_backticks: bool,
no_link_openers: bool,
special_chars: [bool; 256],
skip_chars: [bool; 256],
smart_chars: [bool; 256],
}
#[derive(Default)]
struct Flags {
skip_html_cdata: bool,
skip_html_declaration: bool,
skip_html_pi: bool,
skip_html_comment: bool,
}
pub struct RefMap {
pub map: HashMap<String, ResolvedReference>,
pub(crate) max_ref_size: usize,
ref_size: usize,
}
impl RefMap {
pub fn new() -> Self {
Self {
map: HashMap::new(),
max_ref_size: usize::MAX,
ref_size: 0,
}
}
fn lookup(&mut self, lab: &str) -> Option<ResolvedReference> {
match self.map.get(lab) {
Some(entry) => {
let size = entry.url.len() + entry.title.len();
if size > self.max_ref_size - self.ref_size {
None
} else {
self.ref_size += size;
Some(entry.clone())
}
}
None => None,
}
}
}
pub struct Delimiter<'a: 'd, 'd> {
inl: &'a AstNode<'a>,
position: usize,
length: usize,
delim_char: u8,
can_open: bool,
can_close: bool,
prev: Cell<Option<&'d Delimiter<'a, 'd>>>,
next: Cell<Option<&'d Delimiter<'a, 'd>>>,
}
struct Bracket<'a> {
inl_text: &'a AstNode<'a>,
position: usize,
image: bool,
bracket_after: bool,
}
#[derive(Clone, Copy)]
struct WikilinkComponents<'i> {
url: &'i [u8],
link_label: Option<(&'i [u8], usize, usize)>,
}
impl<'a, 'r, 'o, 'd, 'i, 'c> Subject<'a, 'r, 'o, 'd, 'i, 'c> {
pub fn new(
arena: &'a Arena<AstNode<'a>>,
options: &'o Options<'c>,
input: &'i [u8],
line: usize,
refmap: &'r mut RefMap,
delimiter_arena: &'d Arena<Delimiter<'a, 'd>>,
) -> Self {
let mut s = Subject {
arena,
options,
input,
line,
pos: 0,
column_offset: 0,
line_offset: 0,
flags: Flags::default(),
refmap,
delimiter_arena,
last_delimiter: None,
brackets: vec![],
within_brackets: false,
backticks: [0; MAXBACKTICKS + 1],
scanned_for_backticks: false,
no_link_openers: true,
special_chars: [false; 256],
skip_chars: [false; 256],
smart_chars: [false; 256],
};
for &c in &[
b'\n', b'\r', b'_', b'*', b'"', b'`', b'\\', b'&', b'<', b'[', b']', b'!', b'$',
] {
s.special_chars[c as usize] = true;
}
if options.extension.autolink {
s.special_chars[b':' as usize] = true;
s.special_chars[b'w' as usize] = true;
}
if options.extension.strikethrough || options.extension.subscript {
s.special_chars[b'~' as usize] = true;
s.skip_chars[b'~' as usize] = true;
}
if options.extension.superscript {
s.special_chars[b'^' as usize] = true;
}
#[cfg(feature = "shortcodes")]
if options.extension.shortcodes {
s.special_chars[b':' as usize] = true;
}
if options.extension.underline {
s.special_chars[b'_' as usize] = true;
}
if options.extension.spoiler {
s.special_chars[b'|' as usize] = true;
}
for &c in &[b'"', b'\'', b'.', b'-'] {
s.smart_chars[c as usize] = true;
}
s
}
pub fn pop_bracket(&mut self) -> bool {
self.brackets.pop().is_some()
}
pub fn parse_inline(&mut self, node: &'a AstNode<'a>) -> bool {
let c = match self.peek_char() {
None => return false,
Some(ch) => *ch as char,
};
let node_ast = node.data.borrow();
let adjusted_line = self.line - node_ast.sourcepos.start.line;
self.line_offset = node_ast.line_offsets[adjusted_line];
let new_inl: Option<&'a AstNode<'a>> = match c {
'\0' => return false,
'\r' | '\n' => Some(self.handle_newline()),
'`' => Some(self.handle_backticks()),
'\\' => Some(self.handle_backslash()),
'&' => Some(self.handle_entity()),
'<' => Some(self.handle_pointy_brace()),
':' => {
let mut res = None;
if self.options.extension.autolink {
res = self.handle_autolink_colon(node);
}
#[cfg(feature = "shortcodes")]
if res.is_none() && self.options.extension.shortcodes {
res = self.handle_shortcodes_colon();
}
if res.is_none() {
self.pos += 1;
res = Some(self.make_inline(
NodeValue::Text(":".to_string()),
self.pos - 1,
self.pos - 1,
));
}
res
}
'w' if self.options.extension.autolink => match self.handle_autolink_w(node) {
Some(inl) => Some(inl),
None => {
self.pos += 1;
Some(self.make_inline(
NodeValue::Text("w".to_string()),
self.pos - 1,
self.pos - 1,
))
}
},
'*' | '_' | '\'' | '"' => Some(self.handle_delim(c as u8)),
'-' => Some(self.handle_hyphen()),
'.' => Some(self.handle_period()),
'[' => {
self.pos += 1;
let mut wikilink_inl = None;
if (self.options.extension.wikilinks_title_after_pipe
|| self.options.extension.wikilinks_title_before_pipe)
&& !self.within_brackets
&& self.peek_char() == Some(&(b'['))
{
wikilink_inl = self.handle_wikilink();
}
if wikilink_inl.is_none() {
let inl = self.make_inline(
NodeValue::Text("[".to_string()),
self.pos - 1,
self.pos - 1,
);
self.push_bracket(false, inl);
self.within_brackets = true;
Some(inl)
} else {
wikilink_inl
}
}
']' => {
self.within_brackets = false;
self.handle_close_bracket()
}
'!' => {
self.pos += 1;
if self.peek_char() == Some(&(b'[')) && self.peek_char_n(1) != Some(&(b'^')) {
self.pos += 1;
let inl = self.make_inline(
NodeValue::Text("![".to_string()),
self.pos - 2,
self.pos - 1,
);
self.push_bracket(true, inl);
self.within_brackets = true;
Some(inl)
} else {
Some(self.make_inline(
NodeValue::Text("!".to_string()),
self.pos - 1,
self.pos - 1,
))
}
}
'~' if self.options.extension.strikethrough || self.options.extension.subscript => {
Some(self.handle_delim(b'~'))
}
'^' if self.options.extension.superscript && !self.within_brackets => {
Some(self.handle_delim(b'^'))
}
'$' => Some(self.handle_dollars()),
'|' if self.options.extension.spoiler => Some(self.handle_delim(b'|')),
_ => {
let endpos = self.find_special_char();
let mut contents = self.input[self.pos..endpos].to_vec();
let startpos = self.pos;
self.pos = endpos;
if self
.peek_char()
.map_or(false, |&c| strings::is_line_end_char(c))
{
strings::rtrim(&mut contents);
}
// if we've just produced a LineBreak, then we should consume any leading
// space on this line
if node.last_child().map_or(false, |n| {
matches!(n.data.borrow().value, NodeValue::LineBreak)
}) {
strings::ltrim(&mut contents);
}
Some(self.make_inline(
NodeValue::Text(String::from_utf8(contents).unwrap()),
startpos,
endpos - 1,
))
}
};
if let Some(inl) = new_inl {
node.append(inl);
}
true
}
fn del_ref_eq(lhs: Option<&'d Delimiter<'a, 'd>>, rhs: Option<&'d Delimiter<'a, 'd>>) -> bool {
match (lhs, rhs) {
(None, None) => true,
(Some(l), Some(r)) => ptr::eq(l, r),
_ => false,
}
}
// After parsing a block (and sometimes during), this function traverses the
// stack of `Delimiters`, tokens ("*", "_", etc.) that may delimit regions
// of text for special rendering: emphasis, strong, superscript, subscript,
// spoilertext; looking for pairs of opening and closing delimiters,
// with the goal of placing the intervening nodes into new emphasis,
// etc AST nodes.
//
// The term stack here is a bit of a misnomer, as the `Delimiters` actually
// form a doubly-linked list. Items are pushed onto the stack during parsing,
// but during post-processing are removed from arbitrary locations.
//
// The `Delimiter` contains references AST `Text` nodes, which are also
// linked into the AST as siblings in the order they are parsed. This
// function doesn't know a-priori which ones are markdown syntax and which
// are just text: candidate delimiters that match have their nodes removed
// from the AST, as they are markdown, and their intervening siblings
// lowered into a new AST parent node via the `insert_emph` function;
// candidate delimiters that don't match are left in the tree.
//
// The basic algorithm is to start at the bottom of the stack, walk upwards
// looking for closing delimiters, and from each closing delimiter walk back
// down the stack looking for its matching opening delimiter. This traversal
// favors the smallest matching leftmost pairs, e.g.
//
// _a *b c_ d* e_
// ~~~~~~
//
// (The emphasis region is wavy-underlined)
//
// All of the `_` and `*` tokens are scanned as candidates, but only the
// region "a *b c" is lowered into an `Emph` node; the other candidate
// delimiters are all actually text.
//
// And in
//
// _a _b c_
// ~~~
//
// "b c" is the emphasis region, not "a _b c".
//
// Note that Delimiters are matched by comparing their `delim_char`, which
// is simply a value used to compare opening and closing delimiters - the
// actual text value of the scanned token can theoretically be different.
//
// There's some additional trickiness in the logic because "_", "__", and
// "___" (and etc. etc.) all share the same delim_char, but represent
// different emphasis. Note also that "_"- and "*"-delimited regions have
// complex rules for which can be opening and/or closing delimiters,
// determined in `scan_delims`.
pub fn process_emphasis(&mut self, stack_bottom: usize) {
// This array is an important optimization that prevents searching down
// the stack for openers we've previously searched for and know don't
// exist, preventing exponential blowup on pathological cases.
let mut openers_bottom: [usize; 12] = [stack_bottom; 12];
// This is traversing the stack from the top to the bottom, setting `closer` to
// the delimiter directly above `stack_bottom`. In the case where we are processing
// emphasis on an entire block, `stack_bottom` is `None`, so `closer` references
// the very bottom of the stack.
let mut candidate = self.last_delimiter;
let mut closer: Option<&Delimiter> = None;
while candidate.map_or(false, |c| c.position >= stack_bottom) {
closer = candidate;
candidate = candidate.unwrap().prev.get();
}
while let Some(c) = closer {
if c.can_close {
// Each time through the outer `closer` loop we reset the opener
// to the element below the closer, and search down the stack
// for a matching opener.
let mut opener = c.prev.get();
let mut opener_found = false;
let mut mod_three_rule_invoked = false;
let ix = match c.delim_char {
b'|' => 0,
b'~' => 1,
b'^' => 2,
b'"' => 3,
b'\'' => 4,
b'_' => 5,
b'*' => 6 + (if c.can_open { 3 } else { 0 }) + (c.length % 3),
_ => unreachable!(),
};
// Here's where we find the opener by searching down the stack,
// looking for matching delims with the `can_open` flag.
// On any invocation, on the first time through the outer
// `closer` loop, this inner `opener` search doesn't succeed:
// when processing a full block, `opener` starts out `None`;
// when processing emphasis otherwise, opener will be equal to
// `stack_bottom`.
//
// This search short-circuits for openers we've previously
// failed to find, avoiding repeatedly rescanning the bottom of
// the stack, using the openers_bottom array.
while opener.map_or(false, |o| o.position >= openers_bottom[ix]) {
let o = opener.unwrap();
if o.can_open && o.delim_char == c.delim_char {
// This is a bit convoluted; see points 9 and 10 here:
// http://spec.commonmark.org/0.28/#can-open-emphasis.
// This is to aid processing of runs like this:
// “***hello*there**” or “***hello**there*”. In this
// case, the middle delimiter can both open and close
// emphasis; when trying to find an opening delimiter
// that matches the last ** or *, we need to skip it,
// and this algorithm ensures we do. (The sum of the
// lengths are a multiple of 3.)
let odd_match = (c.can_open || o.can_close)
&& ((o.length + c.length) % 3 == 0)
&& !(o.length % 3 == 0 && c.length % 3 == 0);
if !odd_match {
opener_found = true;
break;
} else {
mod_three_rule_invoked = true;
}
}
opener = o.prev.get();
}
let old_c = c;
// There's a case here for every possible delimiter. If we found
// a matching opening delimiter for our closing delimiter, they
// both get passed.
if c.delim_char == b'*'
|| c.delim_char == b'_'
|| ((self.options.extension.strikethrough || self.options.extension.subscript)
&& c.delim_char == b'~')
|| (self.options.extension.superscript && c.delim_char == b'^')
|| (self.options.extension.spoiler && c.delim_char == b'|')
{
if opener_found {
// Finally, here's the happy case where the delimiters
// match and they are inserted. We get a new closer
// delimiter and go around the loop again.
//
// Note that for "***" and "___" delimiters of length
// greater than 2, insert_emph will create a `Strong`
// node (i.e. "**"), then _truncate_ the delimiters in
// place, turning them into e.g. "*" delimiters, and
// hand us back the same mutated closer to be matched
// again.
//
// In general though the closer will be the next
// delimiter up the stack.
closer = self.insert_emph(opener.unwrap(), c);
} else {
// When no matching opener is found we move the closer
// up the stack, do some bookkeeping with old_closer
// (below), try again.
closer = c.next.get();
}
} else if c.delim_char == b'\'' || c.delim_char == b'"' {
*c.inl.data.borrow_mut().value.text_mut().unwrap() =
if c.delim_char == b'\'' { "’" } else { "”" }.to_string();
closer = c.next.get();
if opener_found {
*opener
.unwrap()
.inl
.data
.borrow_mut()
.value
.text_mut()
.unwrap() = if old_c.delim_char == b'\'' {
"‘"
} else {
"“"
}
.to_string();
self.remove_delimiter(opener.unwrap());
self.remove_delimiter(old_c);
}
}
// If the search for an opener was unsuccessful, then record
// the position the search started at in the `openers_bottom`
// so that the `opener` search can avoid looking for this
// same opener at the bottom of the stack later.
if !opener_found {
if !mod_three_rule_invoked {
openers_bottom[ix] = old_c.position;
}
// Now that we've failed the `opener` search starting from
// `old_closer`, future opener searches will be searching it
// for openers - if `old_closer` can't be used as an opener
// then we know it's just text - remove it from the
// delimiter stack, leaving it in the AST as text
if !old_c.can_open {
self.remove_delimiter(old_c);
}
}
} else {
// Closer is !can_close. Move up the stack
closer = c.next.get();
}
}
// At this point the entire delimiter stack from `stack_bottom` up has
// been scanned for matches, everything left is just text. Pop it all
// off.
self.remove_delimiters(stack_bottom);
}
fn remove_delimiter(&mut self, delimiter: &'d Delimiter<'a, 'd>) {
if delimiter.next.get().is_none() {
assert!(ptr::eq(delimiter, self.last_delimiter.unwrap()));
self.last_delimiter = delimiter.prev.get();
} else {
delimiter.next.get().unwrap().prev.set(delimiter.prev.get());
}
if delimiter.prev.get().is_some() {
delimiter.prev.get().unwrap().next.set(delimiter.next.get());
}
}
fn remove_delimiters(&mut self, stack_bottom: usize) {
while self
.last_delimiter
.map_or(false, |d| d.position >= stack_bottom)
{
self.remove_delimiter(self.last_delimiter.unwrap());
}
}
#[inline]
pub fn eof(&self) -> bool {
self.pos >= self.input.len()
}
#[inline]
pub fn peek_char(&self) -> Option<&u8> {
self.peek_char_n(0)
}
#[inline]
fn peek_char_n(&self, n: usize) -> Option<&u8> {
if self.pos + n >= self.input.len() {
None
} else {
let c = &self.input[self.pos + n];
assert!(*c > 0);
Some(c)
}
}
pub fn find_special_char(&self) -> usize {
for n in self.pos..self.input.len() {
if self.special_chars[self.input[n] as usize] {
if self.input[n] == b'^' && self.within_brackets {
// NO OP
} else {
return n;
}
}
if self.options.parse.smart && self.smart_chars[self.input[n] as usize] {
return n;
}
}
self.input.len()
}
fn adjust_node_newlines(&mut self, node: &'a AstNode<'a>, matchlen: usize, extra: usize) {
if !self.options.render.sourcepos {
return;
}
let (newlines, since_newline) =
count_newlines(&self.input[self.pos - matchlen - extra..self.pos - extra]);
if newlines > 0 {
self.line += newlines;
let node_ast = &mut node.data.borrow_mut();
node_ast.sourcepos.end.line += newlines;
node_ast.sourcepos.end.column = since_newline;
self.column_offset = -(self.pos as isize) + since_newline as isize + extra as isize;
}
}
pub fn handle_newline(&mut self) -> &'a AstNode<'a> {
let nlpos = self.pos;
if self.input[self.pos] == b'\r' {
self.pos += 1;
}
if self.input[self.pos] == b'\n' {
self.pos += 1;
}
let inl = if nlpos > 1 && self.input[nlpos - 1] == b' ' && self.input[nlpos - 2] == b' ' {
self.make_inline(NodeValue::LineBreak, nlpos, self.pos - 1)
} else {
self.make_inline(NodeValue::SoftBreak, nlpos, self.pos - 1)
};
self.line += 1;
self.column_offset = -(self.pos as isize);
self.skip_spaces();
inl
}
pub fn take_while(&mut self, c: u8) -> usize {
let start_pos = self.pos;
while self.peek_char() == Some(&c) {
self.pos += 1;
}
self.pos - start_pos
}
pub fn scan_to_closing_backtick(&mut self, openticklength: usize) -> Option<usize> {
if openticklength > MAXBACKTICKS {
return None;
}
if self.scanned_for_backticks && self.backticks[openticklength] <= self.pos {
return None;
}
loop {
while self.peek_char().map_or(false, |&c| c != b'`') {
self.pos += 1;
}
if self.pos >= self.input.len() {
self.scanned_for_backticks = true;
return None;
}
let numticks = self.take_while(b'`');
if numticks <= MAXBACKTICKS {
self.backticks[numticks] = self.pos - numticks;
}
if numticks == openticklength {
return Some(self.pos);
}
}
}
pub fn handle_backticks(&mut self) -> &'a AstNode<'a> {
let openticks = self.take_while(b'`');
let startpos = self.pos;
let endpos = self.scan_to_closing_backtick(openticks);
match endpos {
None => {
self.pos = startpos;
self.make_inline(NodeValue::Text("`".repeat(openticks)), self.pos, self.pos)
}
Some(endpos) => {
let buf = &self.input[startpos..endpos - openticks];
let buf = strings::normalize_code(buf);
let code = NodeCode {
num_backticks: openticks,
literal: String::from_utf8(buf).unwrap(),
};
let node =
self.make_inline(NodeValue::Code(code), startpos, endpos - openticks - 1);
self.adjust_node_newlines(node, endpos - startpos, openticks);
node
}
}
}
pub fn scan_to_closing_dollar(&mut self, opendollarlength: usize) -> Option<usize> {
if !(self.options.extension.math_dollars) || opendollarlength > MAX_MATH_DOLLARS {
return None;
}
// space not allowed after initial $
if opendollarlength == 1 && self.peek_char().map_or(false, |&c| isspace(c)) {
return None;
}
loop {
while self.peek_char().map_or(false, |&c| c != b'$') {
self.pos += 1;
}
if self.pos >= self.input.len() {
return None;
}
// space not allowed before ending $
if opendollarlength == 1 {
let c = self.input[self.pos - 1];
if isspace(c) {
return None;
}
}
// dollar signs must also be backslash-escaped if they occur within math
let c = self.input[self.pos - 1];
if opendollarlength == 1 && c == (b'\\') {
self.pos += 1;
continue;
}
let numdollars = self.take_while(b'$');
// ending $ can't be followed by a digit
if opendollarlength == 1 && self.peek_char().map_or(false, |&c| isdigit(c)) {
return None;
}
if numdollars == opendollarlength {
return Some(self.pos);
}
}
}
pub fn scan_to_closing_code_dollar(&mut self) -> Option<usize> {
if !self.options.extension.math_code {
return None;
}
loop {
while self.peek_char().map_or(false, |&c| c != b'$') {
self.pos += 1;
}
if self.pos >= self.input.len() {
return None;
}
let c = self.input[self.pos - 1];
if c == b'`' {
self.pos += 1;
return Some(self.pos);
} else {
self.pos += 1;
}
}
}
// Heuristics used from https://pandoc.org/MANUAL.html#extension-tex_math_dollars
pub fn handle_dollars(&mut self) -> &'a AstNode<'a> {
if self.options.extension.math_dollars || self.options.extension.math_code {
let opendollars = self.take_while(b'$');
let mut code_math = false;
// check for code math
if opendollars == 1
&& self.options.extension.math_code
&& self.peek_char().map_or(false, |&c| c == b'`')
{
code_math = true;
self.pos += 1;
}
let startpos = self.pos;
let endpos: Option<usize> = if code_math {
self.scan_to_closing_code_dollar()
} else {
self.scan_to_closing_dollar(opendollars)
};
let fence_length = if code_math { 2 } else { opendollars };
let endpos: Option<usize> = match endpos {
Some(epos) => {
if epos - startpos + fence_length < fence_length * 2 + 1 {
None
} else {
endpos
}
}
None => endpos,
};
match endpos {
None => {
if code_math {
self.pos = startpos - 1;
self.make_inline(
NodeValue::Text("$".to_string()),
self.pos - 1,
self.pos - 1,
)
} else {
self.pos = startpos;
self.make_inline(
NodeValue::Text("$".repeat(opendollars)),
self.pos,
self.pos,
)
}
}
Some(endpos) => {
let buf = &self.input[startpos..endpos - fence_length];
let buf: Vec<u8> = if code_math || opendollars == 1 {
strings::normalize_code(buf)
} else {
buf.to_vec()
};
let math = NodeMath {
dollar_math: !code_math,
display_math: opendollars == 2,
literal: String::from_utf8(buf).unwrap(),
};
let node = self.make_inline(
NodeValue::Math(math),
startpos,
endpos - fence_length - 1,
);
self.adjust_node_newlines(node, endpos - startpos, fence_length);
node
}
}
} else {
self.pos += 1;
self.make_inline(NodeValue::Text("$".to_string()), self.pos - 1, self.pos - 1)
}
}
pub fn skip_spaces(&mut self) -> bool {
let mut skipped = false;
while self.peek_char().map_or(false, |&c| c == b' ' || c == b'\t') {
self.pos += 1;
skipped = true;
}
skipped
}
pub fn handle_delim(&mut self, c: u8) -> &'a AstNode<'a> {
let (numdelims, can_open, can_close) = self.scan_delims(c);
let contents = if c == b'\'' && self.options.parse.smart {
"’".to_string()
} else if c == b'"' && self.options.parse.smart {
if can_close {
"”".to_string()
} else {
"“".to_string()
}
} else {
str::from_utf8(&self.input[self.pos - numdelims..self.pos])
.unwrap()
.to_string()
};
let inl = self.make_inline(
NodeValue::Text(contents),
self.pos - numdelims,
self.pos - 1,
);
if (can_open || can_close) && (!(c == b'\'' || c == b'"') || self.options.parse.smart) {
self.push_delimiter(c, can_open, can_close, inl);
}
inl
}
pub fn handle_hyphen(&mut self) -> &'a AstNode<'a> {
let start = self.pos;
self.pos += 1;
if !self.options.parse.smart || self.peek_char().map_or(true, |&c| c != b'-') {
return self.make_inline(NodeValue::Text("-".to_string()), self.pos - 1, self.pos - 1);
}
while self.options.parse.smart && self.peek_char().map_or(false, |&c| c == b'-') {
self.pos += 1;
}
let numhyphens = (self.pos - start) as i32;
let (ens, ems) = if numhyphens % 3 == 0 {
(0, numhyphens / 3)
} else if numhyphens % 2 == 0 {
(numhyphens / 2, 0)
} else if numhyphens % 3 == 2 {
(1, (numhyphens - 2) / 3)
} else {
(2, (numhyphens - 4) / 3)
};
let ens = if ens > 0 { ens as usize } else { 0 };
let ems = if ems > 0 { ems as usize } else { 0 };
let mut buf = String::with_capacity(3 * (ems + ens));
buf.push_str(&"—".repeat(ems));
buf.push_str(&"–".repeat(ens));
self.make_inline(NodeValue::Text(buf), start, self.pos - 1)
}
pub fn handle_period(&mut self) -> &'a AstNode<'a> {
self.pos += 1;
if self.options.parse.smart && self.peek_char().map_or(false, |&c| c == b'.') {
self.pos += 1;
if self.peek_char().map_or(false, |&c| c == b'.') {
self.pos += 1;
self.make_inline(NodeValue::Text("…".to_string()), self.pos - 3, self.pos - 1)
} else {
self.make_inline(
NodeValue::Text("..".to_string()),
self.pos - 2,
self.pos - 1,
)
}
} else {
self.make_inline(NodeValue::Text(".".to_string()), self.pos - 1, self.pos - 1)
}
}
pub fn scan_delims(&mut self, c: u8) -> (usize, bool, bool) {
let before_char = if self.pos == 0 {
'\n'
} else {
let mut before_char_pos = self.pos - 1;
while before_char_pos > 0
&& (self.input[before_char_pos] >> 6 == 2
|| self.skip_chars[self.input[before_char_pos] as usize])
{
before_char_pos -= 1;
}
match unsafe { str::from_utf8_unchecked(&self.input[before_char_pos..self.pos]) }
.chars()
.next()
{
Some(x) => {
if (x as usize) < 256 && self.skip_chars[x as usize] {
'\n'
} else {
x
}
}
None => '\n',
}
};
let mut numdelims = 0;
if c == b'\'' || c == b'"' {
numdelims += 1;
self.pos += 1;
} else {
while self.peek_char() == Some(&c) {
numdelims += 1;
self.pos += 1;
}
}
let after_char = if self.eof() {
'\n'
} else {
let mut after_char_pos = self.pos;
while after_char_pos < self.input.len() - 1
&& self.skip_chars[self.input[after_char_pos] as usize]
{
after_char_pos += 1;
}
match unsafe { str::from_utf8_unchecked(&self.input[after_char_pos..]) }
.chars()
.next()
{
Some(x) => {
if (x as usize) < 256 && self.skip_chars[x as usize] {
'\n'
} else {
x
}
}
None => '\n',
}
};