-
Notifications
You must be signed in to change notification settings - Fork 128
/
markdown.d
9529 lines (8383 loc) · 326 KB
/
markdown.d
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
/++
MD4C: Markdown parser for C
(http://github.com/mity/md4c)
Copyright:
Copyright (c) 2016-2019 Martin Mitas
Copyright (c) 2019 Guillaume Piolat (D translation as commonmarkd package: https://github.com/AuburnSounds/commonmark-d )
Somewhat modified by Adam D. Ruppe in 2024.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
+/
module arsd.markdown;
/// Options for Markdown parsing.
enum MarkdownFlag : int
{
collapseWhitespace = 0x0001, /** Collapse non-trivial whitespace into single ' ' */
permissiveATXHeaders = 0x0002, /** Do not require space in ATX headers ( ###header ) */
permissiveURLAutoLinks = 0x0004, /** Recognize URLs as autolinks even without '<', '>' */
permissiveEmailAutoLinks = 0x0008, /** Recognize e-mails as autolinks even without '<', '>' and 'mailto:' */
noIndentedCodeBlocks = 0x0010, /** Disable indented code blocks. (Only fenced code works.) */
noHTMLBlocks = 0x0020, /** Disable raw HTML blocks. */
noHTMLSpans = 0x0040, /** Disable raw HTML (inline). */
tablesExtension = 0x0100, /** Enable tables extension. */
enableStrikeThrough = 0x0200, /** Enable strikethrough extension. */
permissiveWWWAutoLinks = 0x0400, /** Enable WWW autolinks (even without any scheme prefix, if they begin with 'www.') */
enableTaskLists = 0x0800, /** Enable task list extension. */
latexMathSpans = 0x1000, /** Enable $ and $$ containing LaTeX equations. */
permissiveAutoLinks = permissiveEmailAutoLinks | permissiveURLAutoLinks | permissiveWWWAutoLinks, /** Recognize e-mails, URL and WWW links */
noHTML = noHTMLBlocks | noHTMLSpans, /** Disable raw HTML. */
/* Convenient sets of flags corresponding to well-known Markdown dialects.
*
* Note we may only support subset of features of the referred dialect.
* The constant just enables those extensions which bring us as close as
* possible given what features we implement.
*
* ABI compatibility note: Meaning of these can change in time as new
* extensions, bringing the dialect closer to the original, are implemented.
*/
dialectCommonMark = 0, /** CommonMark */
dialectGitHub = (permissiveAutoLinks | tablesExtension | enableStrikeThrough | enableTaskLists), /** Github Flavoured Markdown */
}
/// Parses a Markdown input, returns HTML. `flags` set the particular Markdown dialect that is used.
string convertMarkdownToHTML(const(char)[] input, MarkdownFlag flags = MarkdownFlag.dialectCommonMark)
{
import core.stdc.stdlib;
static struct GrowableBuffer
{
nothrow:
@nogc:
char* buf = null;
size_t size = 0;
size_t allocated = 0;
void ensureSize(size_t atLeastthisSize)
{
if (atLeastthisSize > allocated)
{
allocated = 2 * allocated + atLeastthisSize + 1; // TODO: enhancing this estimation probably beneficial to performance
buf = cast(char*) realloc(buf, allocated);
}
}
~this()
{
if (buf)
{
free(buf);
buf = null;
size = 0;
allocated = 0;
}
}
void append(const(char)[] suffix)
{
size_t L = suffix.length;
ensureSize(size + L);
buf[size..size+L] = suffix[0..L];
size += L;
}
const(char)[] getData()
{
return buf[0..size];
}
static void appendCallback(const(char)* chars, uint size, void* userData)
{
GrowableBuffer* gb = cast(GrowableBuffer*) userData;
gb.append(chars[0..size]);
}
}
GrowableBuffer gb;
gb.ensureSize(input.length); // TODO: enhancing this estimation probably beneficial to performance
//int renderFlags = MD_RENDER_FLAG_DEBUG;
int renderFlags = 0;
int ret = md_render_html(input.ptr,
cast(uint) input.length,
&GrowableBuffer.appendCallback,
&gb, flags, renderFlags);
return gb.getData.idup; // Note: this is the only GC-using stuff
}
import core.stdc.string;
import core.stdc.stdio;
import core.stdc.stdlib: malloc, free;
nothrow:
@nogc:
@system:
// Compatibility with older DMDFE
static if (__VERSION__ < 2079)
{
import core.stdc.stdlib: _compare_fp_t;
// Provide @nogc nothrow bsearch and qsort for older compilers
extern (C):
@system:
inout(void)* bsearch(scope const void* key, scope inout(void)* base, size_t nmemb, size_t size, _compare_fp_t compar);
void qsort(scope void* base, size_t nmemb, size_t size, _compare_fp_t compar);
}
else
{
import core.stdc.stdlib: qsort, bsearch;
}
alias MD_CHAR = char;
alias MD_SIZE = uint;
alias MD_OFFSET = uint;
/* Block represents a part of document hierarchy structure like a paragraph
* or list item.
*/
alias MD_BLOCKTYPE = int;
enum : MD_BLOCKTYPE
{
/* <body>...</body> */
MD_BLOCK_DOC = 0,
/* <blockquote>...</blockquote> */
MD_BLOCK_QUOTE,
/* <ul>...</ul>
* Detail: Structure MD_BLOCK_UL_DETAIL. */
MD_BLOCK_UL,
/* <ol>...</ol>
* Detail: Structure MD_BLOCK_OL_DETAIL. */
MD_BLOCK_OL,
/* <li>...</li>
* Detail: Structure MD_BLOCK_LI_DETAIL. */
MD_BLOCK_LI,
/* <hr> */
MD_BLOCK_HR,
/* <h1>...</h1> (for levels up to 6)
* Detail: Structure MD_BLOCK_H_DETAIL. */
MD_BLOCK_H,
/* <pre><code>...</code></pre>
* Note the text lines within code blocks are terminated with '\n'
* instead of explicit MD_TEXT_BR. */
MD_BLOCK_CODE,
/* Raw HTML block. This itself does not correspond to any particular HTML
* tag. The contents of it _is_ raw HTML source intended to be put
* in verbatim form to the HTML output. */
MD_BLOCK_HTML,
/* <p>...</p> */
MD_BLOCK_P,
/* <table>...</table> and its contents.
* Detail: Structure MD_BLOCK_TD_DETAIL (used with MD_BLOCK_TH and MD_BLOCK_TD)
* Note all of these are used only if extension MD_FLAG_TABLES is enabled. */
MD_BLOCK_TABLE,
MD_BLOCK_THEAD,
MD_BLOCK_TBODY,
MD_BLOCK_TR,
MD_BLOCK_TH,
MD_BLOCK_TD
}
/* Span represents an in-line piece of a document which should be rendered with
* the same font, color and other attributes. A sequence of spans forms a block
* like paragraph or list item. */
alias MD_SPANTYPE = int;
enum : MD_SPANTYPE
{
/* <em>...</em> */
MD_SPAN_EM,
/* <strong>...</strong> */
MD_SPAN_STRONG,
/* <a href="xxx">...</a>
* Detail: Structure MD_SPAN_A_DETAIL. */
MD_SPAN_A,
/* <img src="xxx">...</a>
* Detail: Structure MD_SPAN_IMG_DETAIL.
* Note: Image text can contain nested spans and even nested images.
* If rendered into ALT attribute of HTML <IMG> tag, it's responsibility
* of the renderer to deal with it.
*/
MD_SPAN_IMG,
/* <code>...</code> */
MD_SPAN_CODE,
/* <del>...</del>
* Note: Recognized only when MD_FLAG_STRIKETHROUGH is enabled.
*/
MD_SPAN_DEL,
/* For recognizing inline ($) and display ($$) equations
* Note: Recognized only when MD_FLAG_LATEXMATHSPANS is enabled.
*/
MD_SPAN_LATEXMATH,
MD_SPAN_LATEXMATH_DISPLAY
}
/* Text is the actual textual contents of span. */
alias MD_TEXTTYPE = int;
enum : MD_TEXTTYPE
{
/* Normal text. */
MD_TEXT_NORMAL = 0,
/* null character. CommonMark requires replacing null character with
* the replacement char U+FFFD, so this allows caller to do that easily. */
MD_TEXT_NULLCHAR,
/* Line breaks.
* Note these are not sent from blocks with verbatim output (MD_BLOCK_CODE
* or MD_BLOCK_HTML). In such cases, '\n' is part of the text itself. */
MD_TEXT_BR, /* <br> (hard break) */
MD_TEXT_SOFTBR, /* '\n' in source text where it is not semantically meaningful (soft break) */
/* Entity.
* (a) Named entity, e.g.
* (Note MD4C does not have a list of known entities.
* Anything matching the regexp /&[A-Za-z][A-Za-z0-9]{1,47};/ is
* treated as a named entity.)
* (b) Numerical entity, e.g. Ӓ
* (c) Hexadecimal entity, e.g. ካ
*
* As MD4C is mostly encoding agnostic, application gets the verbatim
* entity text into the MD_RENDERER::text_callback(). */
MD_TEXT_ENTITY,
/* Text in a code block (inside MD_BLOCK_CODE) or inlined code (`code`).
* If it is inside MD_BLOCK_CODE, it includes spaces for indentation and
* '\n' for new lines. MD_TEXT_BR and MD_TEXT_SOFTBR are not sent for this
* kind of text. */
MD_TEXT_CODE,
/* Text is a raw HTML. If it is contents of a raw HTML block (i.e. not
* an inline raw HTML), then MD_TEXT_BR and MD_TEXT_SOFTBR are not used.
* The text contains verbatim '\n' for the new lines. */
MD_TEXT_HTML,
/* Text is inside an equation. This is processed the same way as inlined code
* spans (`code`). */
MD_TEXT_LATEXMATH
}
/* Alignment enumeration. */
alias MD_ALIGN = int;
enum : MD_ALIGN
{
MD_ALIGN_DEFAULT = 0, /* When unspecified. */
MD_ALIGN_LEFT,
MD_ALIGN_CENTER,
MD_ALIGN_RIGHT
}
/* String attribute.
*
* This wraps strings which are outside of a normal text flow and which are
* propagated within various detailed structures, but which still may contain
* string portions of different types like e.g. entities.
*
* So, for example, lets consider an image has a title attribute string
* set to "foo " bar". (Note the string size is 14.)
*
* Then the attribute MD_SPAN_IMG_DETAIL::title shall provide the following:
* -- [0]: "foo " (substr_types[0] == MD_TEXT_NORMAL; substr_offsets[0] == 0)
* -- [1]: """ (substr_types[1] == MD_TEXT_ENTITY; substr_offsets[1] == 4)
* -- [2]: " bar" (substr_types[2] == MD_TEXT_NORMAL; substr_offsets[2] == 10)
* -- [3]: (n/a) (n/a ; substr_offsets[3] == 14)
*
* Note that these conditions are guaranteed:
* -- substr_offsets[0] == 0
* -- substr_offsets[LAST+1] == size
* -- Only MD_TEXT_NORMAL, MD_TEXT_ENTITY, MD_TEXT_NULLCHAR substrings can appear.
*/
struct MD_ATTRIBUTE
{
const (MD_CHAR)* text;
MD_SIZE size;
const (MD_TEXTTYPE)* substr_types;
const (MD_OFFSET)* substr_offsets;
}
/* Detailed info for MD_BLOCK_UL. */
struct MD_BLOCK_UL_DETAIL
{
int is_tight; /* Non-zero if tight list, zero if loose. */
MD_CHAR mark; /* Item bullet character in MarkDown source of the list, e.g. '-', '+', '*'. */
}
/* Detailed info for MD_BLOCK_OL. */
struct MD_BLOCK_OL_DETAIL
{
uint start; /* Start index of the ordered list. */
int is_tight; /* Non-zero if tight list, zero if loose. */
MD_CHAR mark_delimiter; /* Character delimiting the item marks in MarkDown source, e.g. '.' or ')' */
}
/* Detailed info for MD_BLOCK_LI. */
struct MD_BLOCK_LI_DETAIL
{
int is_task; /* Can be non-zero only with MD_FLAG_TASKLISTS */
MD_CHAR task_mark; /* If is_task, then one of 'x', 'X' or ' '. Undefined otherwise. */
MD_OFFSET task_mark_offset; /* If is_task, then offset in the input of the char between '[' and ']'. */
}
/* Detailed info for MD_BLOCK_H. */
struct MD_BLOCK_H_DETAIL
{
uint level; /* Header level (1 - 6) */
}
/* Detailed info for MD_BLOCK_CODE. */
struct MD_BLOCK_CODE_DETAIL
{
MD_ATTRIBUTE info;
MD_ATTRIBUTE lang;
MD_CHAR fence_char; /* The character used for fenced code block; or zero for indented code block. */
}
/* Detailed info for MD_BLOCK_TH and MD_BLOCK_TD. */
struct MD_BLOCK_TD_DETAIL
{
MD_ALIGN align_;
}
/* Detailed info for MD_SPAN_A. */
struct MD_SPAN_A_DETAIL
{
MD_ATTRIBUTE href;
MD_ATTRIBUTE title;
}
/* Detailed info for MD_SPAN_IMG. */
struct MD_SPAN_IMG_DETAIL
{
MD_ATTRIBUTE src;
MD_ATTRIBUTE title;
}
/* Flags specifying extensions/deviations from CommonMark specification.
*
* By default (when MD_RENDERER::flags == 0), we follow CommonMark specification.
* The following flags may allow some extensions or deviations from it.
*/
enum
{
MD_FLAG_COLLAPSEWHITESPACE = 0x0001, /* In MD_TEXT_NORMAL, collapse non-trivial whitespace into single ' ' */
MD_FLAG_PERMISSIVEATXHEADERS = 0x0002, /* Do not require space in ATX headers ( ###header ) */
MD_FLAG_PERMISSIVEURLAUTOLINKS = 0x0004, /* Recognize URLs as autolinks even without '<', '>' */
MD_FLAG_PERMISSIVEEMAILAUTOLINKS = 0x0008, /* Recognize e-mails as autolinks even without '<', '>' and 'mailto:' */
MD_FLAG_NOINDENTEDCODEBLOCKS = 0x0010, /* Disable indented code blocks. (Only fenced code works.) */
MD_FLAG_NOHTMLBLOCKS = 0x0020, /* Disable raw HTML blocks. */
MD_FLAG_NOHTMLSPANS = 0x0040, /* Disable raw HTML (inline). */
MD_FLAG_TABLES = 0x0100, /* Enable tables extension. */
MD_FLAG_STRIKETHROUGH = 0x0200, /* Enable strikethrough extension. */
MD_FLAG_PERMISSIVEWWWAUTOLINKS = 0x0400, /* Enable WWW autolinks (even without any scheme prefix, if they begin with 'www.') */
MD_FLAG_TASKLISTS = 0x0800, /* Enable task list extension. */
MD_FLAG_LATEXMATHSPANS = 0x1000, /* Enable $ and $$ containing LaTeX equations. */
MD_FLAG_PERMISSIVEAUTOLINKS = MD_FLAG_PERMISSIVEEMAILAUTOLINKS | MD_FLAG_PERMISSIVEURLAUTOLINKS | MD_FLAG_PERMISSIVEWWWAUTOLINKS,
MD_FLAG_NOHTML = MD_FLAG_NOHTMLBLOCKS | MD_FLAG_NOHTMLSPANS,
/* Convenient sets of flags corresponding to well-known Markdown dialects.
*
* Note we may only support subset of features of the referred dialect.
* The constant just enables those extensions which bring us as close as
* possible given what features we implement.
*
* ABI compatibility note: Meaning of these can change in time as new
* extensions, bringing the dialect closer to the original, are implemented.
*/
MD_DIALECT_COMMONMARK = 0,
MD_DIALECT_GITHUB = (MD_FLAG_PERMISSIVEAUTOLINKS | MD_FLAG_TABLES | MD_FLAG_STRIKETHROUGH | MD_FLAG_TASKLISTS),
}
/* Renderer structure.
*/
struct MD_PARSER
{
nothrow:
@nogc:
/* Reserved. Set to zero.
*/
uint abi_version;
/* Dialect options. Bitmask of MD_FLAG_xxxx values.
*/
uint flags;
/* Caller-provided rendering callbacks.
*
* For some block/span types, more detailed information is provided in a
* type-specific structure pointed by the argument 'detail'.
*
* The last argument of all callbacks, 'userdata', is just propagated from
* md_parse() and is available for any use by the application.
*
* Note any strings provided to the callbacks as their arguments or as
* members of any detail structure are generally not zero-terminated.
* Application has take the respective size information into account.
*
* Callbacks may abort further parsing of the document by returning non-zero.
*/
int function(MD_BLOCKTYPE /*type*/, void* /*detail*/, void* /*userdata*/) enter_block;
int function(MD_BLOCKTYPE /*type*/, void* /*detail*/, void* /*userdata*/) leave_block;
int function(MD_SPANTYPE /*type*/, void* /*detail*/, void* /*userdata*/) enter_span;
int function(MD_SPANTYPE /*type*/, void* /*detail*/, void* /*userdata*/) leave_span;
int function(MD_TEXTTYPE /*type*/, const(MD_CHAR)* /*text*/, MD_SIZE /*size*/, void* /*userdata*/) text;
/* Debug callback. Optional (may be null).
*
* If provided and something goes wrong, this function gets called.
* This is intended for debugging and problem diagnosis for developers;
* it is not intended to provide any errors suitable for displaying to an
* end user.
*/
void function(const(char)* /*msg*/, void* /*userdata*/) debug_log;
/* Reserved. Set to null.
*/
void function() syntax;
}
/*****************************
*** Miscellaneous Stuff ***
*****************************/
/* Misc. macros. */
enum TRUE = 1;
enum FALSE = 0;
/************************
*** Internal Types ***
************************/
/* These are omnipresent so lets save some typing. */
alias CHAR = MD_CHAR;
alias SZ = MD_SIZE;
alias OFF = MD_OFFSET;
/* During analyzes of inline marks, we need to manage some "mark chains",
* of (yet unresolved) openers. This structure holds start/end of the chain.
* The chain internals are then realized through MD_MARK::prev and ::next.
*/
struct MD_MARKCHAIN
{
int head; /* Index of first mark in the chain, or -1 if empty. */
int tail; /* Index of last mark in the chain, or -1 if empty. */
}
enum OPENERS_CHAIN_FIRST = 2;
enum OPENERS_CHAIN_LAST = 11;
/* Context propagated through all the parsing. */
struct MD_CTX
{
nothrow:
@nogc:
/* Immutable stuff (parameters of md_parse()). */
const(CHAR)* text;
SZ size;
MD_PARSER parser;
void* userdata;
/* When this is true, it allows some optimizations. */
int doc_ends_with_newline;
/* Helper temporary growing buffer. */
CHAR* buffer;
uint alloc_buffer;
/* Reference definitions. */
MD_REF_DEF* ref_defs;
int n_ref_defs;
int alloc_ref_defs;
void** ref_def_hashtable;
int ref_def_hashtable_size;
/* Stack of inline/span markers.
* This is only used for parsing a single block contents but by storing it
* here we may reuse the stack for subsequent blocks; i.e. we have fewer
* (re)allocations. */
MD_MARK* marks;
int n_marks;
int alloc_marks;
ubyte[256] mark_char_map;
/* For resolving of inline spans. */
MD_MARKCHAIN[12] mark_chains;
MD_MARKCHAIN* PTR_CHAIN() return { return &mark_chains[0]; }
MD_MARKCHAIN* TABLECELLBOUNDARIES() return { return &mark_chains[1]; }
MD_MARKCHAIN* ASTERISK_OPENERS_extraword_mod3_0() return { return &mark_chains[2]; }
MD_MARKCHAIN* ASTERISK_OPENERS_extraword_mod3_1() return { return &mark_chains[3]; }
MD_MARKCHAIN* ASTERISK_OPENERS_extraword_mod3_2() return { return &mark_chains[4]; }
MD_MARKCHAIN* ASTERISK_OPENERS_intraword_mod3_0() return { return &mark_chains[5]; }
MD_MARKCHAIN* ASTERISK_OPENERS_intraword_mod3_1() return { return &mark_chains[6]; }
MD_MARKCHAIN* ASTERISK_OPENERS_intraword_mod3_2() return { return &mark_chains[7]; }
MD_MARKCHAIN* UNDERSCORE_OPENERS() return { return &mark_chains[8]; }
MD_MARKCHAIN* TILDE_OPENERS() return { return &mark_chains[9]; }
MD_MARKCHAIN* BRACKET_OPENERS() return { return &mark_chains[10]; }
MD_MARKCHAIN* DOLLAR_OPENERS() return { return &mark_chains[11]; }
int n_table_cell_boundaries;
/* For resolving links. */
int unresolved_link_head;
int unresolved_link_tail;
/* For resolving raw HTML. */
OFF html_comment_horizon;
OFF html_proc_instr_horizon;
OFF html_decl_horizon;
OFF html_cdata_horizon;
/* For block analysis.
* Notes:
* -- It holds MD_BLOCK as well as MD_LINE structures. After each
* MD_BLOCK, its (multiple) MD_LINE(s) follow.
* -- For MD_BLOCK_HTML and MD_BLOCK_CODE, MD_VERBATIMLINE(s) are used
* instead of MD_LINE(s).
*/
void* block_bytes;
MD_BLOCK* current_block;
int n_block_bytes;
int alloc_block_bytes;
/* For container block analysis. */
MD_CONTAINER* containers;
int n_containers;
int alloc_containers;
/* Minimal indentation to call the block "indented code block". */
uint code_indent_offset;
/* Contextual info for line analysis. */
SZ code_fence_length; /* For checking closing fence length. */
int html_block_type; /* For checking closing raw HTML condition. */
int last_line_has_list_loosening_effect;
int last_list_item_starts_with_two_blank_lines;
void MD_LOG(const(char)* msg)
{
if(parser.debug_log != null)
parser.debug_log(msg, userdata);
}
/* Character accessors. */
CHAR CH(OFF off)
{
return text[off];
}
const(CHAR)* STR(OFF off)
{
return text + off;
}
bool ISANYOF(OFF off, const(CHAR)* palette) { return ISANYOF_(CH(off), palette); }
bool ISANYOF2(OFF off, CHAR ch1, CHAR ch2) { return ISANYOF2_(CH(off), ch1, ch2); }
bool ISANYOF3(OFF off, CHAR ch1, CHAR ch2, CHAR ch3) { return ISANYOF3_(CH(off), ch1, ch2, ch3); }
bool ISASCII(OFF off) { return ISASCII_(CH(off)); }
bool ISBLANK(OFF off) { return ISBLANK_(CH(off)); }
bool ISNEWLINE(OFF off) { return ISNEWLINE_(CH(off)); }
bool ISWHITESPACE(OFF off) { return ISWHITESPACE_(CH(off)); }
bool ISCNTRL(OFF off) { return ISCNTRL_(CH(off)); }
bool ISPUNCT(OFF off) { return ISPUNCT_(CH(off)); }
bool ISUPPER(OFF off) { return ISUPPER_(CH(off)); }
bool ISLOWER(OFF off) { return ISLOWER_(CH(off)); }
bool ISALPHA(OFF off) { return ISALPHA_(CH(off)); }
bool ISDIGIT(OFF off) { return ISDIGIT_(CH(off)); }
bool ISXDIGIT(OFF off) { return ISXDIGIT_(CH(off)); }
bool ISALNUM(OFF off) { return ISALNUM_(CH(off)); }
}
alias MD_LINETYPE = int;
enum : MD_LINETYPE
{
MD_LINE_BLANK,
MD_LINE_HR,
MD_LINE_ATXHEADER,
MD_LINE_SETEXTHEADER,
MD_LINE_SETEXTUNDERLINE,
MD_LINE_INDENTEDCODE,
MD_LINE_FENCEDCODE,
MD_LINE_HTML,
MD_LINE_TEXT,
MD_LINE_TABLE,
MD_LINE_TABLEUNDERLINE
}
struct MD_LINE_ANALYSIS
{
nothrow:
@nogc:
short type_;
ushort data_;
MD_LINETYPE type() const
{
return type_;
}
void type(MD_LINETYPE value)
{
type_ = cast(short)value;
}
int data() const
{
return data_;
}
void data(uint value)
{
data_ = cast(ushort)value;
}
OFF beg;
OFF end;
uint indent; /* Indentation level. */
}
struct MD_LINE
{
OFF beg;
OFF end;
}
struct MD_VERBATIMLINE
{
OFF beg;
OFF end;
OFF indent;
}
/*****************
*** Helpers ***
*****************/
pure
{
/* Character classification.
* Note we assume ASCII compatibility of code points < 128 here. */
bool ISIN_(CHAR ch, CHAR ch_min, CHAR ch_max)
{
return (ch_min <= cast(uint)(ch) && cast(uint)(ch) <= ch_max);
}
bool ISANYOF_(CHAR ch, const(CHAR)* palette)
{
return md_strchr(palette, ch) != null;
}
bool ISANYOF2_(CHAR ch, CHAR ch1, CHAR ch2)
{
return (ch == ch1) || (ch == ch2);
}
bool ISANYOF3_(CHAR ch, CHAR ch1, CHAR ch2, CHAR ch3)
{
return (ch == ch1) || (ch == ch2) || (ch == ch3);
}
bool ISASCII_(CHAR ch)
{
return (cast(uint)ch) <= 127;
}
bool ISBLANK_(CHAR ch)
{
return ISANYOF2_(ch, ' ', '\t');
}
bool ISNEWLINE_(CHAR ch)
{
return ISANYOF2_(ch, '\r', '\n');
}
bool ISWHITESPACE_(CHAR ch)
{
return ISBLANK_(ch) || ISANYOF2_(ch, '\v', '\f');
}
bool ISCNTRL_(CHAR ch)
{
return (cast(uint)(ch) <= 31 || cast(uint)(ch) == 127);
}
bool ISPUNCT_(CHAR ch)
{
return ISIN_(ch, 33, 47) || ISIN_(ch, 58, 64) || ISIN_(ch, 91, 96) || ISIN_(ch, 123, 126);
}
bool ISUPPER_(CHAR ch)
{
return ISIN_(ch, 'A', 'Z');
}
bool ISLOWER_(CHAR ch)
{
return ISIN_(ch, 'a', 'z');
}
bool ISALPHA_(CHAR ch)
{
return ISUPPER_(ch) || ISLOWER_(ch);
}
bool ISDIGIT_(CHAR ch)
{
return ISIN_(ch, '0', '9');
}
bool ISXDIGIT_(CHAR ch)
{
return ISDIGIT_(ch) || ISIN_(ch, 'A', 'F') || ISIN_(ch, 'a', 'f');
}
bool ISALNUM_(CHAR ch)
{
return ISALPHA_(ch) || ISDIGIT_(ch);
}
}
const(CHAR)* md_strchr(const(CHAR)* str, CHAR ch) pure
{
OFF i;
for(i = 0; str[i] != '\0'; i++) {
if(ch == str[i])
return (str + i);
}
return null;
}
/* Case insensitive check of string equality. */
int md_ascii_case_eq(const(CHAR)* s1, const(CHAR)* s2, SZ n)
{
OFF i;
for(i = 0; i < n; i++) {
CHAR ch1 = s1[i];
CHAR ch2 = s2[i];
if(ISLOWER_(ch1))
ch1 += ('A'-'a');
if(ISLOWER_(ch2))
ch2 += ('A'-'a');
if(ch1 != ch2)
return FALSE;
}
return TRUE;
}
int md_ascii_eq(const(CHAR)* s1, const(CHAR)* s2, SZ n)
{
return memcmp(s1, s2, n * CHAR.sizeof) == 0;
}
int md_text_with_null_replacement(MD_CTX* ctx, MD_TEXTTYPE type, const(CHAR)* str, SZ size)
{
OFF off = 0;
int ret = 0;
while(1) {
while(off < size && str[off] != '\0')
off++;
if(off > 0) {
ret = ctx.parser.text(type, str, off, ctx.userdata);
if(ret != 0)
return ret;
str += off;
size -= off;
off = 0;
}
if(off >= size)
return 0;
ret = ctx.parser.text(MD_TEXT_NULLCHAR, "", 1, ctx.userdata);
if(ret != 0)
return ret;
off++;
}
}
int MD_TEMP_BUFFER(MD_CTX* ctx, SZ sz)
{
if(sz > ctx.alloc_buffer)
{
CHAR* new_buffer;
SZ new_size = ((sz) + (sz) / 2 + 128) & ~127;
new_buffer = cast(CHAR*) realloc_safe(ctx.buffer, new_size);
if (new_buffer == null)
{
ctx.MD_LOG("realloc() failed.");
return -1;
}
ctx.buffer = new_buffer;
ctx.alloc_buffer = new_size;
}
return 0;
}
int MD_ENTER_BLOCK(MD_CTX* ctx, MD_BLOCKTYPE type, void* arg)
{
int ret = ctx.parser.enter_block(type, arg, ctx.userdata);
if(ret != 0)
{
ctx.MD_LOG("Aborted from enter_block() callback.");
return ret;
}
return 0;
}
int MD_LEAVE_BLOCK(MD_CTX* ctx, MD_BLOCKTYPE type, void* arg)
{
int ret = ctx.parser.leave_block(type, arg, ctx.userdata);
if(ret != 0)
{
ctx.MD_LOG("Aborted from leave_block() callback.");
return ret;
}
return 0;
}
int MD_ENTER_SPAN(MD_CTX* ctx, MD_SPANTYPE type, void* arg)
{
int ret = ctx.parser.enter_span(type, arg, ctx.userdata);
if(ret != 0)
{
ctx.MD_LOG("Aborted from enter_span() callback.");
return ret;
}
return 0;
}
int MD_LEAVE_SPAN(MD_CTX* ctx, MD_SPANTYPE type, void* arg)
{
int ret = ctx.parser.leave_span(type, arg, ctx.userdata);
if(ret != 0)
{
ctx.MD_LOG("Aborted from leave_span() callback.");
return ret;
}
return 0;
}
int MD_TEXT(MD_CTX* ctx, MD_TEXTTYPE type, const(MD_CHAR)* str, MD_SIZE size)
{
if(size > 0)
{
int ret = ctx.parser.text((type), (str), (size), ctx.userdata);
if (ret != 0)
{
ctx.MD_LOG("Aborted from text() callback.");
return ret;
}
}
return 0;
}
int MD_TEXT_INSECURE(MD_CTX* ctx, MD_TEXTTYPE type, const(MD_CHAR)* str, MD_SIZE size)
{
if(size > 0)
{
int ret = md_text_with_null_replacement(ctx, type, str, size);
if(ret != 0)
{
ctx.MD_LOG("Aborted from text() callback.");
return ret;
}
}
return 0;
}
/*************************
*** Unicode Support ***
*************************/
struct MD_UNICODE_FOLD_INFO
{
uint[3] codepoints;
int n_codepoints;
};
/* Binary search over sorted "map" of codepoints. Consecutive sequences
* of codepoints may be encoded in the map by just using the
* (MIN_CODEPOINT | 0x40000000) and (MAX_CODEPOINT | 0x80000000).
*
* Returns index of the found record in the map (in the case of ranges,
* the minimal value is used); or -1 on failure. */
int md_unicode_bsearch__(uint codepoint, const(uint)* map, size_t map_size)
{
int beg, end;
int pivot_beg, pivot_end;
beg = 0;
end = cast(int) map_size-1;
while(beg <= end) {
/* Pivot may be a range, not just a single value. */
pivot_beg = pivot_end = (beg + end) / 2;
if(map[pivot_end] & 0x40000000)
pivot_end++;
if(map[pivot_beg] & 0x80000000)
pivot_beg--;
if(codepoint < (map[pivot_beg] & 0x00ffffff))
end = pivot_beg - 1;
else if(codepoint > (map[pivot_end] & 0x00ffffff))
beg = pivot_end + 1;
else
return pivot_beg;
}
return -1;
}
bool md_is_unicode_whitespace__(uint codepoint)
{
/* Unicode "Zs" category.
* (generated by scripts/build_whitespace_map.py) */
static immutable uint[] WHITESPACE_MAP =
[
0x0020, 0x00a0, 0x1680, 0x2000| 0x40000000, 0x200a | 0x80000000, 0x202f, 0x205f, 0x3000
];
/* The ASCII ones are the most frequently used ones, also CommonMark
* specification requests few more in this range. */