-
-
Notifications
You must be signed in to change notification settings - Fork 141
/
mod.rs
2374 lines (2146 loc) · 80.6 KB
/
mod.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
mod autolink;
mod inlines;
#[cfg(feature = "shortcodes")]
pub mod shortcodes;
mod table;
pub mod multiline_block_quote;
use crate::adapters::SyntaxHighlighterAdapter;
use crate::arena_tree::Node;
use crate::ctype::{isdigit, isspace};
use crate::entity;
use crate::nodes::{self, NodeFootnoteDefinition, Sourcepos};
use crate::nodes::{
Ast, AstNode, ListDelimType, ListType, NodeCodeBlock, NodeDescriptionItem, NodeHeading,
NodeHtmlBlock, NodeList, NodeValue,
};
use crate::scanners;
use crate::strings::{self, split_off_front_matter, Case};
use derive_builder::Builder;
use std::cell::RefCell;
use std::cmp::min;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
use std::mem;
use std::str;
use typed_arena::Arena;
use crate::adapters::HeadingAdapter;
use crate::parser::multiline_block_quote::NodeMultilineBlockQuote;
use self::inlines::RefMap;
const TAB_STOP: usize = 4;
const CODE_INDENT: usize = 4;
// Very deeply nested lists can cause quadratic performance issues.
// This constant is used in open_new_blocks() to limit the nesting
// depth. It is unlikely that a non-contrived markdown document will
// be nested this deeply.
const MAX_LIST_DEPTH: usize = 100;
macro_rules! node_matches {
($node:expr, $( $pat:pat )|+) => {{
matches!(
$node.data.borrow().value,
$( $pat )|+
)
}};
}
/// Parse a Markdown document to an AST.
///
/// See the documentation of the crate root for an example.
pub fn parse_document<'a>(
arena: &'a Arena<AstNode<'a>>,
buffer: &str,
options: &Options,
) -> &'a AstNode<'a> {
parse_document_with_broken_link_callback(arena, buffer, options, None)
}
/// Parse a Markdown document to an AST.
///
/// In case the parser encounters any potential links that have a broken reference (e.g `[foo]`
/// when there is no `[foo]: url` entry at the bottom) the provided callback will be called with
/// the reference name, and the returned pair will be used as the link destination and title if not
/// None.
///
/// **Note:** The label provided to the callback is the normalized representation of the label as
/// described in the [GFM spec](https://github.github.com/gfm/#matches).
///
/// ```
/// use comrak::{Arena, parse_document_with_broken_link_callback, format_html, Options};
/// use comrak::nodes::{AstNode, NodeValue};
///
/// # fn main() -> std::io::Result<()> {
/// // The returned nodes are created in the supplied Arena, and are bound by its lifetime.
/// let arena = Arena::new();
///
/// let root = parse_document_with_broken_link_callback(
/// &arena,
/// "# Cool input!\nWow look at this cool [link][foo]. A [broken link] renders as text.",
/// &Options::default(),
/// Some(&mut |link_ref: &str| match link_ref {
/// "foo" => Some((
/// "https://www.rust-lang.org/".to_string(),
/// "The Rust Language".to_string(),
/// )),
/// _ => None,
/// }),
/// );
///
/// let mut output = Vec::new();
/// format_html(root, &Options::default(), &mut output)?;
/// let output_str = std::str::from_utf8(&output).expect("invalid UTF-8");
/// assert_eq!(output_str, "<h1>Cool input!</h1>\n<p>Wow look at this cool \
/// <a href=\"https://www.rust-lang.org/\" title=\"The Rust Language\">link</a>. \
/// A [broken link] renders as text.</p>\n");
/// # Ok(())
/// # }
/// ```
pub fn parse_document_with_broken_link_callback<'a, 'c>(
arena: &'a Arena<AstNode<'a>>,
buffer: &str,
options: &Options,
callback: Option<Callback<'c>>,
) -> &'a AstNode<'a> {
let root: &'a AstNode<'a> = arena.alloc(Node::new(RefCell::new(Ast {
value: NodeValue::Document,
content: String::new(),
sourcepos: (1, 1, 1, 1).into(),
internal_offset: 0,
open: true,
last_line_blank: false,
table_visited: false,
})));
let mut parser = Parser::new(arena, root, options, callback);
let mut linebuf = Vec::with_capacity(buffer.len());
parser.feed(&mut linebuf, buffer, true);
parser.finish(linebuf)
}
type Callback<'c> = &'c mut dyn FnMut(&str) -> Option<(String, String)>;
pub struct Parser<'a, 'o, 'c> {
arena: &'a Arena<AstNode<'a>>,
refmap: RefMap,
root: &'a AstNode<'a>,
current: &'a AstNode<'a>,
line_number: usize,
offset: usize,
column: usize,
thematic_break_kill_pos: usize,
first_nonspace: usize,
first_nonspace_column: usize,
indent: usize,
blank: bool,
partially_consumed_tab: bool,
curline_len: usize,
curline_end_col: usize,
last_line_length: usize,
last_buffer_ended_with_cr: bool,
total_size: usize,
options: &'o Options,
callback: Option<Callback<'c>>,
}
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
/// Umbrella options struct.
pub struct Options {
/// Enable CommonMark extensions.
pub extension: ExtensionOptions,
/// Configure parse-time options.
pub parse: ParseOptions,
/// Configure render-time options.
pub render: RenderOptions,
}
#[non_exhaustive]
#[derive(Default, Debug, Clone, Builder)]
#[builder(default)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
/// Options to select extensions.
pub struct ExtensionOptions {
/// Enables the
/// [strikethrough extension](https://github.github.com/gfm/#strikethrough-extension-)
/// from the GFM spec.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.strikethrough = true;
/// assert_eq!(markdown_to_html("Hello ~world~ there.\n", &options),
/// "<p>Hello <del>world</del> there.</p>\n");
/// ```
pub strikethrough: bool,
/// Enables the
/// [tagfilter extension](https://github.github.com/gfm/#disallowed-raw-html-extension-)
/// from the GFM spec.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.tagfilter = true;
/// options.render.unsafe_ = true;
/// assert_eq!(markdown_to_html("Hello <xmp>.\n\n<xmp>", &options),
/// "<p>Hello <xmp>.</p>\n<xmp>\n");
/// ```
pub tagfilter: bool,
/// Enables the [table extension](https://github.github.com/gfm/#tables-extension-)
/// from the GFM spec.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.table = true;
/// assert_eq!(markdown_to_html("| a | b |\n|---|---|\n| c | d |\n", &options),
/// "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n\
/// <tbody>\n<tr>\n<td>c</td>\n<td>d</td>\n</tr>\n</tbody>\n</table>\n");
/// ```
pub table: bool,
/// Enables the [autolink extension](https://github.github.com/gfm/#autolinks-extension-)
/// from the GFM spec.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.autolink = true;
/// assert_eq!(markdown_to_html("Hello www.github.com.\n", &options),
/// "<p>Hello <a href=\"http://www.github.com\">www.github.com</a>.</p>\n");
/// ```
pub autolink: bool,
/// Enables the
/// [task list items extension](https://github.github.com/gfm/#task-list-items-extension-)
/// from the GFM spec.
///
/// Note that the spec does not define the precise output, so only the bare essentials are
/// rendered.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.tasklist = true;
/// options.render.unsafe_ = true;
/// assert_eq!(markdown_to_html("* [x] Done\n* [ ] Not done\n", &options),
/// "<ul>\n<li><input type=\"checkbox\" checked=\"\" disabled=\"\" /> Done</li>\n\
/// <li><input type=\"checkbox\" disabled=\"\" /> Not done</li>\n</ul>\n");
/// ```
pub tasklist: bool,
/// Enables the superscript Comrak extension.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.superscript = true;
/// assert_eq!(markdown_to_html("e = mc^2^.\n", &options),
/// "<p>e = mc<sup>2</sup>.</p>\n");
/// ```
pub superscript: bool,
/// Enables the header IDs Comrak extension.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.header_ids = Some("user-content-".to_string());
/// assert_eq!(markdown_to_html("# README\n", &options),
/// "<h1><a href=\"#readme\" aria-hidden=\"true\" class=\"anchor\" id=\"user-content-readme\"></a>README</h1>\n");
/// ```
pub header_ids: Option<String>,
/// Enables the footnotes extension per `cmark-gfm`.
///
/// For usage, see `src/tests.rs`. The extension is modelled after
/// [Kramdown](https://kramdown.gettalong.org/syntax.html#footnotes).
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.footnotes = true;
/// assert_eq!(markdown_to_html("Hi[^x].\n\n[^x]: A greeting.\n", &options),
/// "<p>Hi<sup class=\"footnote-ref\"><a href=\"#fn-x\" id=\"fnref-x\" data-footnote-ref>1</a></sup>.</p>\n<section class=\"footnotes\" data-footnotes>\n<ol>\n<li id=\"fn-x\">\n<p>A greeting. <a href=\"#fnref-x\" class=\"footnote-backref\" data-footnote-backref data-footnote-backref-idx=\"1\" aria-label=\"Back to reference 1\">↩</a></p>\n</li>\n</ol>\n</section>\n");
/// ```
pub footnotes: bool,
/// Enables the description lists extension.
///
/// Each term must be defined in one paragraph, followed by a blank line,
/// and then by the details. Details begins with a colon.
///
/// Not (yet) compatible with render.sourcepos.
///
/// ``` md
/// First term
///
/// : Details for the **first term**
///
/// Second term
///
/// : Details for the **second term**
///
/// More details in second paragraph.
/// ```
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.description_lists = true;
/// assert_eq!(markdown_to_html("Term\n\n: Definition", &options),
/// "<dl><dt>Term</dt>\n<dd>\n<p>Definition</p>\n</dd>\n</dl>\n");
/// ```
pub description_lists: bool,
/// Enables the front matter extension.
///
/// Front matter, which begins with the delimiter string at the beginning of the file and ends
/// at the end of the next line that contains only the delimiter, is passed through unchanged
/// in markdown output and omitted from HTML output.
///
/// ``` md
/// ---
/// layout: post
/// title: Formatting Markdown with Comrak
/// ---
///
/// # Shorter Title
///
/// etc.
/// ```
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.front_matter_delimiter = Some("---".to_owned());
/// assert_eq!(
/// markdown_to_html("---\nlayout: post\n---\nText\n", &options),
/// markdown_to_html("Text\n", &Options::default()));
/// ```
///
/// ```
/// # use comrak::{format_commonmark, Arena, Options};
/// use comrak::parse_document;
/// let mut options = Options::default();
/// options.extension.front_matter_delimiter = Some("---".to_owned());
/// let arena = Arena::new();
/// let input ="---\nlayout: post\n---\nText\n";
/// let root = parse_document(&arena, input, &options);
/// let mut buf = Vec::new();
/// format_commonmark(&root, &options, &mut buf);
/// assert_eq!(&String::from_utf8(buf).unwrap(), input);
/// ```
pub front_matter_delimiter: Option<String>,
/// Enables the multiline block quote extension.
///
/// Place `>>>` before and after text to make it into
/// a block quote.
///
/// ``` md
/// Paragraph one
///
/// >>>
/// Paragraph two
///
/// - one
/// - two
/// >>>
/// ```
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.multiline_block_quotes = true;
/// assert_eq!(markdown_to_html(">>>\nparagraph\n>>>", &options),
/// "<blockquote>\n<p>paragraph</p>\n</blockquote>\n");
/// ```
pub multiline_block_quotes: bool,
#[cfg(feature = "shortcodes")]
#[cfg_attr(docsrs, doc(cfg(feature = "shortcodes")))]
/// Phrases wrapped inside of ':' blocks will be replaced with emojis.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// assert_eq!(markdown_to_html("Happy Friday! :smile:", &options),
/// "<p>Happy Friday! :smile:</p>\n");
///
/// options.extension.shortcodes = true;
/// assert_eq!(markdown_to_html("Happy Friday! :smile:", &options),
/// "<p>Happy Friday! 😄</p>\n");
/// ```
pub shortcodes: bool,
}
#[non_exhaustive]
#[derive(Default, Debug, Clone, Builder)]
#[builder(default)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
/// Options for parser functions.
pub struct ParseOptions {
/// Punctuation (quotes, full-stops and hyphens) are converted into 'smart' punctuation.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// assert_eq!(markdown_to_html("'Hello,' \"world\" ...", &options),
/// "<p>'Hello,' "world" ...</p>\n");
///
/// options.parse.smart = true;
/// assert_eq!(markdown_to_html("'Hello,' \"world\" ...", &options),
/// "<p>‘Hello,’ “world” …</p>\n");
/// ```
pub smart: bool,
/// The default info string for fenced code blocks.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// assert_eq!(markdown_to_html("```\nfn hello();\n```\n", &options),
/// "<pre><code>fn hello();\n</code></pre>\n");
///
/// options.parse.default_info_string = Some("rust".into());
/// assert_eq!(markdown_to_html("```\nfn hello();\n```\n", &options),
/// "<pre><code class=\"language-rust\">fn hello();\n</code></pre>\n");
/// ```
pub default_info_string: Option<String>,
/// Whether or not a simple `x` or `X` is used for tasklist or any other symbol is allowed.
pub relaxed_tasklist_matching: bool,
/// Relax parsing of autolinks, allowing links to be detected inside brackets.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// options.extension.autolink = true;
/// assert_eq!(markdown_to_html("[https://foo.com]", &options),
/// "<p>[https://foo.com]</p>\n");
///
/// options.parse.relaxed_autolinks = true;
/// assert_eq!(markdown_to_html("[https://foo.com]", &options),
/// "<p>[<a href=\"https://foo.com\">https://foo.com</a>]</p>\n");
/// ```
pub relaxed_autolinks: bool,
}
#[non_exhaustive]
#[derive(Default, Debug, Clone, Copy, Builder)]
#[builder(default)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
/// Options for formatter functions.
pub struct RenderOptions {
/// [Soft line breaks](http://spec.commonmark.org/0.27/#soft-line-breaks) in the input
/// translate into hard line breaks in the output.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// assert_eq!(markdown_to_html("Hello.\nWorld.\n", &options),
/// "<p>Hello.\nWorld.</p>\n");
///
/// options.render.hardbreaks = true;
/// assert_eq!(markdown_to_html("Hello.\nWorld.\n", &options),
/// "<p>Hello.<br />\nWorld.</p>\n");
/// ```
pub hardbreaks: bool,
/// GitHub-style `<pre lang="xyz">` is used for fenced code blocks with info tags.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// assert_eq!(markdown_to_html("``` rust\nfn hello();\n```\n", &options),
/// "<pre><code class=\"language-rust\">fn hello();\n</code></pre>\n");
///
/// options.render.github_pre_lang = true;
/// assert_eq!(markdown_to_html("``` rust\nfn hello();\n```\n", &options),
/// "<pre lang=\"rust\"><code>fn hello();\n</code></pre>\n");
/// ```
pub github_pre_lang: bool,
/// Enable full info strings for code blocks
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// assert_eq!(markdown_to_html("``` rust extra info\nfn hello();\n```\n", &options),
/// "<pre><code class=\"language-rust\">fn hello();\n</code></pre>\n");
///
/// options.render.full_info_string = true;
/// let html = markdown_to_html("``` rust extra info\nfn hello();\n```\n", &options);
/// let re = regex::Regex::new(r#"data-meta="extra info""#).unwrap();
/// assert!(re.is_match(&html));
/// ```
pub full_info_string: bool,
/// The wrap column when outputting CommonMark.
///
/// ```
/// # use comrak::{parse_document, Options, format_commonmark};
/// # fn main() {
/// # let arena = typed_arena::Arena::new();
/// let mut options = Options::default();
/// let node = parse_document(&arena, "hello hello hello hello hello hello", &options);
/// let mut output = vec![];
/// format_commonmark(node, &options, &mut output).unwrap();
/// assert_eq!(String::from_utf8(output).unwrap(),
/// "hello hello hello hello hello hello\n");
///
/// options.render.width = 20;
/// let mut output = vec![];
/// format_commonmark(node, &options, &mut output).unwrap();
/// assert_eq!(String::from_utf8(output).unwrap(),
/// "hello hello hello\nhello hello hello\n");
/// # }
/// ```
pub width: usize,
/// Allow rendering of raw HTML and potentially dangerous links.
///
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// let input = "<script>\nalert('xyz');\n</script>\n\n\
/// Possibly <marquee>annoying</marquee>.\n\n\
/// [Dangerous](javascript:alert(document.cookie)).\n\n\
/// [Safe](http://commonmark.org).\n";
///
/// assert_eq!(markdown_to_html(input, &options),
/// "<!-- raw HTML omitted -->\n\
/// <p>Possibly <!-- raw HTML omitted -->annoying<!-- raw HTML omitted -->.</p>\n\
/// <p><a href=\"\">Dangerous</a>.</p>\n\
/// <p><a href=\"http://commonmark.org\">Safe</a>.</p>\n");
///
/// options.render.unsafe_ = true;
/// assert_eq!(markdown_to_html(input, &options),
/// "<script>\nalert(\'xyz\');\n</script>\n\
/// <p>Possibly <marquee>annoying</marquee>.</p>\n\
/// <p><a href=\"javascript:alert(document.cookie)\">Dangerous</a>.</p>\n\
/// <p><a href=\"http://commonmark.org\">Safe</a>.</p>\n");
/// ```
pub unsafe_: bool,
/// Escape raw HTML instead of clobbering it.
/// ```
/// # use comrak::{markdown_to_html, Options};
/// let mut options = Options::default();
/// let input = "<i>italic text</i>";
///
/// assert_eq!(markdown_to_html(input, &options),
/// "<p><!-- raw HTML omitted -->italic text<!-- raw HTML omitted --></p>\n");
///
/// options.render.escape = true;
/// assert_eq!(markdown_to_html(input, &options),
/// "<p><i>italic text</i></p>\n");
/// ```
pub escape: bool,
/// Set the type of [bullet list marker](https://spec.commonmark.org/0.30/#bullet-list-marker) to use. Options are:
///
/// * `ListStyleType::Dash` to use `-` (default)
/// * `ListStyleType::Plus` to use `+`
/// * `ListStyleType::Star` to use `*`
///
/// ```rust
/// # use comrak::{markdown_to_commonmark, Options, ListStyleType};
/// let mut options = Options::default();
/// let input = "- one\n- two\n- three";
/// assert_eq!(markdown_to_commonmark(input, &options),
/// "- one\n- two\n- three\n"); // default is Dash
///
/// options.render.list_style = ListStyleType::Plus;
/// assert_eq!(markdown_to_commonmark(input, &options),
/// "+ one\n+ two\n+ three\n");
///
/// options.render.list_style = ListStyleType::Star;
/// assert_eq!(markdown_to_commonmark(input, &options),
/// "* one\n* two\n* three\n");
/// ```
pub list_style: ListStyleType,
/// Include source position attributes in XML output.
///
/// Not yet compatible with extension.description_lists.
///
/// ```rust
/// # use comrak::{markdown_to_commonmark_xml, Options};
/// let mut options = Options::default();
/// options.render.sourcepos = true;
/// let input = "Hello *world*!";
/// let xml = markdown_to_commonmark_xml(input, &options);
/// assert!(xml.contains("<emph sourcepos=\"1:7-1:13\">"));
/// ```
pub sourcepos: bool,
}
#[non_exhaustive]
#[derive(Default, Debug, Clone, Builder)]
#[builder(default)]
/// Umbrella plugins struct.
pub struct Plugins<'p> {
/// Configure render-time plugins.
pub render: RenderPlugins<'p>,
}
#[non_exhaustive]
#[derive(Default, Clone, Builder)]
#[builder(default)]
/// Plugins for alternative rendering.
pub struct RenderPlugins<'p> {
/// Provide a syntax highlighter adapter implementation for syntax
/// highlighting of codefence blocks.
/// ```
/// # use comrak::{markdown_to_html, Options, Plugins, markdown_to_html_with_plugins};
/// # use comrak::adapters::SyntaxHighlighterAdapter;
/// use std::collections::HashMap;
/// use std::io::{self, Write};
/// let options = Options::default();
/// let mut plugins = Plugins::default();
/// let input = "```rust\nfn main<'a>();\n```";
///
/// assert_eq!(markdown_to_html_with_plugins(input, &options, &plugins),
/// "<pre><code class=\"language-rust\">fn main<'a>();\n</code></pre>\n");
///
/// pub struct MockAdapter {}
/// impl SyntaxHighlighterAdapter for MockAdapter {
/// fn write_highlighted(&self, output: &mut dyn Write, lang: Option<&str>, code: &str) -> io::Result<()> {
/// write!(output, "<span class=\"lang-{}\">{}</span>", lang.unwrap(), code)
/// }
///
/// fn write_pre_tag(&self, output: &mut dyn Write, _attributes: HashMap<String, String>) -> io::Result<()> {
/// output.write_all(b"<pre lang=\"rust\">")
/// }
///
/// fn write_code_tag(&self, output: &mut dyn Write, _attributes: HashMap<String, String>) -> io::Result<()> {
/// output.write_all(b"<code class=\"language-rust\">")
/// }
/// }
///
/// let adapter = MockAdapter {};
/// plugins.render.codefence_syntax_highlighter = Some(&adapter);
///
/// assert_eq!(markdown_to_html_with_plugins(input, &options, &plugins),
/// "<pre lang=\"rust\"><code class=\"language-rust\"><span class=\"lang-rust\">fn main<'a>();\n</span></code></pre>\n");
/// ```
pub codefence_syntax_highlighter: Option<&'p dyn SyntaxHighlighterAdapter>,
/// Optional heading adapter
pub heading_adapter: Option<&'p dyn HeadingAdapter>,
}
impl Debug for RenderPlugins<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RenderPlugins")
.field(
"codefence_syntax_highlighter",
&"impl SyntaxHighlighterAdapter",
)
.finish()
}
}
#[derive(Clone)]
pub struct Reference {
pub url: String,
pub title: String,
}
struct FootnoteDefinition<'a> {
ix: Option<u32>,
node: &'a AstNode<'a>,
name: String,
total_references: u32,
}
impl<'a, 'o, 'c> Parser<'a, 'o, 'c> {
fn new(
arena: &'a Arena<AstNode<'a>>,
root: &'a AstNode<'a>,
options: &'o Options,
callback: Option<Callback<'c>>,
) -> Self {
Parser {
arena,
refmap: RefMap::new(),
root,
current: root,
line_number: 0,
offset: 0,
column: 0,
thematic_break_kill_pos: 0,
first_nonspace: 0,
first_nonspace_column: 0,
indent: 0,
blank: false,
partially_consumed_tab: false,
curline_len: 0,
curline_end_col: 0,
last_line_length: 0,
last_buffer_ended_with_cr: false,
total_size: 0,
options,
callback,
}
}
fn feed(&mut self, linebuf: &mut Vec<u8>, mut s: &str, eof: bool) {
if let (0, Some(delimiter)) = (
self.total_size,
&self.options.extension.front_matter_delimiter,
) {
if let Some((front_matter, rest)) = split_off_front_matter(s, delimiter) {
let node = self.add_child(
self.root,
NodeValue::FrontMatter(front_matter.to_string()),
1,
);
s = rest;
self.finalize(node).unwrap();
}
}
let s = s.as_bytes();
if s.len() > usize::MAX - self.total_size {
self.total_size = usize::MAX;
} else {
self.total_size += s.len();
}
let mut buffer = 0;
if self.last_buffer_ended_with_cr && !s.is_empty() && s[0] == b'\n' {
buffer += 1;
}
self.last_buffer_ended_with_cr = false;
let end = s.len();
while buffer < end {
let mut process = false;
let mut eol = buffer;
while eol < end {
if strings::is_line_end_char(s[eol]) {
process = true;
break;
}
if s[eol] == 0 {
break;
}
eol += 1;
}
if eol >= end && eof {
process = true;
}
if process {
if !linebuf.is_empty() {
linebuf.extend_from_slice(&s[buffer..eol]);
self.process_line(linebuf);
linebuf.truncate(0);
} else {
self.process_line(&s[buffer..eol]);
}
} else if eol < end && s[eol] == b'\0' {
linebuf.extend_from_slice(&s[buffer..eol]);
linebuf.extend_from_slice(&"\u{fffd}".to_string().into_bytes());
} else {
linebuf.extend_from_slice(&s[buffer..eol]);
}
buffer = eol;
if buffer < end {
if s[buffer] == b'\0' {
buffer += 1;
} else {
if s[buffer] == b'\r' {
buffer += 1;
if buffer == end {
self.last_buffer_ended_with_cr = true;
}
}
if buffer < end && s[buffer] == b'\n' {
buffer += 1;
}
}
}
}
}
fn scan_thematic_break_inner(&mut self, line: &[u8]) -> (usize, bool) {
let mut i = self.first_nonspace;
if i >= line.len() {
return (i, false);
}
let c = line[i];
if c != b'*' && c != b'_' && c != b'-' {
return (i, false);
}
let mut count = 1;
let mut nextc;
loop {
i += 1;
if i >= line.len() {
return (i, false);
}
nextc = line[i];
if nextc == c {
count += 1;
} else if nextc != b' ' && nextc != b'\t' {
break;
}
}
if count >= 3 && (nextc == b'\r' || nextc == b'\n') {
((i - self.first_nonspace) + 1, true)
} else {
(i, false)
}
}
fn scan_thematic_break(&mut self, line: &[u8]) -> Option<usize> {
let (offset, found) = self.scan_thematic_break_inner(line);
if !found {
self.thematic_break_kill_pos = offset;
None
} else {
Some(offset)
}
}
fn find_first_nonspace(&mut self, line: &[u8]) {
let mut chars_to_tab = TAB_STOP - (self.column % TAB_STOP);
if self.first_nonspace <= self.offset {
self.first_nonspace = self.offset;
self.first_nonspace_column = self.column;
loop {
if self.first_nonspace >= line.len() {
break;
}
match line[self.first_nonspace] {
32 => {
self.first_nonspace += 1;
self.first_nonspace_column += 1;
chars_to_tab -= 1;
if chars_to_tab == 0 {
chars_to_tab = TAB_STOP;
}
}
9 => {
self.first_nonspace += 1;
self.first_nonspace_column += chars_to_tab;
chars_to_tab = TAB_STOP;
}
_ => break,
}
}
}
self.indent = self.first_nonspace_column - self.column;
self.blank = self.first_nonspace < line.len()
&& strings::is_line_end_char(line[self.first_nonspace]);
}
fn process_line(&mut self, line: &[u8]) {
let mut new_line: Vec<u8>;
let line = if line.is_empty() || !strings::is_line_end_char(*line.last().unwrap()) {
new_line = line.into();
new_line.push(b'\n');
&new_line
} else {
line
};
self.curline_len = line.len();
self.curline_end_col = line.len();
if self.curline_end_col > 0 && line[self.curline_end_col - 1] == b'\n' {
self.curline_end_col -= 1;
}
if self.curline_end_col > 0 && line[self.curline_end_col - 1] == b'\r' {
self.curline_end_col -= 1;
}
self.offset = 0;
self.column = 0;
self.first_nonspace = 0;
self.first_nonspace_column = 0;
self.indent = 0;
self.thematic_break_kill_pos = 0;
self.blank = false;
self.partially_consumed_tab = false;
if self.line_number == 0
&& line.len() >= 3
&& unsafe { str::from_utf8_unchecked(line) }.starts_with('\u{feff}')
{
self.offset += 3;
}
self.line_number += 1;
let mut all_matched = true;
if let Some(last_matched_container) = self.check_open_blocks(line, &mut all_matched) {
let mut container = last_matched_container;
let current = self.current;
self.open_new_blocks(&mut container, line, all_matched);
if current.same_node(self.current) {
self.add_text_to_container(container, last_matched_container, line);
}
}
self.last_line_length = self.curline_end_col;
self.curline_len = 0;
self.curline_end_col = 0;
}
fn check_open_blocks(
&mut self,
line: &[u8],
all_matched: &mut bool,
) -> Option<&'a AstNode<'a>> {
let (new_all_matched, mut container, should_continue) =
self.check_open_blocks_inner(self.root, line);
*all_matched = new_all_matched;
if !*all_matched {
container = container.parent().unwrap();
}
if !should_continue {
None
} else {
Some(container)
}
}
fn check_open_blocks_inner(
&mut self,
mut container: &'a AstNode<'a>,
line: &[u8],
) -> (bool, &'a AstNode<'a>, bool) {
let mut should_continue = true;
while nodes::last_child_is_open(container) {
container = container.last_child().unwrap();
let ast = &mut *container.data.borrow_mut();
self.find_first_nonspace(line);
match ast.value {
NodeValue::BlockQuote => {
if !self.parse_block_quote_prefix(line) {
return (false, container, should_continue);
}
}
NodeValue::Item(ref nl) => {
if !self.parse_node_item_prefix(line, container, nl) {
return (false, container, should_continue);
}
}
NodeValue::DescriptionItem(ref di) => {
if !self.parse_description_item_prefix(line, container, di) {
return (false, container, should_continue);
}
}
NodeValue::CodeBlock(..) => {
if !self.parse_code_block_prefix(line, container, ast, &mut should_continue) {
return (false, container, should_continue);
}
}
NodeValue::HtmlBlock(ref nhb) => {
if !self.parse_html_block_prefix(nhb.block_type) {
return (false, container, should_continue);
}
}
NodeValue::Paragraph => {
if self.blank {
return (false, container, should_continue);
}
}
NodeValue::Table(..) => {
if !table::matches(&line[self.first_nonspace..]) {
return (false, container, should_continue);
}
continue;
}
NodeValue::Heading(..) | NodeValue::TableRow(..) | NodeValue::TableCell => {
return (false, container, should_continue);
}
NodeValue::FootnoteDefinition(..) => {
if !self.parse_footnote_definition_block_prefix(line) {
return (false, container, should_continue);
}
}
NodeValue::MultilineBlockQuote(..) => {
if !self.parse_multiline_block_quote_prefix(
line,
container,
ast,
&mut should_continue,
) {