public
Description: An implementation of markdown in C, using a PEG grammar
Clone URL: git://github.com/jgm/peg-markdown.git
jgm (author)
Thu May 08 14:31:54 -0700 2008
commit  320bdab8acb58a5ee6a043aa4571638810d50889
tree    b3d37c34a2deca924e279026ebefa3d74ec85b59
parent  8d8f6e2ba51b14b098052c9d4d0cef164cd6f1ad
peg-markdown / markdown_parser.leg
100644 776 lines (595 sloc) 30.404 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
%{
/**********************************************************************
 
  markdown_parser.leg - markdown parser in C using a PEG grammar.
  (c) 2008 John MacFarlane (jgm at berkeley dot edu).
 
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.
 
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.
 
 ***********************************************************************/
 
#include <stdbool.h>
#include <assert.h>
#include "markdown_peg.h"
 
extern int strcasecmp(const char *string1, const char *string2);
int yyparse(void);
 
/**********************************************************************
 
  List manipulation functions
 
 ***********************************************************************/
 
/* cons - cons an element onto a list, returning pointer to new head */
static element *cons(element new, element *list) {
    element *head = malloc(sizeof(element));
    assert(head != NULL);
    *head = new;
    (*head).next = list;
    return head;
}
 
/* pushelt - push an element onto the (list) contents of an element */
static void pushelt(element new, element *lst) {
    assert((*lst).key == LIST);
    (*lst).children = cons(new, (*lst).children);
}
 
/* reverse - reverse a list, returning pointer to new list */
static element *reverse(element *list) {
    element *new = NULL;
    while (list != NULL) {
        new = cons(*list, new);
        list = (*list).next;
    }
    return new;
}
 
/* length_of_strings - returns sum of length of strings in a list of STR elements */
static int length_of_strings(element *list) {
    int len = 0;
    while (list != NULL) {
        assert((*list).key == STR);
        assert((*list).contents.str != NULL);
        len += strlen((*list).contents.str);
        list = (*list).next;
    }
    return len;
}
 
/* concat_string_list - concatenates string contents of list of STR elements */
static char *concat_string_list(element *list) {
    char *result = malloc(length_of_strings(list) + 2); /* leave room for optional \n and \0 */
    *result = '\0';
    while (list != NULL) {
        assert((*list).key == STR);
        assert((*list).contents.str != NULL);
        result = strcat(result, (*list).contents.str);
        list = (*list).next;
    }
    return result;
}
 
/**********************************************************************
 
  Global variables used in parsing
 
 ***********************************************************************/
 
static char *charbuf = ""; /* Buffer of characters to be parsed. */
static element *references; /* List of link references found. */
static int output_format;
static element parse_result; /* Results of parse. */
static int syntax_extensions; /* Syntax extensions selected. */
 
/**********************************************************************
 
  Auxiliary functions for parsing actions.
  These make it easier to build up data structures (including lists)
  in the parsing actions.
 
 ***********************************************************************/
 
/* mk_str - constructor for STR element */
static element mk_str(char *string) {
    element result;
    assert(string != NULL);
    result.key = STR;
    result.contents.str = strdup(string);
    return result;
}
 
/* mk_list - constructs an element with key 'key' and children from 'lst' (reversed).
 * This is designed to be used with pushelt to build lists in a parser action.
 * The reversing is necessary because pushelt adds to the head of a list. */
static element mk_list(int key, element lst) {
    element result;
    result.key = key;
    result.children = reverse(lst.children);
    return result;
}
 
/* mk_link - constructor for LINK element */
static element mk_link(element *label, char *url, char *title) {
    element result;
    result.key = LINK;
    result.contents.link.label = label;
    result.contents.link.url = strdup(url);
    result.contents.link.title = strdup(title);
    return result;
}
 
/* match_inlines - returns true if inline lists match (case-insensitive...) */
static bool match_inlines(element *l1, element *l2) {
    while (l1 != NULL && l2 != NULL) {
        if ((*l1).key != (*l2).key)
            return false;
        switch ((*l1).key) {
        case SPACE:
        case LINEBREAK:
            break;
        case CODE:
        case STR:
        case HTML:
            if (strcasecmp((*l1).contents.str, (*l2).contents.str) == 0)
                break;
            else
                return false;
        case EMPH:
        case STRONG:
        case LIST:
            if (match_inlines((*l1).children, (*l2).children))
                break;
            else
                return false;
        case LINK:
        case IMAGE:
            return false; /* No links or images within links */
        default:
            fprintf(stderr, "match_inlines encountered unknown key = %d\n", (*l1).key);
            exit(EXIT_FAILURE);
            break;
        }
        l1 = (*l1).next;
        l2 = (*l2).next;
    }
    return (l1 == NULL && l2 == NULL); /* return true if both lists exhausted */
}
 
/* find_reference - return true if link found in references matching label.
 * 'link' is modified with the matching url and title. */
static bool find_reference(link *result, element *label) {
    element *cur = references; /* pointer to walk up list of references */
    link curitem;
    while (cur != NULL) {
        curitem = (*cur).contents.link;
        if (match_inlines(label, curitem.label)) {
            (*result) = curitem;
            return true;
        }
        else
            cur = (*cur).next;
    }
    return false;
}
 
/**********************************************************************
 
  Definitions for leg parser generator.
  YY_INPUT is the function the parser calls to get new input.
  We take all new input from (static) charbuf.
 
 ***********************************************************************/
 
# define YYSTYPE element
 
#define YY_INPUT(buf, result, max_size) \
{ \
    int yyc; \
    if (charbuf && *charbuf != '\0') { \
        yyc= *charbuf++; \
    } else { \
        yyc= EOF; \
    } \
    result= (EOF == yyc) ? 0 : (*(buf)= yyc, 1); \
}
 
/**********************************************************************
 
  PEG grammar and parser actions for markdown syntax.
 
 ***********************************************************************/
 
%}
 
Doc = a:Blocks BlankLine* Eof
            { parse_result = a; }
 
Blocks = a:StartList ( b:Block { pushelt(b, &a); } )*
            { $$ = mk_list(LIST, a); }
 
Block = BlankLine*
            ( BlockQuote
            | Verbatim
            | Reference
            | Heading
            | OrderedList
            | BulletList
            | HorizontalRule
            | HtmlBlock
            | Para
            | Plain )
 
Para = NonindentSpace a:Inlines BlankLine+
            { $$ = a; $$.key = PARA; }
 
Plain = a:Inlines
            { $$ = a; $$.key = PLAIN; }
 
AtxInline = !Newline !(Sp '#'* Sp Newline) Inline
 
AtxStart = < ( "######" | "#####" | "####" | "###" | "##" | "#" ) >
            { $$.key = H1 + (strlen(yytext) - 1); }
 
AtxHeading = s:AtxStart Sp a:StartList ( b:AtxInline { pushelt(b, &a); } )+ (Sp '#'* Sp)? Newline
            { $$ = mk_list(s.key, a); }
 
SetextHeading = SetextHeading1 | SetextHeading2
 
SetextHeadingInline = !Endline Inline
 
SetextHeading1 = a:StartList ( b:SetextHeadingInline { pushelt(b, &a); } )+ Newline "===" '='* Newline
                  { $$ = mk_list(H1, a); }
 
SetextHeading2 = a:StartList ( b:SetextHeadingInline { pushelt(b, &a) ; } )+ Newline "---" '-'* Newline
                  { $$ = mk_list(H2, a); }
 
Heading = AtxHeading | SetextHeading
 
BlockQuote = BlockQuoteRaw
 
BlockQuoteLine = '>' ' '? Line
 
BlockQuoteRaw = a:StartList ( b:BlockQuoteLine { pushelt(b, &a); } )+
                 { char *c = concat_string_list(reverse(a.children));
                     strcat(c, "\n"); /* Note: an extra byte was allocated for this */
                     $$.contents.str = c;
                     $$.key = BLOCKQUOTE;
                 }
 
NonblankIndentedLine = !BlankLine IndentedLine
 
VerbatimChunk = a:StartList
                ( c:BlankLine { pushelt(c, &a); } )*
                ( b:NonblankIndentedLine { pushelt(b, &a); } )+
                { $$ = mk_str(concat_string_list(reverse(a.children))); }
 
Verbatim = a:StartList ( b:VerbatimChunk { pushelt(b, &a); } )+
               { $$ = mk_str(concat_string_list(reverse(a.children))); $$.key = VERBATIM; }
 
HorizontalRule = NonindentSpace
                 ( '*' Sp '*' Sp '*' (Sp '*')*
                 | '-' Sp '-' Sp '-' (Sp '-')*
                 | '_' Sp '_' Sp '_' (Sp '_')*)
                 Sp Newline BlankLine+
                 { $$.key = HRULE; }
 
Bullet = NonindentSpace ('+' | '*' | '-') Spacechar+
 
BulletList = BulletListTight | BulletListLoose
 
BulletListTight = a:StartList ( b:BulletListItem { pushelt(b, &a); } )+ BlankLine* !BulletListLoose
                  { $$ = mk_list(BULLETLIST, a); }
 
BulletListLoose = a:StartList
                  ( b:BulletListItem BlankLine*
                    { char *bplus = malloc(strlen(b.contents.str) + 3);
                        strcpy(bplus, b.contents.str);
                        strcat(bplus, "\n\n"); /* In loose list, \n\n added to end of each element */
                        b = mk_str(bplus);
                        b.key = LISTITEM;
                        pushelt(b, &a);
                    } )+
                  { $$ = mk_list(BULLETLIST, a); }
 
BulletListItem = !HorizontalRule Bullet
                 a:StartList
                 b:BulletListBlock { pushelt(b, &a); }
                 ( c:BulletListContinuationBlock { pushelt(c, &a); } )*
                 { $$ = mk_str(concat_string_list(reverse(a.children))); $$.key = LISTITEM; }
 
BulletListBlock = a:StartList b:Line { pushelt(b, &a); } (c:ListBlockLine { pushelt(c, &a); })*
                  { $$ = mk_str(concat_string_list(reverse(a.children))); }
 
BulletListContinuationBlock = a:StartList
                              ( b:BlankLines
                                { if (strlen(b.contents.str) == 0)
                                         b.contents.str = strdup("\001"); /* block separator */
                                     pushelt(b, &a); } )
                              ( Indent c:BulletListBlock { pushelt(c, &a); } )+
                              { $$ = mk_str(concat_string_list(reverse(a.children))); }
 
Enumerator = NonindentSpace [0-9]+ '.' Spacechar+
 
OrderedList = OrderedListTight | OrderedListLoose
 
OrderedListTight = a:StartList
                   ( b:OrderedListItem { pushelt(b, &a); } )+
                   BlankLine* !OrderedListLoose
                   { $$ = mk_list(ORDEREDLIST, a); }
 
OrderedListLoose = a:StartList
                   ( b:OrderedListItem BlankLine*
                     { char *bplus = malloc(strlen(b.contents.str) + 3);
                        strcpy(bplus, b.contents.str);
                        strcat(bplus, "\n\n"); /* in loose list, add \n\n to end of each block */
                        b = mk_str(bplus);
                        b.key = LISTITEM;
                        pushelt(b, &a);
                     } )+
                   { $$ = mk_list(ORDEREDLIST, a); }
 
OrderedListItem = !HorizontalRule Enumerator
                    a:StartList
                    b:OrderedListBlock { pushelt(b, &a); }
                    ( c:OrderedListContinuationBlock { pushelt(c, &a); } )*
                    { $$ = mk_str(concat_string_list(reverse(a.children))); $$.key = LISTITEM; }
 
OrderedListBlock = a:StartList b:Line { pushelt(b, &a); }
                    ( c:ListBlockLine { pushelt(c, &a); } )*
                    { $$ = mk_str(concat_string_list(reverse(a.children))); }
 
OrderedListContinuationBlock = a:StartList
                              ( b:BlankLines
                                { if (strlen(b.contents.str) == 0)
                                         b.contents.str = strdup("\001"); /* block separator */
                                     pushelt(b, &a);
                                } )
                              ( Indent c:OrderedListBlock { pushelt(c, &a); } )+
                              { $$ = mk_str(concat_string_list(reverse(a.children))); }
 
BlankLines = < BlankLine* >
                { $$ = mk_str(yytext); }
 
ListBlockLine = !( Indent? ( BulletListItem | OrderedListItem ) )
                !BlankLine
                OptionallyIndentedLine
 
# Parsers for different kinds of block-level HTML content.
# This is repetitive due to constraints of PEG grammar.
 
HtmlBlockOpenAddress = '<' Spnl ("address" | "ADDRESS") Spnl HtmlAttribute* '>'
HtmlBlockCloseAddress = '<' Spnl '/' ("address" | "ADDRESS") Spnl '>'
 
HtmlBlockOpenBlockquote = '<' Spnl ("blockquote" | "BLOCKQUOTE") Spnl HtmlAttribute* '>'
HtmlBlockCloseBlockquote = '<' Spnl '/' ("blockquote" | "BLOCKQUOTE") Spnl '>'
 
HtmlBlockOpenCenter = '<' Spnl ("center" | "CENTER") Spnl HtmlAttribute* '>'
HtmlBlockCloseCenter = '<' Spnl '/' ("center" | "CENTER") Spnl '>'
 
HtmlBlockOpenDir = '<' Spnl ("dir" | "DIR") Spnl HtmlAttribute* '>'
HtmlBlockCloseDir = '<' Spnl '/' ("dir" | "DIR") Spnl '>'
 
HtmlBlockOpenDiv = '<' Spnl ("div" | "DIV") Spnl HtmlAttribute* '>'
HtmlBlockCloseDiv = '<' Spnl '/' ("div" | "DIV") Spnl '>'
 
HtmlBlockOpenDl = '<' Spnl ("dl" | "DL") Spnl HtmlAttribute* '>'
HtmlBlockCloseDl = '<' Spnl '/' ("dl" | "DL") Spnl '>'
 
HtmlBlockOpenFieldset = '<' Spnl ("fieldset" | "FIELDSET") Spnl HtmlAttribute* '>'
HtmlBlockCloseFieldset = '<' Spnl '/' ("fieldset" | "FIELDSET") Spnl '>'
 
HtmlBlockOpenForm = '<' Spnl ("form" | "FORM") Spnl HtmlAttribute* '>'
HtmlBlockCloseForm = '<' Spnl '/' ("form" | "FORM") Spnl '>'
 
HtmlBlockOpenH1 = '<' Spnl ("h1" | "H1") Spnl HtmlAttribute* '>'
HtmlBlockCloseH1 = '<' Spnl '/' ("h1" | "H1") Spnl '>'
 
HtmlBlockOpenH2 = '<' Spnl ("h2" | "H2") Spnl HtmlAttribute* '>'
HtmlBlockCloseH2 = '<' Spnl '/' ("h2" | "H2") Spnl '>'
 
HtmlBlockOpenH3 = '<' Spnl ("h3" | "H3") Spnl HtmlAttribute* '>'
HtmlBlockCloseH3 = '<' Spnl '/' ("h3" | "H3") Spnl '>'
 
HtmlBlockOpenH4 = '<' Spnl ("h4" | "H4") Spnl HtmlAttribute* '>'
HtmlBlockCloseH4 = '<' Spnl '/' ("h4" | "H4") Spnl '>'
 
HtmlBlockOpenH5 = '<' Spnl ("h5" | "H5") Spnl HtmlAttribute* '>'
HtmlBlockCloseH5 = '<' Spnl '/' ("h5" | "H5") Spnl '>'
 
HtmlBlockOpenH6 = '<' Spnl ("h6" | "H6") Spnl HtmlAttribute* '>'
HtmlBlockCloseH6 = '<' Spnl '/' ("h6" | "H6") Spnl '>'
 
HtmlBlockOpenHr = '<' Spnl ("hr" | "HR") Spnl HtmlAttribute* '>'
HtmlBlockCloseHr = '<' Spnl '/' ("hr" | "HR") Spnl '>'
 
HtmlBlockOpenIsindex = '<' Spnl ("isindex" | "ISINDEX") Spnl HtmlAttribute* '>'
HtmlBlockCloseIsindex = '<' Spnl '/' ("isindex" | "ISINDEX") Spnl '>'
 
HtmlBlockOpenMenu = '<' Spnl ("menu" | "MENU") Spnl HtmlAttribute* '>'
HtmlBlockCloseMenu = '<' Spnl '/' ("menu" | "MENU") Spnl '>'
 
HtmlBlockOpenNoframes = '<' Spnl ("noframes" | "NOFRAMES") Spnl HtmlAttribute* '>'
HtmlBlockCloseNoframes = '<' Spnl '/' ("noframes" | "NOFRAMES") Spnl '>'
 
HtmlBlockOpenNoscript = '<' Spnl ("noscript" | "NOSCRIPT") Spnl HtmlAttribute* '>'
HtmlBlockCloseNoscript = '<' Spnl '/' ("noscript" | "NOSCRIPT") Spnl '>'
 
HtmlBlockOpenOl = '<' Spnl ("ol" | "OL") Spnl HtmlAttribute* '>'
HtmlBlockCloseOl = '<' Spnl '/' ("ol" | "OL") Spnl '>'
 
HtmlBlockOpenP = '<' Spnl ("p" | "P") Spnl HtmlAttribute* '>'
HtmlBlockCloseP = '<' Spnl '/' ("p" | "P") Spnl '>'
 
HtmlBlockOpenPre = '<' Spnl ("pre" | "PRE") Spnl HtmlAttribute* '>'
HtmlBlockClosePre = '<' Spnl '/' ("pre" | "PRE") Spnl '>'
 
HtmlBlockOpenTable = '<' Spnl ("table" | "TABLE") Spnl HtmlAttribute* '>'
HtmlBlockCloseTable = '<' Spnl '/' ("table" | "TABLE") Spnl '>'
 
HtmlBlockOpenUl = '<' Spnl ("ul" | "UL") Spnl HtmlAttribute* '>'
HtmlBlockCloseUl = '<' Spnl '/' ("ul" | "UL") Spnl '>'
 
HtmlBlockOpenDd = '<' Spnl ("dd" | "DD") Spnl HtmlAttribute* '>'
HtmlBlockCloseDd = '<' Spnl '/' ("dd" | "DD") Spnl '>'
 
HtmlBlockOpenDt = '<' Spnl ("dt" | "DT") Spnl HtmlAttribute* '>'
HtmlBlockCloseDt = '<' Spnl '/' ("dt" | "DT") Spnl '>'
 
HtmlBlockOpenFrameset = '<' Spnl ("frameset" | "FRAMESET") Spnl HtmlAttribute* '>'
HtmlBlockCloseFrameset = '<' Spnl '/' ("frameset" | "FRAMESET") Spnl '>'
 
HtmlBlockOpenLi = '<' Spnl ("li" | "LI") Spnl HtmlAttribute* '>'
HtmlBlockCloseLi = '<' Spnl '/' ("li" | "LI") Spnl '>'
 
HtmlBlockOpenTbody = '<' Spnl ("tbody" | "TBODY") Spnl HtmlAttribute* '>'
HtmlBlockCloseTbody = '<' Spnl '/' ("tbody" | "TBODY") Spnl '>'
 
HtmlBlockOpenTd = '<' Spnl ("td" | "TD") Spnl HtmlAttribute* '>'
HtmlBlockCloseTd = '<' Spnl '/' ("td" | "TD") Spnl '>'
 
HtmlBlockOpenTfoot = '<' Spnl ("tfoot" | "TFOOT") Spnl HtmlAttribute* '>'
HtmlBlockCloseTfoot = '<' Spnl '/' ("tfoot" | "TFOOT") Spnl '>'
 
HtmlBlockOpenTh = '<' Spnl ("th" | "TH") Spnl HtmlAttribute* '>'
HtmlBlockCloseTh = '<' Spnl '/' ("th" | "TH") Spnl '>'
 
HtmlBlockOpenThead = '<' Spnl ("thead" | "THEAD") Spnl HtmlAttribute* '>'
HtmlBlockCloseThead = '<' Spnl '/' ("thead" | "THEAD") Spnl '>'
 
HtmlBlockOpenTr = '<' Spnl ("tr" | "TR") Spnl HtmlAttribute* '>'
HtmlBlockCloseTr = '<' Spnl '/' ("tr" | "TR") Spnl '>'
 
HtmlBlockOpenScript = '<' Spnl ("script" | "SCRIPT") Spnl HtmlAttribute* '>'
HtmlBlockCloseScript = '<' Spnl '/' ("script" | "SCRIPT") Spnl '>'
 
HtmlBlockInTags = HtmlBlockOpenAddress (HtmlBlockInTags | !HtmlBlockCloseAddress .)* HtmlBlockCloseAddress
                | HtmlBlockOpenBlockquote (HtmlBlockInTags | !HtmlBlockCloseBlockquote .)* HtmlBlockCloseBlockquote
                | HtmlBlockOpenCenter (HtmlBlockInTags | !HtmlBlockCloseCenter .)* HtmlBlockCloseCenter
                | HtmlBlockOpenDir (HtmlBlockInTags | !HtmlBlockCloseDir .)* HtmlBlockCloseDir
                | HtmlBlockOpenDiv (HtmlBlockInTags | !HtmlBlockCloseDiv .)* HtmlBlockCloseDiv
                | HtmlBlockOpenDl (HtmlBlockInTags | !HtmlBlockCloseDl .)* HtmlBlockCloseDl
                | HtmlBlockOpenFieldset (HtmlBlockInTags | !HtmlBlockCloseFieldset .)* HtmlBlockCloseFieldset
                | HtmlBlockOpenForm (HtmlBlockInTags | !HtmlBlockCloseForm .)* HtmlBlockCloseForm
                | HtmlBlockOpenH1 (HtmlBlockInTags | !HtmlBlockCloseH1 .)* HtmlBlockCloseH1
                | HtmlBlockOpenH2 (HtmlBlockInTags | !HtmlBlockCloseH2 .)* HtmlBlockCloseH2
                | HtmlBlockOpenH3 (HtmlBlockInTags | !HtmlBlockCloseH3 .)* HtmlBlockCloseH3
                | HtmlBlockOpenH4 (HtmlBlockInTags | !HtmlBlockCloseH4 .)* HtmlBlockCloseH4
                | HtmlBlockOpenH5 (HtmlBlockInTags | !HtmlBlockCloseH5 .)* HtmlBlockCloseH5
                | HtmlBlockOpenH6 (HtmlBlockInTags | !HtmlBlockCloseH6 .)* HtmlBlockCloseH6
                | HtmlBlockOpenHr (HtmlBlockInTags | !HtmlBlockCloseHr .)* HtmlBlockCloseHr
                | HtmlBlockOpenIsindex (HtmlBlockInTags | !HtmlBlockCloseIsindex .)* HtmlBlockCloseIsindex
                | HtmlBlockOpenMenu (HtmlBlockInTags | !HtmlBlockCloseMenu .)* HtmlBlockCloseMenu
                | HtmlBlockOpenNoframes (HtmlBlockInTags | !HtmlBlockCloseNoframes .)* HtmlBlockCloseNoframes
                | HtmlBlockOpenNoscript (HtmlBlockInTags | !HtmlBlockCloseNoscript .)* HtmlBlockCloseNoscript | HtmlBlockOpenOl (HtmlBlockInTags | !HtmlBlockCloseOl .)* HtmlBlockCloseOl
                | HtmlBlockOpenP (HtmlBlockInTags | !HtmlBlockCloseP .)* HtmlBlockCloseP
                | HtmlBlockOpenPre (HtmlBlockInTags | !HtmlBlockClosePre .)* HtmlBlockClosePre
                | HtmlBlockOpenTable (HtmlBlockInTags | !HtmlBlockCloseTable .)* HtmlBlockCloseTable
                | HtmlBlockOpenUl (HtmlBlockInTags | !HtmlBlockCloseUl .)* HtmlBlockCloseUl
                | HtmlBlockOpenDd (HtmlBlockInTags | !HtmlBlockCloseDd .)* HtmlBlockCloseDd
                | HtmlBlockOpenDt (HtmlBlockInTags | !HtmlBlockCloseDt .)* HtmlBlockCloseDt
                | HtmlBlockOpenFrameset (HtmlBlockInTags | !HtmlBlockCloseFrameset .)* HtmlBlockCloseFrameset
                | HtmlBlockOpenLi (HtmlBlockInTags | !HtmlBlockCloseLi .)* HtmlBlockCloseLi
                | HtmlBlockOpenTbody (HtmlBlockInTags | !HtmlBlockCloseTbody .)* HtmlBlockCloseTbody
                | HtmlBlockOpenTd (HtmlBlockInTags | !HtmlBlockCloseTd .)* HtmlBlockCloseTd
                | HtmlBlockOpenTfoot (HtmlBlockInTags | !HtmlBlockCloseTfoot .)* HtmlBlockCloseTfoot
                | HtmlBlockOpenTh (HtmlBlockInTags | !HtmlBlockCloseTh .)* HtmlBlockCloseTh
                | HtmlBlockOpenThead (HtmlBlockInTags | !HtmlBlockCloseThead .)* HtmlBlockCloseThead
                | HtmlBlockOpenTr (HtmlBlockInTags | !HtmlBlockCloseTr .)* HtmlBlockCloseTr
                | HtmlBlockOpenScript (HtmlBlockInTags | !HtmlBlockCloseScript .)* HtmlBlockCloseScript
 
HtmlBlock = < ( HtmlBlockInTags | HtmlComment | HtmlBlockSelfClosing ) >
            BlankLine+
            { $$ = mk_str(yytext); $$.key = HTMLBLOCK; }
 
HtmlBlockSelfClosing = '<' Spnl HtmlBlockType Spnl HtmlAttribute* '/' Spnl '>'
 
HtmlBlockType = "address" | "blockquote" | "center" | "dir" | "div" | "dl" | "fieldset" | "form" | "h1" | "h2" | "h3" |
                "h4" | "h5" | "h6" | "hr" | "isindex" | "menu" | "noframes" | "noscript" | "ol" | "p" | "pre" | "table" |
                "ul" | "dd" | "dt" | "frameset" | "li" | "tbody" | "td" | "tfoot" | "th" | "thead" | "tr" | "script" |
                "ADDRESS" | "BLOCKQUOTE" | "CENTER" | "DIR" | "DIV" | "DL" | "FIELDSET" | "FORM" | "H1" | "H2" | "H3" |
                "H4" | "H5" | "H6" | "HR" | "ISINDEX" | "MENU" | "NOFRAMES" | "NOSCRIPT" | "OL" | "P" | "PRE" | "TABLE" |
                "UL" | "DD" | "DT" | "FRAMESET" | "LI" | "TBODY" | "TD" | "TFOOT" | "TH" | "THEAD" | "TR" | "SCRIPT"
 
Inlines = a:StartList ( !Endline b:Inline { pushelt(b, &a); }
                        | c:Endline &Inline { pushelt(c, &a); } )+ Endline?
            { $$ = mk_list(LIST, a); }
 
Inline = Str
        | LineBreak
        | Endline
        | Space
        | Strong
        | Emph
        | Image
        | Link
        | Code
        | RawHtml
        | Entity
        | EscapedChar
        | Smart
        | Symbol
 
Space = Spacechar+
        { $$.key = SPACE; $$.contents.str = " "; }
 
Str = < NormalChar+ >
        { $$ = mk_str(yytext); }
 
EscapedChar = '\\' !Newline < . >
                { $$ = mk_str(yytext); }
 
Entity = ( HexEntity | DecEntity | CharEntity )
            { $$ = mk_str(yytext); $$.key = HTML; }
 
Endline = TerminalEndline | NormalEndline
 
NormalEndline = Sp Newline !BlankLine
                  { $$.key = SPACE; $$.contents.str = "\n"; }
 
TerminalEndline = Sp Newline Eof
                  { $$.key = SPACE; $$.contents.str = ""; }
 
LineBreak = " " Endline
            { $$.key = LINEBREAK; }
 
Symbol = < SpecialChar >
            { $$ = mk_str(yytext); }
 
Emph = EmphStar | EmphUl
 
EmphStar = OneStar !Spacechar !Newline
            a:StartList
            ( b:EmphInlineStar { pushelt(b, &a); } )+
            OneStar
            { $$ = mk_list(EMPH, a); }
 
EmphInlineStar = StrongStar
                | !(Spnl OneStar) Inline
 
EmphUl = OneUl !Spacechar !Newline
            a:StartList
            ( b:EmphInlineUl { pushelt(b, &a); } )+
            OneUl !Alphanumeric
            { $$ = mk_list(EMPH, a); }
 
EmphInlineUl = StrongUl
                | !(Spnl OneUl) Inline
 
Strong = StrongStar | StrongUl
 
StrongStar = TwoStar !Spacechar !Newline
                a:StartList
                ( b:StrongInlineStar { pushelt(b, &a); } )+
                TwoStar
                { $$ = mk_list(STRONG, a); }
 
StrongInlineStar = !(Spnl TwoStar) Inline
 
StrongUl = TwoUl !Spacechar !Newline
            a:StartList
            ( b:StrongInlineUl { pushelt(b, &a); } )+
            TwoUl
            { $$ = mk_list(STRONG, a); }
 
StrongInlineUl = !(Spnl TwoUl) Inline
 
Image = '!' ( ExplicitLink | ReferenceLink )
        { $$.key = IMAGE; }
 
Link = ExplicitLink | ReferenceLink | AutoLink
 
ReferenceLink = ReferenceLinkDouble | ReferenceLinkSingle
 
ReferenceLinkDouble = a:Label < Spnl > b:Label
                       { link match;
                           if (find_reference(&match, b.children))
                               $$ = mk_link(a.children, match.url, match.title);
                           else {
                               /* $$.key == LIST; (not needed because $$.key set by Label match */
                               $$.children = cons(mk_str("["), cons(a, cons(mk_str("]"), cons(mk_str(yytext),
                                           cons(mk_str("["), cons(b, cons(mk_str("]"), NULL)))))));
                           }
                       }
 
ReferenceLinkSingle = a:Label < (Spnl "[]")? >
                       { link match;
                           if (find_reference(&match, a.children)) {
                               $$ = mk_link(a.children, match.url, match.title);
                           }
                           else {
                               $$.key = LIST;
                               $$.children = cons(mk_str("["), cons(a, cons(mk_str("]"),cons(mk_str(yytext),NULL))));
                           }
                       }
 
ExplicitLink = l:Label Spnl '(' Sp s:Source Spnl t:Title Sp ')'
                { $$ = mk_link(l.children, s.contents.str, t.contents.str); }
 
Source = ( '<' < SourceContents > '>' | < SourceContents > )
          { $$ = mk_str(yytext); }
 
SourceContents = ( ( !'(' !')' !'>' Nonspacechar )+
                 | '(' SourceContents ')'
                 )*
 
Title = ( TitleSingle | TitleDouble | < "" > )
        { $$ = mk_str(yytext); }
 
TitleSingle = '\'' < ( !( '\'' Sp ( ')' | Newline ) ) !Newline . )* > '\''
 
TitleDouble = '"' < ( !( '"' Sp ( ')' | Newline ) ) !Newline . )* > '"'
 
AutoLink = AutoLinkUrl | AutoLinkEmail
 
AutoLinkUrl = '<' < [A-Za-z]+ "://" ( !Newline !'>' . )+ > '>'
                { $$ = mk_link(cons(mk_str(yytext), NULL), yytext, ""); }
 
AutoLinkEmail = '<' < [-A-Za-z0-9+_]+ '@' ( !Newline !'>' . )+ > '>'
                { char *mailto = malloc(strlen(yytext) + 8);
                    sprintf(mailto, "mailto:%s", yytext);
                    $$ = mk_link(cons(mk_str(yytext), NULL), mailto, "");
                }
 
Reference = NonindentSpace l:Label ':' Spnl s:RefSrc Spnl t:RefTitle BlankLine*
            { $$ = mk_link(l.children, s.contents.str, t.contents.str); $$.key = REFERENCE; }
 
Label = '['
        a:StartList
        ( b:LabelInline { pushelt(b, &a); } )+
        ']'
        { $$ = mk_list(LIST, a); }
 
LabelInline = !']' Inline
 
RefSrc = < Nonspacechar+ > { $$ = mk_str(yytext); $$.key = HTML; }
 
RefTitle = ( RefTitleSingle | RefTitleDouble | RefTitleParens | EmptyTitle )
            { $$ = mk_str(yytext); }
 
EmptyTitle = < "" >
 
RefTitleSingle = '\'' < ( !( '\'' Sp Newline | Newline ) . )* > '\''
 
RefTitleDouble = '"' < ( !('"' Sp Newline | Newline) . )* > '"'
 
RefTitleParens = '(' < ( !(')' Sp Newline | Newline) . )* > ')'
 
References = a:StartList
             ( b:Reference { pushelt(b, &a); } | SkipBlock )*
             { references = a.children; }
 
Ticks1 = "`"
Ticks2 = "``"
Ticks3 = "```"
Ticks4 = "````"
Ticks5 = "`````"
 
Code = ( Ticks1 Sp < ( ( !'`' Nonspacechar )+ | !Ticks1 '`'+ | !( Sp Ticks1 ) Sp )+ > Sp Ticks1
       | Ticks2 Sp < ( ( !'`' Nonspacechar )+ | !Ticks2 '`'+ | !( Sp Ticks2 ) Sp )+ > Sp Ticks2
       | Ticks3 Sp < ( ( !'`' Nonspacechar )+ | !Ticks3 '`'+ | !( Sp Ticks3 ) Sp )+ > Sp Ticks3
       | Ticks4 Sp < ( ( !'`' Nonspacechar )+ | !Ticks4 '`'+ | !( Sp Ticks4 ) Sp )+ > Sp Ticks4
       | Ticks5 Sp < ( ( !'`' Nonspacechar )+ | !Ticks5 '`'+ | !( Sp Ticks5 ) Sp )+ > Sp Ticks5
       )
       { $$ = mk_str(yytext); $$.key = CODE; }
 
RawHtml = < (HtmlComment | HtmlTag) >
            { $$ = mk_str(yytext); $$.key = HTML; }
 
BlankLine = Sp Newline
                { $$ = mk_str("\n"); }
 
Quoted = '"' (!'"' .)* '"' | '\'' (!'\'' .)* '\''
HtmlAttribute = (Alphanumeric | '-')+ Spnl ('=' Spnl (Quoted | Nonspacechar+))? Spnl
HtmlComment = "<!--" (!"-->" .)* "-->"
HtmlTag = '<' Spnl '/'? Alphanumeric+ Spnl HtmlAttribute* '/'? Spnl '>'
Eof = !.
Spacechar = ' ' | '\t'
Nonspacechar = !Spacechar !Newline .
Newline = '\n' | '\r' '\n'?
Sp = Spacechar*
Spnl = Sp (Newline Sp)?
SpecialChar = '*' | '_' | '`' | '&' | '[' | ']' | '<' | '!' | '\\' | ExtendedSpecialChar
NormalChar = !( SpecialChar | Spacechar | Newline ) .
Alphanumeric = [A-Za-z0-9]
 
HexEntity = < '&' '#' [Xx] [0-9a-fA-F]+ ';' >
DecEntity = < '&' '#' [0-9]+ > ';' >
CharEntity = < '&' [A-Za-z0-9]+ ';' >
 
OneStar = '*' !OneStar
OneUl = '_' !OneUl
TwoStar = "**" !TwoStar
TwoUl = "__" !TwoUl
 
NonindentSpace = " " | " " | " " | ""
Indent = "\t" | " "
IndentedLine = Indent Line
OptionallyIndentedLine = Indent? Line
 
# StartList starts a list data structure that can be added to with pushelt:
StartList = &.
            { $$.key = LIST; $$.children = NULL; }
 
Line = ( < (!'\r' !'\n' .)* Newline > | < .+ > Eof )
        { $$ = mk_str(yytext); }
 
SkipBlock = ( !BlankLine Line )+ BlankLine*
          | BlankLine+
 
# Syntax extensions
 
ExtendedSpecialChar = (&{ (syntax_extensions & EXT_SMART) } '.')
 
Smart = &{ (syntax_extensions & EXT_SMART) } Ellipses
 
Ellipses = ("..." | ". . .") { $$.key = ELLIPSIS; }
 
%%
 
element markdown(char *string, int extensions) {
 
    char *oldcharbuf;
    
    syntax_extensions = extensions;
   
    oldcharbuf = charbuf;
    charbuf = string;
    yyparsefrom(yy_References); /* first pass, just to collect references */
 
    charbuf = string; /* go back to beginning, to convert */
    yyparsefrom(yy_Doc);
 
    charbuf = oldcharbuf; /* restore charbuf to original value */
    return parse_result;
 
}