-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathFlexmarkHtmlConverter.java
More file actions
1723 lines (1465 loc) · 72.2 KB
/
FlexmarkHtmlConverter.java
File metadata and controls
1723 lines (1465 loc) · 72.2 KB
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
package com.vladsch.flexmark.html2md.converter;
import com.vladsch.flexmark.ast.Reference;
import com.vladsch.flexmark.html.renderer.HeaderIdGeneratorFactory;
import com.vladsch.flexmark.html.renderer.LinkStatus;
import com.vladsch.flexmark.html.renderer.LinkType;
import com.vladsch.flexmark.html.renderer.ResolvedLink;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.builder.BuilderBase;
import com.vladsch.flexmark.util.data.DataHolder;
import com.vladsch.flexmark.util.data.DataKey;
import com.vladsch.flexmark.util.data.MutableDataHolder;
import com.vladsch.flexmark.util.data.ScopedDataSet;
import com.vladsch.flexmark.util.dependency.DependencyResolver;
import com.vladsch.flexmark.util.format.TableFormatOptions;
import com.vladsch.flexmark.util.format.options.TableCaptionHandling;
import com.vladsch.flexmark.util.html.Attribute;
import com.vladsch.flexmark.util.html.Attributes;
import com.vladsch.flexmark.util.html.CellAlignment;
import com.vladsch.flexmark.util.html.MutableAttributes;
import com.vladsch.flexmark.util.misc.Extension;
import com.vladsch.flexmark.util.misc.Ref;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import com.vladsch.flexmark.util.sequence.LineAppendable;
import com.vladsch.flexmark.util.sequence.LineAppendableImpl;
import com.vladsch.flexmark.util.sequence.builder.ISequenceBuilder;
import com.vladsch.flexmark.util.sequence.builder.StringSequenceBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.vladsch.flexmark.util.sequence.LineAppendable.*;
/**
* Renders a tree of nodes to HTML.
* <p>
* Start with the {@link #builder} method to configure the renderer. Example:
* <pre><code>
* HtmlRenderer renderer = builder().escapeHtml(true).build();
* renderer.render(node);
* </code></pre>
*/
@SuppressWarnings("WeakerAccess")
public class FlexmarkHtmlConverter {
/**
* output control for FormattingAppendable, see {@link LineAppendable#setOptions(int)}
*/
final public static DataKey<Integer> FORMAT_FLAGS = new DataKey<>("FORMAT_FLAGS", F_TRIM_TRAILING_WHITESPACE | F_TRIM_LEADING_WHITESPACE | F_COLLAPSE_WHITESPACE | F_TRIM_LEADING_EOL | F_PREFIX_PRE_FORMATTED);
final public static DataKey<Integer> MAX_BLANK_LINES = new DataKey<>("MAX_BLANK_LINES", 2);
final public static DataKey<Integer> MAX_TRAILING_BLANK_LINES = new DataKey<>("MAX_TRAILING_BLANK_LINES", 1);
final public static DataKey<Boolean> LIST_CONTENT_INDENT = new DataKey<>("LIST_CONTENT_INDENT", true);
final public static DataKey<Boolean> SETEXT_HEADINGS = new DataKey<>("SETEXT_HEADINGS", true);
final public static DataKey<Boolean> OUTPUT_UNKNOWN_TAGS = new DataKey<>("OUTPUT_UNKNOWN_TAGS", false);
final public static DataKey<Boolean> TYPOGRAPHIC_QUOTES = new DataKey<>("TYPOGRAPHIC_QUOTES", true);
final public static DataKey<Boolean> TYPOGRAPHIC_SMARTS = new DataKey<>("TYPOGRAPHIC_SMARTS", true);
final public static DataKey<Boolean> EXTRACT_AUTO_LINKS = new DataKey<>("EXTRACT_AUTO_LINKS", true);
final public static DataKey<Boolean> OUTPUT_ATTRIBUTES_ID = new DataKey<>("OUTPUT_ATTRIBUTES_ID", true);
final public static DataKey<String> OUTPUT_ATTRIBUTES_NAMES_REGEX = new DataKey<>("OUTPUT_ATTRIBUTES_NAMES_REGEX", "");
final public static DataKey<Boolean> WRAP_AUTO_LINKS = new DataKey<>("WRAP_AUTO_LINKS", true);
final public static DataKey<Boolean> RENDER_COMMENTS = new DataKey<>("RENDER_COMMENTS", false);
final public static DataKey<Boolean> DOT_ONLY_NUMERIC_LISTS = new DataKey<>("DOT_ONLY_NUMERIC_LISTS", true);
final public static DataKey<Boolean> COMMENT_ORIGINAL_NON_NUMERIC_LIST_ITEM = new DataKey<>("COMMENT_ORIGINAL_NON_NUMERIC_LIST_ITEM", false);
final public static DataKey<Boolean> PRE_CODE_PRESERVE_EMPHASIS = new DataKey<>("PRE_CODE_PRESERVE_EMPHASIS", false);
final public static DataKey<Character> ORDERED_LIST_DELIMITER = new DataKey<>("ORDERED_LIST_DELIMITER", '.');
final public static DataKey<Character> UNORDERED_LIST_DELIMITER = new DataKey<>("UNORDERED_LIST_DELIMITER", '*');
final public static DataKey<Integer> DEFINITION_MARKER_SPACES = new DataKey<>("DEFINITION_MARKER_SPACES", 3);
final public static DataKey<Integer> MIN_SETEXT_HEADING_MARKER_LENGTH = new DataKey<>("MIN_SETEXT_HEADING_MARKER_LENGTH", 3);
final public static DataKey<Integer> LIST_ITEM_INDENT = new DataKey<>("LIST_ITEM_INDENT", 4);
final public static DataKey<String> CODE_INDENT = new DataKey<>("CODE_INDENT", " ");
final public static DataKey<String> NBSP_TEXT = new DataKey<>("NBSP_TEXT", " ");
final public static DataKey<String> EOL_IN_TITLE_ATTRIBUTE = new DataKey<>("EOL_IN_TITLE_ATTRIBUTE", " ");
final public static DataKey<String> THEMATIC_BREAK = new DataKey<>("THEMATIC_BREAK", "*** ** * ** ***");
// Render HTML contents - UNWRAPPED
final public static DataKey<String[]> UNWRAPPED_TAGS = new DataKey<>("UNWRAPPED_TAGS", new String[] {
"article",
"address",
"frameset",
"section",
"small",
"iframe",
});
// Render HTML contents - WRAPPED in original HTML tag
final public static DataKey<String[]> WRAPPED_TAGS = new DataKey<>("WRAPPED_TAGS", new String[] {
"kbd",
"var",
});
// regex to use for processing id attributes, if matched then will concatenate all groups which are not empty, if result string is empty after trimming then no id will be generated
// if value empty then no processing is done
final public static DataKey<String> OUTPUT_ID_ATTRIBUTE_REGEX = new DataKey<>("OUTPUT_ID_ATTRIBUTE_REGEX", "^user-content-(.*)$");
@Deprecated final public static DataKey<Integer> TABLE_MIN_SEPARATOR_COLUMN_WIDTH = TableFormatOptions.FORMAT_TABLE_MIN_SEPARATOR_COLUMN_WIDTH;
@Deprecated final public static DataKey<Integer> TABLE_MIN_SEPARATOR_DASHES = TableFormatOptions.FORMAT_TABLE_MIN_SEPARATOR_DASHES;
@Deprecated final public static DataKey<Boolean> TABLE_LEAD_TRAIL_PIPES = TableFormatOptions.FORMAT_TABLE_LEAD_TRAIL_PIPES;
@Deprecated final public static DataKey<Boolean> TABLE_SPACE_AROUND_PIPES = TableFormatOptions.FORMAT_TABLE_SPACE_AROUND_PIPES;
@Deprecated final public static DataKey<TableCaptionHandling> TABLE_CAPTION = TableFormatOptions.FORMAT_TABLE_CAPTION;
final public static DataKey<Boolean> LISTS_END_ON_DOUBLE_BLANK = new DataKey<>("LISTS_END_ON_DOUBLE_BLANK", false);
final public static DataKey<Boolean> DIV_AS_PARAGRAPH = new DataKey<>("DIV_AS_PARAGRAPH", false);
final public static DataKey<Boolean> BR_AS_PARA_BREAKS = new DataKey<>("BR_AS_PARA_BREAKS", true);
final public static DataKey<Boolean> BR_AS_EXTRA_BLANK_LINES = new DataKey<>("BR_AS_EXTRA_BLANK_LINES", true);
final public static DataKey<Boolean> DIV_TABLE_PROCESSING = new DataKey<>("DIV_TABLE_PROCESSING", false);
final public static DataKey<String[]> DIV_TABLE_HDR_CLASSES = new DataKey<>("DIV_TABLE_HDR_CLASSES", new String[] {
"wt-data-grid__row_header",
});
final public static DataKey<String[]> DIV_TABLE_ROW_CLASSES = new DataKey<>("DIV_TABLE_ROW_CLASSES", new String[] {
"wt-data-grid__row",
});
final public static DataKey<String[]> DIV_TABLE_CELL_CLASSES = new DataKey<>("DIV_TABLE_CELL_CLASSES", new String[] {
"wt-data-grid__cell",
});
final public static DataKey<Boolean> ADD_TRAILING_EOL = new DataKey<>("ADD_TRAILING_EOL", true);
final public static DataKey<Boolean> SKIP_HEADING_1 = new DataKey<>("SKIP_HEADING_1", false);
final public static DataKey<Boolean> SKIP_HEADING_2 = new DataKey<>("SKIP_HEADING_2", false);
final public static DataKey<Boolean> SKIP_HEADING_3 = new DataKey<>("SKIP_HEADING_3", false);
final public static DataKey<Boolean> SKIP_HEADING_4 = new DataKey<>("SKIP_HEADING_4", false);
final public static DataKey<Boolean> SKIP_HEADING_5 = new DataKey<>("SKIP_HEADING_5", false);
final public static DataKey<Boolean> SKIP_HEADING_6 = new DataKey<>("SKIP_HEADING_6", false);
final public static DataKey<Boolean> SKIP_ATTRIBUTES = new DataKey<>("SKIP_ATTRIBUTES", false);
final public static DataKey<Boolean> SKIP_FENCED_CODE = new DataKey<>("SKIP_FENCED_CODE", false);
final public static DataKey<Boolean> SKIP_CHAR_ESCAPE = new DataKey<>("SKIP_CHAR_ESCAPE", false);
final public static DataKey<ExtensionConversion> EXT_INLINE_STRONG = new DataKey<>("EXT_INLINE_STRONG", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_INLINE_EMPHASIS = new DataKey<>("EXT_INLINE_EMPHASIS", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_INLINE_CODE = new DataKey<>("EXT_INLINE_CODE", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_INLINE_DEL = new DataKey<>("EXT_INLINE_DEL", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_INLINE_INS = new DataKey<>("EXT_INLINE_INS", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_INLINE_SUB = new DataKey<>("EXT_INLINE_SUB", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_INLINE_SUP = new DataKey<>("EXT_INLINE_SUP", ExtensionConversion.MARKDOWN);
final public static DataKey<ExtensionConversion> EXT_MATH = new DataKey<>("EXT_MATH", ExtensionConversion.HTML);
final public static DataKey<ExtensionConversion> EXT_TABLES = new DataKey<>("EXT_TABLES", ExtensionConversion.MARKDOWN);
final public static DataKey<LinkConversion> EXT_INLINE_LINK = new DataKey<>("EXT_INLINE_LINK", LinkConversion.MARKDOWN_EXPLICIT);
final public static DataKey<LinkConversion> EXT_INLINE_IMAGE = new DataKey<>("EXT_INLINE_IMAGE", LinkConversion.MARKDOWN_EXPLICIT);
final public static DataKey<Ref<com.vladsch.flexmark.util.ast.Document>> FOR_DOCUMENT = new DataKey<>("FOR_DOCUMENT", new Ref<>(null));
final public static DataKey<Map<String, String>> TYPOGRAPHIC_REPLACEMENT_MAP = new DataKey<>("TYPOGRAPHIC_REPLACEMENT_MAP", new HashMap<>());
/**
* if true then will dump HTML tree of body element to console when using {@link #convert(String, Appendable)}(String)
*/
final public static DataKey<Boolean> DUMP_HTML_TREE = new DataKey<>("DUMP_HTML_TREE", false);
/**
* If true then will ignore rows with th columns after rows with td columns have been
* emitted to the table.
* <p>
* If false then will convert these to regular columns.
*/
final public static DataKey<Boolean> IGNORE_TABLE_HEADING_AFTER_ROWS = new DataKey<>("IGNORE_TABLE_HEADING_AFTER_ROWS", true);
// HTML node names (all lowercase)
final public static String A_NODE = "a";
final public static String ABBR_NODE = "abbr";
final public static String ASIDE_NODE = "aside";
final public static String BR_NODE = "br";
final public static String BLOCKQUOTE_NODE = "blockquote";
final public static String CODE_NODE = "code";
final public static String IMG_NODE = "img";
final public static String DEL_NODE = "del";
final public static String STRIKE_NODE = "strike";
final public static String DIV_NODE = "div";
final public static String DD_NODE = "dd";
final public static String DL_NODE = "dl";
final public static String DT_NODE = "dt";
final public static String I_NODE = "i";
final public static String EM_NODE = "em";
final public static String B_NODE = "b";
final public static String STRONG_NODE = "strong";
final public static String EMOJI_NODE = "g-emoji";
final public static String INPUT_NODE = "input";
final public static String INS_NODE = "ins";
final public static String U_NODE = "u";
final public static String SUB_NODE = "sub";
final public static String SUP_NODE = "sup";
final public static String HR_NODE = "hr";
final public static String OL_NODE = "ol";
final public static String UL_NODE = "ul";
final public static String LI_NODE = "li";
final public static String TABLE_NODE = "table";
final public static String TBODY_NODE = "tbody";
final public static String TD_NODE = "td";
final public static String TH_NODE = "th";
final public static String THEAD_NODE = "thead";
final public static String TR_NODE = "tr";
final public static String CAPTION_NODE = "caption";
final public static String SVG_NODE = "svg";
final public static String P_NODE = "p";
final public static String PRE_NODE = "pre";
final public static String MATH_NODE = "math";
final public static String SPAN_NODE = "span";
final public static String TEXT_NODE = "#text";
final public static String COMMENT_NODE = "#comment";
final public static String H1_NODE = "h1";
final public static String H2_NODE = "h2";
final public static String H3_NODE = "h3";
final public static String H4_NODE = "h4";
final public static String H5_NODE = "h5";
final public static String H6_NODE = "h6";
final public static String DEFAULT_NODE = "";
final public static String[] HEADING_NODES = {
H1_NODE,
H2_NODE,
H3_NODE,
H4_NODE,
H5_NODE,
H6_NODE,
};
public static String[] EXPLICIT_LINK_TEXT_TAGS = new String[] { IMG_NODE };
final private static Map<Object, CellAlignment> TABLE_CELL_ALIGNMENTS = new LinkedHashMap<>();
static {
TABLE_CELL_ALIGNMENTS.put(Pattern.compile("\\bleft\\b"), CellAlignment.LEFT);
TABLE_CELL_ALIGNMENTS.put(Pattern.compile("\\bcenter\\b"), CellAlignment.CENTER);
TABLE_CELL_ALIGNMENTS.put(Pattern.compile("\\bright\\b"), CellAlignment.RIGHT);
TABLE_CELL_ALIGNMENTS.put("text-left", CellAlignment.LEFT);
TABLE_CELL_ALIGNMENTS.put("text-center", CellAlignment.CENTER);
TABLE_CELL_ALIGNMENTS.put("text-right", CellAlignment.RIGHT);
}
static final Map<String, String> SPECIAL_CHARS_MAP = new HashMap<>();
final private static String TYPOGRAPHIC_QUOTES_PIPED = "“|”|‘|’|«|»|“|”|‘|’|'|«|»";
final private static String TYPOGRAPHIC_SMARTS_PIPED = "…|–|—|…|&endash;|&emdash;";
static {
SPECIAL_CHARS_MAP.put("“", "\"");
SPECIAL_CHARS_MAP.put("”", "\"");
SPECIAL_CHARS_MAP.put("“", "\"");
SPECIAL_CHARS_MAP.put("”", "\"");
SPECIAL_CHARS_MAP.put("‘", "'");
SPECIAL_CHARS_MAP.put("’", "'");
SPECIAL_CHARS_MAP.put("‘", "'");
SPECIAL_CHARS_MAP.put("’", "'");
SPECIAL_CHARS_MAP.put("'", "'");
SPECIAL_CHARS_MAP.put("«", "<<");
SPECIAL_CHARS_MAP.put("«", "<<");
SPECIAL_CHARS_MAP.put("»", ">>");
SPECIAL_CHARS_MAP.put("»", ">>");
SPECIAL_CHARS_MAP.put("…", "...");
SPECIAL_CHARS_MAP.put("…", "...");
SPECIAL_CHARS_MAP.put("–", "--");
SPECIAL_CHARS_MAP.put("&endash;", "--");
SPECIAL_CHARS_MAP.put("—", "---");
SPECIAL_CHARS_MAP.put("&emdash;", "---");
}
final public static DataKey<Map<Object, CellAlignment>> TABLE_CELL_ALIGNMENT_MAP = new DataKey<>("TABLE_CELL_ALIGNMENT_MAP", TABLE_CELL_ALIGNMENTS);
final HtmlConverterOptions htmlConverterOptions;
final private DataHolder options;
final List<DelegatingNodeRendererFactoryWrapper> nodeRendererFactories;
final List<HtmlLinkResolverFactory> linkResolverFactories;
FlexmarkHtmlConverter(Builder builder) {
this.options = builder.toImmutable();
this.htmlConverterOptions = new HtmlConverterOptions(this.options);
List<HtmlNodeRendererFactory> nodeConverterFactories = new ArrayList<>(builder.nodeRendererFactories.size() + 1);
nodeConverterFactories.addAll(builder.nodeRendererFactories);
// resolve renderer dependencies
List<DelegatingNodeRendererFactoryWrapper> nodeRenderers = new ArrayList<>(nodeConverterFactories.size());
for (int i = nodeConverterFactories.size() - 1; i >= 0; i--) {
HtmlNodeRendererFactory nodeRendererFactory = nodeConverterFactories.get(i);
nodeRenderers.add(new DelegatingNodeRendererFactoryWrapper(nodeRenderers, nodeRendererFactory));
}
// Add as last. This means clients can override the rendering of core nodes if they want by default
HtmlConverterCoreNodeRendererFactory nodeRendererFactory = new HtmlConverterCoreNodeRendererFactory();
nodeRenderers.add(new DelegatingNodeRendererFactoryWrapper(nodeRenderers, nodeRendererFactory));
nodeRendererFactories = DependencyResolver.resolveFlatDependencies(nodeRenderers, null, dependent -> dependent.getFactory().getClass());
linkResolverFactories = DependencyResolver.resolveFlatDependencies(builder.linkResolverFactories, null, null);
}
public DataHolder getOptions() {
return options;
}
/**
* Create a new builder for configuring an {@link FlexmarkHtmlConverter}.
*
* @return a builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Create a new builder for configuring an {@link FlexmarkHtmlConverter}.
*
* @param options initialization options
* @return a builder
*/
public static Builder builder(DataHolder options) {
return new Builder(options);
}
/**
* Render a node to the appendable
*
* @param html html to convert to markdown
* @param output appendable to use for the output
*/
public void convert(@NotNull String html, @NotNull Appendable output) {
Document document = Jsoup.parse(html);
if (DUMP_HTML_TREE.get(getOptions())) {
LineAppendableImpl trace = new LineAppendableImpl(LineAppendable.F_TRIM_LEADING_EOL);
trace.setIndentPrefix(" ");
dumpHtmlTree(trace, document.body());
System.out.println(trace.toString(0, 0));
}
MainHtmlConverter converter = new MainHtmlConverter(options, new HtmlMarkdownWriter(htmlConverterOptions.formatFlags), document, null);
converter.render(document);
converter.flushTo(output, htmlConverterOptions.maxBlankLines, htmlConverterOptions.maxTrailingBlankLines);
}
/**
* Parse HTML with default options
*
* @param html html to be parsed
* @return resulting markdown string
*/
public String convert(@NotNull String html) {
return convert(html, 1);
}
/**
* Parse HTML with given options and max trailing blank lines
*
* @param html html to be parsed
* @param maxTrailingBlankLines max trailing blank lines, -1 will suppress trailing EOL
* @return resulting markdown string
*/
public String convert(@NotNull String html, int maxTrailingBlankLines) {
Document document = Jsoup.parse(html);
if (DUMP_HTML_TREE.get(getOptions())) {
LineAppendableImpl trace = new LineAppendableImpl(LineAppendable.F_TRIM_LEADING_EOL);
trace.setIndentPrefix(" ");
dumpHtmlTree(trace, document.body());
System.out.println(trace.toString(0, 0));
}
MainHtmlConverter converter = new MainHtmlConverter(options, new HtmlMarkdownWriter(htmlConverterOptions.formatFlags), document, null);
converter.render(document);
return converter.getMarkdown().toString(htmlConverterOptions.maxBlankLines, maxTrailingBlankLines);
}
public static void dumpHtmlTree(LineAppendable out, Node node) {
out.line().append(node.nodeName());
for (org.jsoup.nodes.Attribute attribute : node.attributes().asList()) {
out.append(' ').append(attribute.getKey()).append("=\"").append(attribute.getValue()).append("\"");
}
out.line().indent();
for (Node child : node.childNodes()) {
dumpHtmlTree(out, child);
}
out.unIndent();
}
/**
* Render a node to the appendable
*
* @param node node to render
* @param output appendable to use for the output
* @param maxTrailingBlankLines max blank lines allowed at end of output
*/
public void convert(Node node, Appendable output, int maxTrailingBlankLines) {
MainHtmlConverter renderer = new MainHtmlConverter(options, new HtmlMarkdownWriter(htmlConverterOptions.formatFlags), node.ownerDocument(), null);
renderer.render(node);
renderer.flushTo(output, htmlConverterOptions.maxBlankLines, maxTrailingBlankLines);
}
/**
* Render the tree of nodes to markdown
*
* @param node the root node
* @return the formatted markdown
*/
public String convert(Node node) {
StringBuilder sb = new StringBuilder();
convert(node, sb, 0);
return sb.toString();
}
/**
* Builder for configuring an {@link FlexmarkHtmlConverter}. See methods for default configuration.
*/
public static class Builder extends BuilderBase<Builder> {
List<HtmlNodeRendererFactory> nodeRendererFactories = new ArrayList<>();
List<HtmlLinkResolverFactory> linkResolverFactories = new ArrayList<>();
HeaderIdGeneratorFactory htmlIdGeneratorFactory = null;
public Builder() {
super();
}
public Builder(@Nullable DataHolder options) {
super(options);
loadExtensions();
}
/**
* @return the configured {@link FlexmarkHtmlConverter}
*/
@NotNull
public FlexmarkHtmlConverter build() {
return new FlexmarkHtmlConverter(this);
}
@Override
protected void removeApiPoint(@NotNull Object apiPoint) {
if (apiPoint instanceof HtmlNodeRendererFactory) this.nodeRendererFactories.remove(apiPoint);
else if (apiPoint instanceof HtmlLinkResolverFactory) this.linkResolverFactories.remove(apiPoint);
else if (apiPoint instanceof HeaderIdGeneratorFactory) this.htmlIdGeneratorFactory = null;
else {
throw new IllegalStateException("Unknown data point type: " + apiPoint.getClass().getName());
}
}
@Override
protected void preloadExtension(@NotNull Extension extension) {
if (extension instanceof HtmlConverterExtension) {
HtmlConverterExtension htmlConverterExtension = (HtmlConverterExtension) extension;
htmlConverterExtension.rendererOptions(this);
}
}
@Override
protected boolean loadExtension(@NotNull Extension extension) {
if (extension instanceof HtmlConverterExtension) {
HtmlConverterExtension htmlConverterExtension = (HtmlConverterExtension) extension;
htmlConverterExtension.extend(this);
return true;
}
return false;
}
/**
* Add a factory for instantiating a node renderer (done when rendering). This allows to override the rendering
* of node types or define rendering for custom node types.
* <p>
* If multiple node renderers for the same node type are created, the one from the factory that was added first
* "wins". (This is how the rendering for core node types can be overridden; the default rendering comes last.)
*
* @param htmlNodeRendererFactory the factory for creating a node renderer
* @return {@code this}
*/
@SuppressWarnings("UnusedReturnValue")
public Builder htmlNodeRendererFactory(@NotNull HtmlNodeRendererFactory htmlNodeRendererFactory) {
this.nodeRendererFactories.add(htmlNodeRendererFactory);
return this;
}
/**
* Add a factory for instantiating a node renderer (done when rendering). This allows to override the rendering
* of node types or define rendering for custom node types.
* <p>
* If multiple node renderers for the same node type are created, the one from the factory that was added first
* "wins". (This is how the rendering for core node types can be overridden; the default rendering comes last.)
*
* @param linkResolverFactory the factory for creating a node renderer
* @return {@code this}
*/
@SuppressWarnings("UnusedReturnValue")
public Builder linkResolverFactory(@NotNull HtmlLinkResolverFactory linkResolverFactory) {
this.linkResolverFactories.add(linkResolverFactory);
addExtensionApiPoint(linkResolverFactory);
return this;
}
}
/**
* Extension for {@link FlexmarkHtmlConverter}.
*/
public interface HtmlConverterExtension extends Extension {
/**
* This method is called first on all extensions so that they can adjust the options.
*
* @param options option set that will be used for the builder
*/
void rendererOptions(@NotNull MutableDataHolder options);
void extend(@NotNull Builder builder);
}
final private static Iterator<Node> NULL_ITERATOR = new Iterator<Node>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Node next() {
return null;
}
@Override
public void remove() {
}
};
final public static Iterable<Node> NULL_ITERABLE = () -> NULL_ITERATOR;
private class MainHtmlConverter extends HtmlNodeConverterSubContext {
final private @NotNull Document document;
final private @NotNull com.vladsch.flexmark.util.ast.Document myForDocument;
final private @NotNull Map<String, HtmlNodeRendererHandler<?>> renderers;
final private @NotNull List<PhasedHtmlNodeRenderer> phasedFormatters;
final private @NotNull Set<HtmlConverterPhase> renderingPhases;
final private @NotNull DataHolder myOptions;
private HtmlConverterPhase phase;
final private @NotNull HtmlConverterOptions myHtmlConverterOptions;
final private @Nullable Pattern specialCharsPattern;
final private @NotNull Stack<HtmlConverterState> myStateStack;
final private @NotNull Map<String, String> mySpecialCharsMap;
private @Nullable HtmlConverterState myState;
private boolean myTrace;
private boolean myInlineCode;
private @Nullable Parser myParser = null;
final private @NotNull HtmlLinkResolver[] myHtmlLinkResolvers;
final private @NotNull HashMap<String, Reference> myReferenceUrlToReferenceMap; // map of URL to reference node
final private @NotNull HashSet<Reference> myExternalReferences; // map of URL to reference node
@Override
public HtmlConverterState getState() {
return myState;
}
MainHtmlConverter(@NotNull DataHolder options, @NotNull HtmlMarkdownWriter out, @NotNull Document document, @Nullable DataHolder parentOptions) {
super(out);
this.myOptions = new ScopedDataSet(parentOptions, options);
this.renderers = new HashMap<>(32);
this.renderingPhases = new HashSet<>(HtmlConverterPhase.values().length);
this.phasedFormatters = new ArrayList<>(nodeRendererFactories.size());
this.myHtmlLinkResolvers = new HtmlLinkResolver[linkResolverFactories.size()];
out.setContext(this);
myHtmlConverterOptions = new HtmlConverterOptions(myOptions);
if (myHtmlConverterOptions.typographicQuotes && myHtmlConverterOptions.typographicSmarts) {
specialCharsPattern = Pattern.compile(TYPOGRAPHIC_QUOTES_PIPED + "|" + TYPOGRAPHIC_SMARTS_PIPED);
} else if (myHtmlConverterOptions.typographicQuotes) {
specialCharsPattern = Pattern.compile(TYPOGRAPHIC_QUOTES_PIPED);
} else if (myHtmlConverterOptions.typographicSmarts) {
specialCharsPattern = Pattern.compile(TYPOGRAPHIC_SMARTS_PIPED);
} else {
specialCharsPattern = null;
}
//myTrace = true;
myStateStack = new Stack<>();
myReferenceUrlToReferenceMap = new HashMap<>();
myExternalReferences = new HashSet<>();
myState = null;
Map<String, String> typographicReplacementMap = TYPOGRAPHIC_REPLACEMENT_MAP.get(myOptions);
if (!typographicReplacementMap.isEmpty()) {
mySpecialCharsMap = typographicReplacementMap;
} else {
mySpecialCharsMap = SPECIAL_CHARS_MAP;
}
// The first node renderer for a node type "wins".
for (int i = nodeRendererFactories.size() - 1; i >= 0; i--) {
HtmlNodeRendererFactory htmlNodeRendererFactory = nodeRendererFactories.get(i);
HtmlNodeRenderer htmlNodeRenderer = htmlNodeRendererFactory.apply(this.myOptions);
List<HtmlNodeRendererHandler<?>> formattingHandlers = htmlNodeRenderer.getHtmlNodeRendererHandlers();
if (formattingHandlers == null) continue;
for (HtmlNodeRendererHandler<?> nodeType : formattingHandlers) {
// Overwrite existing renderer
renderers.put(nodeType.getTagName(), nodeType);
}
if (htmlNodeRenderer instanceof PhasedHtmlNodeRenderer) {
Set<HtmlConverterPhase> phases = ((PhasedHtmlNodeRenderer) htmlNodeRenderer).getHtmlConverterPhases();
if (phases != null) {
if (phases.isEmpty()) throw new IllegalStateException("PhasedNodeFormatter with empty Phases");
this.renderingPhases.addAll(phases);
this.phasedFormatters.add((PhasedHtmlNodeRenderer) htmlNodeRenderer);
} else {
throw new IllegalStateException("PhasedNodeFormatter with null Phases");
}
}
}
for (int i = 0; i < linkResolverFactories.size(); i++) {
myHtmlLinkResolvers[i] = linkResolverFactories.get(i).apply(this);
}
this.document = document;
this.myForDocument = FlexmarkHtmlConverter.FOR_DOCUMENT.get(options).value;
}
@SuppressWarnings("WeakerAccess")
private class SubHtmlNodeConverter extends HtmlNodeConverterSubContext implements HtmlNodeConverterContext {
final private MainHtmlConverter myMainNodeRenderer;
final private DataHolder myOptions;
SubHtmlNodeConverter(@NotNull MainHtmlConverter mainNodeRenderer, @NotNull HtmlMarkdownWriter out, @Nullable DataHolder options) {
super(out);
myMainNodeRenderer = mainNodeRenderer;
myOptions = options == null || options == myMainNodeRenderer.getOptions() ? myMainNodeRenderer.getOptions() : new ScopedDataSet(myMainNodeRenderer.getOptions(), options);
}
@Override
public @NotNull DataHolder getOptions() {return myOptions;}
@Override
public @NotNull HtmlConverterOptions getHtmlConverterOptions() {return myMainNodeRenderer.getHtmlConverterOptions();}
@Override
public @NotNull Document getDocument() {return myMainNodeRenderer.getDocument();}
@Override
public HtmlConverterPhase getFormattingPhase() {return myMainNodeRenderer.getFormattingPhase();}
@Override
public void render(@NotNull Node node) {
myMainNodeRenderer.renderNode(node, this);
}
@Override
public Node getCurrentNode() {
return myRenderingNode;
}
@Override
public @NotNull HtmlNodeConverterContext getSubContext() {
return getSubContext(myOptions, StringSequenceBuilder.emptyBuilder());
}
@Override
public @NotNull HtmlNodeConverterContext getSubContext(@Nullable DataHolder options) {
return getSubContext(options, StringSequenceBuilder.emptyBuilder());
}
@Override
public @NotNull HtmlNodeConverterContext getSubContext(@Nullable DataHolder options, @NotNull ISequenceBuilder<?, ?> builder) {
HtmlMarkdownWriter writer = new HtmlMarkdownWriter(builder, this.markdown.getOptions());
writer.setContext(this);
//noinspection ReturnOfInnerClass
return new SubHtmlNodeConverter(myMainNodeRenderer, writer, options == null || options == myOptions ? myOptions : new ScopedDataSet(myOptions, options));
}
@Override
public void renderChildren(@NotNull Node parent, boolean outputAttributes, Runnable prePopAction) {
FlexmarkHtmlConverter.processHtmlTree(this, parent, outputAttributes, prePopAction);
}
@Nullable
@Override
public com.vladsch.flexmark.util.ast.Document getForDocument() {
return myMainNodeRenderer.getForDocument();
}
@Override
public @NotNull ResolvedLink resolveLink(@NotNull LinkType linkType, @NotNull CharSequence url, Boolean urlEncode) {
return myMainNodeRenderer.resolveLink(linkType, url, urlEncode);
}
@Override
public @NotNull ResolvedLink resolveLink(@NotNull LinkType linkType, @NotNull CharSequence url, Attributes attributes, Boolean urlEncode) {
return myMainNodeRenderer.resolveLink(linkType, url, attributes, urlEncode);
}
@Override
public void pushState(@NotNull Node parent) {
myMainNodeRenderer.pushState(parent);
}
@Override
public void popState(@Nullable LineAppendable out) {
myMainNodeRenderer.popState(out);
}
@Override
public void processAttributes(@NotNull Node node) {
myMainNodeRenderer.processAttributes(node);
}
@Override
public int outputAttributes(@NotNull LineAppendable out, @NotNull String initialSep) {
return myMainNodeRenderer.outputAttributes(out, initialSep);
}
@Override
public void transferIdToParent() {
myMainNodeRenderer.transferIdToParent();
}
@Override
public void transferToParentExcept(String... excludes) {
myMainNodeRenderer.transferToParentExcept(excludes);
}
@Override
public void transferToParentOnly(String... includes) {
myMainNodeRenderer.transferToParentOnly(includes);
}
@Override
public @Nullable Node peek() {
return myMainNodeRenderer.peek();
}
@Override
public @Nullable Node peek(int skip) {
return myMainNodeRenderer.peek(skip);
}
@Override
public @Nullable Node next() {
return myMainNodeRenderer.next();
}
@Override
public void skip() {
myMainNodeRenderer.skip();
}
@Override
public @Nullable Node next(int skip) {
return myMainNodeRenderer.next(skip);
}
@Override
public void skip(int skip) {
myMainNodeRenderer.skip(skip);
}
@Override
public void delegateRender() {
myMainNodeRenderer.renderByPreviousHandler(this);
}
@Override
public @NotNull HashMap<String, Reference> getReferenceUrlToReferenceMap() {
return myMainNodeRenderer.getReferenceUrlToReferenceMap();
}
@Override
public @NotNull HashSet<Reference> getExternalReferences() {
return myMainNodeRenderer.getExternalReferences();
}
@Override
public Reference getOrCreateReference(@NotNull String url, @NotNull String text, @Nullable String title) {
return myMainNodeRenderer.getOrCreateReference(url, text, title);
}
@Override
public com.vladsch.flexmark.util.ast.@NotNull Node parseMarkdown(@NotNull String markdown) {
return myMainNodeRenderer.parseMarkdown(markdown);
}
@Override
public void processUnwrapped(@NotNull Node element) {
myMainNodeRenderer.processUnwrapped(this, element);
}
@Override
public void processWrapped(@NotNull Node node, @Nullable Boolean isBlock, boolean escapeMarkdown) {
FlexmarkHtmlConverter.processWrapped(this, node, isBlock, escapeMarkdown);
}
@Override
public void appendOuterHtml(@NotNull Node node) {
FlexmarkHtmlConverter.appendOuterHtml(this, node);
}
@Override
public boolean isInlineCode() {
return myMainNodeRenderer.isInlineCode();
}
@Override
public void setInlineCode(boolean inlineCode) {
myMainNodeRenderer.setInlineCode(inlineCode);
}
@Override
public void inlineCode(@NotNull Runnable inlineRunnable) {
myMainNodeRenderer.inlineCode(inlineRunnable);
}
@Override
public @NotNull String escapeSpecialChars(@NotNull String text) {
return myMainNodeRenderer.escapeSpecialChars(text);
}
@Override
public @NotNull String prepareText(@NotNull String text) {
return myMainNodeRenderer.prepareText(text);
}
@Override
public @NotNull String prepareText(@NotNull String text, boolean inCode) {
return myMainNodeRenderer.prepareText(text, inCode);
}
@Override
public @NotNull String processTextNodes(@NotNull Node node) {
return myMainNodeRenderer.processTextNodes(node);
}
@Override
public void excludeAttributes(String... excludes) {
myMainNodeRenderer.excludeAttributes(excludes);
}
@Override
public void processTextNodes(@NotNull Node node, boolean stripIdAttribute) {
processTextNodes(node, stripIdAttribute, null, null);
}
@Override
public void processTextNodes(@NotNull Node node, boolean stripIdAttribute, @NotNull CharSequence wrapText) {
processTextNodes(node, stripIdAttribute, wrapText, wrapText);
}
@Override
public void processTextNodes(@NotNull Node node, boolean stripIdAttribute, @Nullable CharSequence textPrefix, @Nullable CharSequence textSuffix) {
FlexmarkHtmlConverter.processTextNodes(this, node, stripIdAttribute, textPrefix, textSuffix);
}
@Override
public void wrapTextNodes(@NotNull Node node, @NotNull CharSequence wrapText, boolean needSpaceAround) {
FlexmarkHtmlConverter.wrapTextNodes(this, node, wrapText, needSpaceAround);
}
@Override
public void processConditional(@NotNull ExtensionConversion extensionConversion, @NotNull Node node, @NotNull Runnable processNode) {
FlexmarkHtmlConverter.processConditional(this, extensionConversion, node, processNode);
}
@Override
public void renderDefault(@NotNull Node node) {
FlexmarkHtmlConverter.processDefault(this, node, getHtmlConverterOptions().outputUnknownTags);
}
@Override
public HtmlConverterState getState() {
return myMainNodeRenderer.getState();
}
@Override
public boolean isTrace() {
return myMainNodeRenderer.isTrace();
}
@Override
public void setTrace(boolean trace) {
myMainNodeRenderer.setTrace(trace);
}
@Override
public @NotNull Stack<HtmlConverterState> getStateStack() {
return myMainNodeRenderer.getStateStack();
}
}
@Override
public @NotNull HashMap<String, Reference> getReferenceUrlToReferenceMap() {
return myReferenceUrlToReferenceMap;
}
@Override
public @NotNull HashSet<Reference> getExternalReferences() {
return myExternalReferences;
}
@Override
public boolean isTrace() {
return myTrace;
}
@Override
public @NotNull Stack<HtmlConverterState> getStateStack() {
return myStateStack;
}
@Override
public void setTrace(boolean trace) {
myTrace = trace;
}
@Override
public com.vladsch.flexmark.util.ast.@NotNull Node parseMarkdown(@NotNull String markdown) {
if (myParser == null) {
myParser = Parser.builder(myOptions).build();
}
return myParser.parse(markdown);
}
@Override
public Reference getOrCreateReference(@NotNull String url, @NotNull String text, @Nullable String title) {
Reference reference = myReferenceUrlToReferenceMap.get(url);
if (reference != null) {
if (title != null && !title.trim().isEmpty()) {
if (reference.getTitle().isBlank()) {
// just add it to the existing reference
reference.setTitle(BasedSequence.of(title).subSequence(0, ((CharSequence) title).length()));
return reference;
} else if (reference.getTitle().equals(title.trim())) {
return reference;
}
}
return reference;
}
// create a new one with URL and if no conflict with text as id
String referenceId = text;
if (myReferenceUrlToReferenceMap.containsKey(referenceId)) {
for (int i = 1; ; i++) {
referenceId = text + "_" + i;
if (!myReferenceUrlToReferenceMap.containsKey(referenceId)) {
break;
}
}
}
StringBuilder sb = new StringBuilder().append("[").append(referenceId).append("]: ").append(url);
if (title != null && !title.trim().isEmpty()) {
sb.append(" '").append(title.replace("'", "\\'")).append("'");
}
com.vladsch.flexmark.util.ast.Node document = parseMarkdown(sb.toString());
com.vladsch.flexmark.util.ast.Node firstChild = document.getFirstChild();
if (firstChild instanceof Reference) {
reference = (Reference) firstChild;
myReferenceUrlToReferenceMap.put(url, reference);
return reference;
}
return null;
}
@Override
public @NotNull ResolvedLink resolveLink(@NotNull LinkType linkType, @NotNull CharSequence url, Boolean urlEncode) {
return resolveLink(linkType, url, null, urlEncode);
}
@Override
public @NotNull ResolvedLink resolveLink(@NotNull LinkType linkType, @NotNull CharSequence url, Attributes attributes, Boolean urlEncode) {
// Resolved links not cached to allow resolving to different targets by more than URL
//HashMap<String, ResolvedLink> resolvedLinks = resolvedLinkMap.computeIfAbsent(linkType, k -> new HashMap<String, ResolvedLink>());
String urlSeq = String.valueOf(url);
//ResolvedLink resolvedLink = resolvedLinks.get(urlSeq);
ResolvedLink resolvedLink;
//if (resolvedLink == null) {
resolvedLink = new ResolvedLink(linkType, urlSeq, attributes);
if (!urlSeq.isEmpty()) {
Node currentNode = getCurrentNode();
for (HtmlLinkResolver htmlLinkResolver : myHtmlLinkResolvers) {
resolvedLink = htmlLinkResolver.resolveLink(currentNode, this, resolvedLink);
if (resolvedLink.getStatus() != LinkStatus.UNKNOWN) break;
}
}
// put it in the map
//resolvedLinks.put(urlSeq, resolvedLink);
//}
return resolvedLink;
}
@Nullable
@Override
public Node getCurrentNode() {