Coverage Report

Created: 2026-05-16 09:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/workdir/UnpackedTarball/md4c/src/md4c.c
Line
Count
Source
1
/*
2
 * MD4C: Markdown parser for C
3
 * (http://github.com/mity/md4c)
4
 *
5
 * Copyright (c) 2016-2024 Martin Mitáš
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a
8
 * copy of this software and associated documentation files (the "Software"),
9
 * to deal in the Software without restriction, including without limitation
10
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11
 * and/or sell copies of the Software, and to permit persons to whom the
12
 * Software is furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23
 * IN THE SOFTWARE.
24
 */
25
26
#include "md4c.h"
27
28
#include <limits.h>
29
#include <stdint.h>
30
#include <stdio.h>
31
#include <stdlib.h>
32
#include <string.h>
33
34
35
/*****************************
36
 ***  Miscellaneous Stuff  ***
37
 *****************************/
38
39
#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199409L
40
    /* C89/90 or old compilers in general may not understand "inline". */
41
    #if defined __GNUC__
42
        #define inline __inline__
43
    #elif defined _MSC_VER
44
        #define inline __inline
45
    #else
46
        #define inline
47
    #endif
48
#endif
49
50
/* Make the UTF-8 support the default. */
51
#if !defined MD4C_USE_ASCII && !defined MD4C_USE_UTF8 && !defined MD4C_USE_UTF16
52
    #define MD4C_USE_UTF8
53
#endif
54
55
/* Magic for making wide literals with MD4C_USE_UTF16. */
56
#ifdef _T
57
    #undef _T
58
#endif
59
#if defined MD4C_USE_UTF16
60
    #define _T(x)           L##x
61
#else
62
0
    #define _T(x)           x
63
#endif
64
65
/* Misc. macros. */
66
0
#define SIZEOF_ARRAY(a)     (sizeof(a) / sizeof(a[0]))
67
68
#define STRINGIZE_(x)       #x
69
#define STRINGIZE(x)        STRINGIZE_(x)
70
71
0
#define MAX(a,b)            ((a) > (b) ? (a) : (b))
72
0
#define MIN(a,b)            ((a) < (b) ? (a) : (b))
73
74
#ifndef TRUE
75
0
    #define TRUE            1
76
0
    #define FALSE           0
77
#endif
78
79
#define MD_LOG(msg)                                                     \
80
0
    do {                                                                \
81
0
        if(ctx->parser.debug_log != NULL)                               \
82
0
            ctx->parser.debug_log((msg), ctx->userdata);                \
83
0
    } while(0)
84
85
#ifdef DEBUG
86
    #define MD_ASSERT(cond)                                             \
87
            do {                                                        \
88
                if(!(cond)) {                                           \
89
                    MD_LOG(__FILE__ ":" STRINGIZE(__LINE__) ": "        \
90
                           "Assertion '" STRINGIZE(cond) "' failed.");  \
91
                    exit(1);                                            \
92
                }                                                       \
93
            } while(0)
94
95
    #define MD_UNREACHABLE()        MD_ASSERT(1 == 0)
96
#else
97
    #ifdef __GNUC__
98
0
        #define MD_ASSERT(cond)     do { if(!(cond)) __builtin_unreachable(); } while(0)
99
0
        #define MD_UNREACHABLE()    do { __builtin_unreachable(); } while(0)
100
    #elif defined _MSC_VER  &&  _MSC_VER > 120
101
        #define MD_ASSERT(cond)     do { __assume(cond); } while(0)
102
        #define MD_UNREACHABLE()    do { __assume(0); } while(0)
103
    #else
104
        #define MD_ASSERT(cond)     do {} while(0)
105
        #define MD_UNREACHABLE()    do {} while(0)
106
    #endif
107
#endif
108
109
/* For falling through case labels in switch statements. */
110
#if defined __clang__ && __clang_major__ >= 12
111
0
    #define MD_FALLTHROUGH()        __attribute__((fallthrough))
112
#elif defined __GNUC__ && __GNUC__ >= 7
113
    #define MD_FALLTHROUGH()        __attribute__((fallthrough))
114
#else
115
    #define MD_FALLTHROUGH()        ((void)0)
116
#endif
117
118
/* Suppress "unused parameter" warnings. */
119
0
#define MD_UNUSED(x)                ((void)x)
120
121
122
/******************************
123
 ***  Some internal limits  ***
124
 ******************************/
125
126
/* We limit code span marks to lower than 32 backticks. This solves the
127
 * pathologic case of too many openers, each of different length: Their
128
 * resolving would be then O(n^2). */
129
0
#define CODESPAN_MARK_MAXLEN    32
130
131
/* We limit column count of tables to prevent quadratic explosion of output
132
 * from pathological input of a table thousands of columns and thousands
133
 * of rows where rows are requested with as little as single character
134
 * per-line, relying on us to "helpfully" fill all the missing "<td></td>". */
135
0
#define TABLE_MAXCOLCOUNT       128
136
137
138
/************************
139
 ***  Internal Types  ***
140
 ************************/
141
142
/* These are omnipresent so lets save some typing. */
143
0
#define CHAR    MD_CHAR
144
0
#define SZ      MD_SIZE
145
0
#define OFF     MD_OFFSET
146
147
typedef struct MD_MARK_tag MD_MARK;
148
typedef struct MD_BLOCK_tag MD_BLOCK;
149
typedef struct MD_CONTAINER_tag MD_CONTAINER;
150
typedef struct MD_REF_DEF_tag MD_REF_DEF;
151
152
153
/* During analyzes of inline marks, we need to manage stacks of unresolved
154
 * openers of the given type.
155
 * The stack connects the marks via MD_MARK::next;
156
 */
157
typedef struct MD_MARKSTACK_tag MD_MARKSTACK;
158
struct MD_MARKSTACK_tag {
159
    int top;        /* -1 if empty. */
160
};
161
162
/* Context propagated through all the parsing. */
163
typedef struct MD_CTX_tag MD_CTX;
164
struct MD_CTX_tag {
165
    /* Immutable stuff (parameters of md_parse()). */
166
    const CHAR* text;
167
    SZ size;
168
    MD_PARSER parser;
169
    void* userdata;
170
171
    /* When this is true, it allows some optimizations. */
172
    int doc_ends_with_newline;
173
174
    /* Helper temporary growing buffer. */
175
    CHAR* buffer;
176
    unsigned alloc_buffer;
177
178
    /* Reference definitions. */
179
    MD_REF_DEF* ref_defs;
180
    int n_ref_defs;
181
    int alloc_ref_defs;
182
    void** ref_def_hashtable;
183
    int ref_def_hashtable_size;
184
    SZ max_ref_def_output;
185
186
    /* Stack of inline/span markers.
187
     * This is only used for parsing a single block contents but by storing it
188
     * here we may reuse the stack for subsequent blocks; i.e. we have fewer
189
     * (re)allocations. */
190
    MD_MARK* marks;
191
    int n_marks;
192
    int alloc_marks;
193
194
#if defined MD4C_USE_UTF16
195
    char mark_char_map[128];
196
#else
197
    char mark_char_map[256];
198
#endif
199
200
    /* For resolving of inline spans. */
201
    MD_MARKSTACK opener_stacks[16];
202
0
#define ASTERISK_OPENERS_oo_mod3_0      (ctx->opener_stacks[0])     /* Opener-only */
203
#define ASTERISK_OPENERS_oo_mod3_1      (ctx->opener_stacks[1])
204
#define ASTERISK_OPENERS_oo_mod3_2      (ctx->opener_stacks[2])
205
#define ASTERISK_OPENERS_oc_mod3_0      (ctx->opener_stacks[3])     /* Both opener and closer candidate */
206
#define ASTERISK_OPENERS_oc_mod3_1      (ctx->opener_stacks[4])
207
#define ASTERISK_OPENERS_oc_mod3_2      (ctx->opener_stacks[5])
208
0
#define UNDERSCORE_OPENERS_oo_mod3_0    (ctx->opener_stacks[6])     /* Opener-only */
209
#define UNDERSCORE_OPENERS_oo_mod3_1    (ctx->opener_stacks[7])
210
#define UNDERSCORE_OPENERS_oo_mod3_2    (ctx->opener_stacks[8])
211
#define UNDERSCORE_OPENERS_oc_mod3_0    (ctx->opener_stacks[9])     /* Both opener and closer candidate */
212
#define UNDERSCORE_OPENERS_oc_mod3_1    (ctx->opener_stacks[10])
213
#define UNDERSCORE_OPENERS_oc_mod3_2    (ctx->opener_stacks[11])
214
0
#define TILDE_OPENERS_1                 (ctx->opener_stacks[12])
215
0
#define TILDE_OPENERS_2                 (ctx->opener_stacks[13])
216
0
#define BRACKET_OPENERS                 (ctx->opener_stacks[14])
217
0
#define DOLLAR_OPENERS                  (ctx->opener_stacks[15])
218
219
    /* Stack of dummies which need to call free() for pointers stored in them.
220
     * These are constructed during inline parsing and freed after all the block
221
     * is processed (i.e. all callbacks referring those strings are called). */
222
    MD_MARKSTACK ptr_stack;
223
224
    /* For resolving table rows. */
225
    int n_table_cell_boundaries;
226
    int table_cell_boundaries_head;
227
    int table_cell_boundaries_tail;
228
229
    /* For resolving links. */
230
    int unresolved_link_head;
231
    int unresolved_link_tail;
232
233
    /* For resolving raw HTML. */
234
    OFF html_comment_horizon;
235
    OFF html_proc_instr_horizon;
236
    OFF html_decl_horizon;
237
    OFF html_cdata_horizon;
238
239
    /* For block analysis.
240
     * Notes:
241
     *   -- It holds MD_BLOCK as well as MD_LINE structures. After each
242
     *      MD_BLOCK, its (multiple) MD_LINE(s) follow.
243
     *   -- For MD_BLOCK_HTML and MD_BLOCK_CODE, MD_VERBATIMLINE(s) are used
244
     *      instead of MD_LINE(s).
245
     */
246
    void* block_bytes;
247
    MD_BLOCK* current_block;
248
    int n_block_bytes;
249
    int alloc_block_bytes;
250
251
    /* For container block analysis. */
252
    MD_CONTAINER* containers;
253
    int n_containers;
254
    int alloc_containers;
255
256
    /* Minimal indentation to call the block "indented code block". */
257
    unsigned code_indent_offset;
258
259
    /* Contextual info for line analysis. */
260
    SZ code_fence_length;   /* For checking closing fence length. */
261
    int html_block_type;    /* For checking closing raw HTML condition. */
262
    int last_line_has_list_loosening_effect;
263
    int last_list_item_starts_with_two_blank_lines;
264
};
265
266
enum MD_LINETYPE_tag {
267
    MD_LINE_BLANK,
268
    MD_LINE_HR,
269
    MD_LINE_ATXHEADER,
270
    MD_LINE_SETEXTHEADER,
271
    MD_LINE_SETEXTUNDERLINE,
272
    MD_LINE_INDENTEDCODE,
273
    MD_LINE_FENCEDCODE,
274
    MD_LINE_HTML,
275
    MD_LINE_TEXT,
276
    MD_LINE_TABLE,
277
    MD_LINE_TABLEUNDERLINE
278
};
279
typedef enum MD_LINETYPE_tag MD_LINETYPE;
280
281
typedef struct MD_LINE_ANALYSIS_tag MD_LINE_ANALYSIS;
282
struct MD_LINE_ANALYSIS_tag {
283
    MD_LINETYPE type;
284
    unsigned data;
285
    int enforce_new_block;
286
    OFF beg;
287
    OFF end;
288
    unsigned indent;        /* Indentation level. */
289
};
290
291
typedef struct MD_LINE_tag MD_LINE;
292
struct MD_LINE_tag {
293
    OFF beg;
294
    OFF end;
295
};
296
297
typedef struct MD_VERBATIMLINE_tag MD_VERBATIMLINE;
298
struct MD_VERBATIMLINE_tag {
299
    OFF beg;
300
    OFF end;
301
    OFF indent;
302
};
303
304
305
/*****************
306
 ***  Helpers  ***
307
 *****************/
308
309
/* Character accessors. */
310
0
#define CH(off)                 (ctx->text[(off)])
311
0
#define STR(off)                (ctx->text + (off))
312
313
/* Character classification.
314
 * Note we assume ASCII compatibility of code points < 128 here. */
315
0
#define ISIN_(ch, ch_min, ch_max)       ((ch_min) <= (unsigned)(ch) && (unsigned)(ch) <= (ch_max))
316
0
#define ISANYOF_(ch, palette)           ((ch) != _T('\0')  &&  md_strchr((palette), (ch)) != NULL)
317
0
#define ISANYOF2_(ch, ch1, ch2)         ((ch) == (ch1) || (ch) == (ch2))
318
0
#define ISANYOF3_(ch, ch1, ch2, ch3)    ((ch) == (ch1) || (ch) == (ch2) || (ch) == (ch3))
319
0
#define ISASCII_(ch)                    ((unsigned)(ch) <= 127)
320
0
#define ISBLANK_(ch)                    (ISANYOF2_((ch), _T(' '), _T('\t')))
321
0
#define ISNEWLINE_(ch)                  (ISANYOF2_((ch), _T('\r'), _T('\n')))
322
0
#define ISWHITESPACE_(ch)               (ISBLANK_(ch) || ISANYOF2_((ch), _T('\v'), _T('\f')))
323
0
#define ISCNTRL_(ch)                    ((unsigned)(ch) <= 31 || (unsigned)(ch) == 127)
324
0
#define ISPUNCT_(ch)                    (ISIN_(ch, 33, 47) || ISIN_(ch, 58, 64) || ISIN_(ch, 91, 96) || ISIN_(ch, 123, 126))
325
0
#define ISUPPER_(ch)                    (ISIN_(ch, _T('A'), _T('Z')))
326
0
#define ISLOWER_(ch)                    (ISIN_(ch, _T('a'), _T('z')))
327
0
#define ISALPHA_(ch)                    (ISUPPER_(ch) || ISLOWER_(ch))
328
0
#define ISDIGIT_(ch)                    (ISIN_(ch, _T('0'), _T('9')))
329
0
#define ISXDIGIT_(ch)                   (ISDIGIT_(ch) || ISIN_(ch, _T('A'), _T('F')) || ISIN_(ch, _T('a'), _T('f')))
330
0
#define ISALNUM_(ch)                    (ISALPHA_(ch) || ISDIGIT_(ch))
331
332
0
#define ISANYOF(off, palette)           ISANYOF_(CH(off), (palette))
333
0
#define ISANYOF2(off, ch1, ch2)         ISANYOF2_(CH(off), (ch1), (ch2))
334
0
#define ISANYOF3(off, ch1, ch2, ch3)    ISANYOF3_(CH(off), (ch1), (ch2), (ch3))
335
0
#define ISASCII(off)                    ISASCII_(CH(off))
336
0
#define ISBLANK(off)                    ISBLANK_(CH(off))
337
0
#define ISNEWLINE(off)                  ISNEWLINE_(CH(off))
338
0
#define ISWHITESPACE(off)               ISWHITESPACE_(CH(off))
339
0
#define ISCNTRL(off)                    ISCNTRL_(CH(off))
340
0
#define ISPUNCT(off)                    ISPUNCT_(CH(off))
341
0
#define ISUPPER(off)                    ISUPPER_(CH(off))
342
#define ISLOWER(off)                    ISLOWER_(CH(off))
343
0
#define ISALPHA(off)                    ISALPHA_(CH(off))
344
0
#define ISDIGIT(off)                    ISDIGIT_(CH(off))
345
#define ISXDIGIT(off)                   ISXDIGIT_(CH(off))
346
0
#define ISALNUM(off)                    ISALNUM_(CH(off))
347
348
349
#if defined MD4C_USE_UTF16
350
    #define md_strchr wcschr
351
#else
352
0
    #define md_strchr strchr
353
#endif
354
355
356
/* Case insensitive check of string equality. */
357
static inline int
358
md_ascii_case_eq(const CHAR* s1, const CHAR* s2, SZ n)
359
0
{
360
0
    OFF i;
361
0
    for(i = 0; i < n; i++) {
362
0
        CHAR ch1 = s1[i];
363
0
        CHAR ch2 = s2[i];
364
365
0
        if(ISLOWER_(ch1))
366
0
            ch1 += ('A'-'a');
367
0
        if(ISLOWER_(ch2))
368
0
            ch2 += ('A'-'a');
369
0
        if(ch1 != ch2)
370
0
            return FALSE;
371
0
    }
372
0
    return TRUE;
373
0
}
374
375
static inline int
376
md_ascii_eq(const CHAR* s1, const CHAR* s2, SZ n)
377
0
{
378
0
    return memcmp(s1, s2, n * sizeof(CHAR)) == 0;
379
0
}
380
381
static int
382
md_text_with_null_replacement(MD_CTX* ctx, MD_TEXTTYPE type, const CHAR* str, SZ size)
383
0
{
384
0
    OFF off = 0;
385
0
    int ret = 0;
386
387
0
    while(1) {
388
0
        while(off < size  &&  str[off] != _T('\0'))
389
0
            off++;
390
391
0
        if(off > 0) {
392
0
            ret = ctx->parser.text(type, str, off, ctx->userdata);
393
0
            if(ret != 0)
394
0
                return ret;
395
396
0
            str += off;
397
0
            size -= off;
398
0
            off = 0;
399
0
        }
400
401
0
        if(off >= size)
402
0
            return 0;
403
404
0
        ret = ctx->parser.text(MD_TEXT_NULLCHAR, _T(""), 1, ctx->userdata);
405
0
        if(ret != 0)
406
0
            return ret;
407
0
        off++;
408
0
    }
409
0
}
410
411
412
#define MD_CHECK(func)                                                      \
413
0
    do {                                                                    \
414
0
        ret = (func);                                                       \
415
0
        if(ret != 0)                                                        \
416
0
            goto abort;                                                     \
417
0
    } while(0)
418
419
420
#define MD_TEMP_BUFFER(sz)                                                  \
421
0
    do {                                                                    \
422
0
        if(sz > ctx->alloc_buffer) {                                        \
423
0
            CHAR* new_buffer;                                               \
424
0
            SZ new_size = ((sz) + (sz) / 2 + 128) & ~127;                   \
425
0
                                                                            \
426
0
            new_buffer = realloc(ctx->buffer, new_size);                    \
427
0
            if(new_buffer == NULL) {                                        \
428
0
                MD_LOG("realloc() failed.");                                \
429
0
                ret = -1;                                                   \
430
0
                goto abort;                                                 \
431
0
            }                                                               \
432
0
                                                                            \
433
0
            ctx->buffer = new_buffer;                                       \
434
0
            ctx->alloc_buffer = new_size;                                   \
435
0
        }                                                                   \
436
0
    } while(0)
437
438
439
#define MD_ENTER_BLOCK(type, arg)                                           \
440
0
    do {                                                                    \
441
0
        ret = ctx->parser.enter_block((type), (arg), ctx->userdata);        \
442
0
        if(ret != 0) {                                                      \
443
0
            MD_LOG("Aborted from enter_block() callback.");                 \
444
0
            goto abort;                                                     \
445
0
        }                                                                   \
446
0
    } while(0)
447
448
#define MD_LEAVE_BLOCK(type, arg)                                           \
449
0
    do {                                                                    \
450
0
        ret = ctx->parser.leave_block((type), (arg), ctx->userdata);        \
451
0
        if(ret != 0) {                                                      \
452
0
            MD_LOG("Aborted from leave_block() callback.");                 \
453
0
            goto abort;                                                     \
454
0
        }                                                                   \
455
0
    } while(0)
456
457
#define MD_ENTER_SPAN(type, arg)                                            \
458
0
    do {                                                                    \
459
0
        ret = ctx->parser.enter_span((type), (arg), ctx->userdata);         \
460
0
        if(ret != 0) {                                                      \
461
0
            MD_LOG("Aborted from enter_span() callback.");                  \
462
0
            goto abort;                                                     \
463
0
        }                                                                   \
464
0
    } while(0)
465
466
#define MD_LEAVE_SPAN(type, arg)                                            \
467
0
    do {                                                                    \
468
0
        ret = ctx->parser.leave_span((type), (arg), ctx->userdata);         \
469
0
        if(ret != 0) {                                                      \
470
0
            MD_LOG("Aborted from leave_span() callback.");                  \
471
0
            goto abort;                                                     \
472
0
        }                                                                   \
473
0
    } while(0)
474
475
#define MD_TEXT(type, str, size)                                            \
476
0
    do {                                                                    \
477
0
        if(size > 0) {                                                      \
478
0
            ret = ctx->parser.text((type), (str), (size), ctx->userdata);   \
479
0
            if(ret != 0) {                                                  \
480
0
                MD_LOG("Aborted from text() callback.");                    \
481
0
                goto abort;                                                 \
482
0
            }                                                               \
483
0
        }                                                                   \
484
0
    } while(0)
485
486
#define MD_TEXT_INSECURE(type, str, size)                                   \
487
0
    do {                                                                    \
488
0
        if(size > 0) {                                                      \
489
0
            ret = md_text_with_null_replacement(ctx, type, str, size);      \
490
0
            if(ret != 0) {                                                  \
491
0
                MD_LOG("Aborted from text() callback.");                    \
492
0
                goto abort;                                                 \
493
0
            }                                                               \
494
0
        }                                                                   \
495
0
    } while(0)
496
497
498
/* If the offset falls into a gap between line, we return the following
499
 * line. */
500
static const MD_LINE*
501
md_lookup_line(OFF off, const MD_LINE* lines, MD_SIZE n_lines, MD_SIZE* p_line_index)
502
0
{
503
0
    MD_SIZE lo, hi;
504
0
    MD_SIZE pivot;
505
0
    const MD_LINE* line;
506
507
0
    lo = 0;
508
0
    hi = n_lines - 1;
509
0
    while(lo <= hi) {
510
0
        pivot = (lo + hi) / 2;
511
0
        line = &lines[pivot];
512
513
0
        if(off < line->beg) {
514
0
            if(hi == 0  ||  lines[hi-1].end < off) {
515
0
                if(p_line_index != NULL)
516
0
                    *p_line_index = pivot;
517
0
                return line;
518
0
            }
519
0
            hi = pivot - 1;
520
0
        } else if(off > line->end) {
521
0
            lo = pivot + 1;
522
0
        } else {
523
0
            if(p_line_index != NULL)
524
0
                *p_line_index = pivot;
525
0
            return line;
526
0
        }
527
0
    }
528
529
0
    return NULL;
530
0
}
531
532
533
/*************************
534
 ***  Unicode Support  ***
535
 *************************/
536
537
typedef struct MD_UNICODE_FOLD_INFO_tag MD_UNICODE_FOLD_INFO;
538
struct MD_UNICODE_FOLD_INFO_tag {
539
    unsigned codepoints[3];
540
    unsigned n_codepoints;
541
};
542
543
544
#if defined MD4C_USE_UTF16 || defined MD4C_USE_UTF8
545
    /* Binary search over sorted "map" of codepoints. Consecutive sequences
546
     * of codepoints may be encoded in the map by just using the
547
     * (MIN_CODEPOINT | 0x40000000) and (MAX_CODEPOINT | 0x80000000).
548
     *
549
     * Returns index of the found record in the map (in the case of ranges,
550
     * the minimal value is used); or -1 on failure. */
551
    static int
552
    md_unicode_bsearch__(unsigned codepoint, const unsigned* map, size_t map_size)
553
0
    {
554
0
        int beg, end;
555
0
        int pivot_beg, pivot_end;
556
557
0
        beg = 0;
558
0
        end = (int) map_size-1;
559
0
        while(beg <= end) {
560
            /* Pivot may be a range, not just a single value. */
561
0
            pivot_beg = pivot_end = (beg + end) / 2;
562
0
            if(map[pivot_end] & 0x40000000)
563
0
                pivot_end++;
564
0
            if(map[pivot_beg] & 0x80000000)
565
0
                pivot_beg--;
566
567
0
            if(codepoint < (map[pivot_beg] & 0x00ffffff))
568
0
                end = pivot_beg - 1;
569
0
            else if(codepoint > (map[pivot_end] & 0x00ffffff))
570
0
                beg = pivot_end + 1;
571
0
            else
572
0
                return pivot_beg;
573
0
        }
574
575
0
        return -1;
576
0
    }
577
578
    static int
579
    md_is_unicode_whitespace__(unsigned codepoint)
580
0
    {
581
0
#define R(cp_min, cp_max)   ((cp_min) | 0x40000000), ((cp_max) | 0x80000000)
582
0
#define S(cp)               (cp)
583
        /* Unicode "Zs" category.
584
         * (generated by scripts/build_whitespace_map.py) */
585
0
        static const unsigned WHITESPACE_MAP[] = {
586
0
            S(0x0020), S(0x00a0), S(0x1680), R(0x2000,0x200a), S(0x202f), S(0x205f), S(0x3000)
587
0
        };
588
0
#undef R
589
0
#undef S
590
591
        /* The ASCII ones are the most frequently used ones, also CommonMark
592
         * specification requests few more in this range. */
593
0
        if(codepoint <= 0x7f)
594
0
            return ISWHITESPACE_(codepoint);
595
596
0
        return (md_unicode_bsearch__(codepoint, WHITESPACE_MAP, SIZEOF_ARRAY(WHITESPACE_MAP)) >= 0);
597
0
    }
598
599
    static int
600
    md_is_unicode_punct__(unsigned codepoint)
601
0
    {
602
0
#define R(cp_min, cp_max)   ((cp_min) | 0x40000000), ((cp_max) | 0x80000000)
603
0
#define S(cp)               (cp)
604
        /* Unicode general "P" and "S" categories.
605
         * (generated by scripts/build_punct_map.py) */
606
0
        static const unsigned PUNCT_MAP[] = {
607
0
            R(0x0021,0x002f), R(0x003a,0x0040), R(0x005b,0x0060), R(0x007b,0x007e), R(0x00a1,0x00a9),
608
0
            R(0x00ab,0x00ac), R(0x00ae,0x00b1), S(0x00b4), R(0x00b6,0x00b8), S(0x00bb), S(0x00bf), S(0x00d7),
609
0
            S(0x00f7), R(0x02c2,0x02c5), R(0x02d2,0x02df), R(0x02e5,0x02eb), S(0x02ed), R(0x02ef,0x02ff), S(0x0375),
610
0
            S(0x037e), R(0x0384,0x0385), S(0x0387), S(0x03f6), S(0x0482), R(0x055a,0x055f), R(0x0589,0x058a),
611
0
            R(0x058d,0x058f), S(0x05be), S(0x05c0), S(0x05c3), S(0x05c6), R(0x05f3,0x05f4), R(0x0606,0x060f),
612
0
            S(0x061b), R(0x061d,0x061f), R(0x066a,0x066d), S(0x06d4), S(0x06de), S(0x06e9), R(0x06fd,0x06fe),
613
0
            R(0x0700,0x070d), R(0x07f6,0x07f9), R(0x07fe,0x07ff), R(0x0830,0x083e), S(0x085e), S(0x0888),
614
0
            R(0x0964,0x0965), S(0x0970), R(0x09f2,0x09f3), R(0x09fa,0x09fb), S(0x09fd), S(0x0a76), R(0x0af0,0x0af1),
615
0
            S(0x0b70), R(0x0bf3,0x0bfa), S(0x0c77), S(0x0c7f), S(0x0c84), S(0x0d4f), S(0x0d79), S(0x0df4), S(0x0e3f),
616
0
            S(0x0e4f), R(0x0e5a,0x0e5b), R(0x0f01,0x0f17), R(0x0f1a,0x0f1f), S(0x0f34), S(0x0f36), S(0x0f38),
617
0
            R(0x0f3a,0x0f3d), S(0x0f85), R(0x0fbe,0x0fc5), R(0x0fc7,0x0fcc), R(0x0fce,0x0fda), R(0x104a,0x104f),
618
0
            R(0x109e,0x109f), S(0x10fb), R(0x1360,0x1368), R(0x1390,0x1399), S(0x1400), R(0x166d,0x166e),
619
0
            R(0x169b,0x169c), R(0x16eb,0x16ed), R(0x1735,0x1736), R(0x17d4,0x17d6), R(0x17d8,0x17db),
620
0
            R(0x1800,0x180a), S(0x1940), R(0x1944,0x1945), R(0x19de,0x19ff), R(0x1a1e,0x1a1f), R(0x1aa0,0x1aa6),
621
0
            R(0x1aa8,0x1aad), R(0x1b4e,0x1b4f), R(0x1b5a,0x1b6a), R(0x1b74,0x1b7f), R(0x1bfc,0x1bff),
622
0
            R(0x1c3b,0x1c3f), R(0x1c7e,0x1c7f), R(0x1cc0,0x1cc7), S(0x1cd3), S(0x1fbd), R(0x1fbf,0x1fc1),
623
0
            R(0x1fcd,0x1fcf), R(0x1fdd,0x1fdf), R(0x1fed,0x1fef), R(0x1ffd,0x1ffe), R(0x2010,0x2027),
624
0
            R(0x2030,0x205e), R(0x207a,0x207e), R(0x208a,0x208e), R(0x20a0,0x20c4), R(0x2100,0x2101),
625
0
            R(0x2103,0x2106), R(0x2108,0x2109), S(0x2114), R(0x2116,0x2118), R(0x211e,0x2123), S(0x2125), S(0x2127),
626
0
            S(0x2129), S(0x212e), R(0x213a,0x213b), R(0x2140,0x2144), R(0x214a,0x214d), S(0x214f), R(0x218a,0x218b),
627
0
            R(0x2190,0x2429), R(0x2440,0x244a), R(0x249c,0x24e9), R(0x2500,0x2775), R(0x2794,0x2b73),
628
0
            R(0x2b76,0x2bff), R(0x2ce5,0x2cea), R(0x2cf9,0x2cfc), R(0x2cfe,0x2cff), S(0x2d70), R(0x2e00,0x2e2e),
629
0
            R(0x2e30,0x2e5d), R(0x2e60,0x2e63), R(0x2e80,0x2e99), R(0x2e9b,0x2ef3), R(0x2f00,0x2fd5),
630
0
            R(0x2ff0,0x2fff), R(0x3001,0x3004), R(0x3008,0x3020), S(0x3030), R(0x3036,0x3037), R(0x303d,0x303f),
631
0
            R(0x309b,0x309c), S(0x30a0), S(0x30fb), R(0x3190,0x3191), R(0x3196,0x319f), R(0x31c0,0x31e5), S(0x31ef),
632
0
            R(0x3200,0x321e), R(0x322a,0x3247), S(0x3250), R(0x3260,0x327f), R(0x328a,0x32b0), R(0x32c0,0x33ff),
633
0
            R(0x4dc0,0x4dff), R(0xa490,0xa4c6), R(0xa4fe,0xa4ff), R(0xa60d,0xa60f), S(0xa673), S(0xa67e),
634
0
            R(0xa6f2,0xa6f7), R(0xa700,0xa716), R(0xa720,0xa721), R(0xa789,0xa78a), R(0xa828,0xa82b),
635
0
            R(0xa836,0xa839), R(0xa874,0xa877), R(0xa8ce,0xa8cf), R(0xa8f8,0xa8fa), S(0xa8fc), R(0xa92e,0xa92f),
636
0
            S(0xa95f), R(0xa9c1,0xa9cd), R(0xa9de,0xa9df), R(0xaa5c,0xaa5f), R(0xaa77,0xaa79), R(0xaade,0xaadf),
637
0
            R(0xaaf0,0xaaf1), S(0xab5b), R(0xab6a,0xab6b), S(0xabeb), S(0xfb29), R(0xfbb2,0xfbd2), R(0xfd3e,0xfd4f),
638
0
            R(0xfd90,0xfd91), R(0xfdc8,0xfdcf), R(0xfdfc,0xfdff), R(0xfe10,0xfe19), R(0xfe30,0xfe52),
639
0
            R(0xfe54,0xfe66), R(0xfe68,0xfe6b), R(0xff01,0xff0f), R(0xff1a,0xff20), R(0xff3b,0xff40),
640
0
            R(0xff5b,0xff65), R(0xffe0,0xffe6), R(0xffe8,0xffee), R(0xfffc,0xfffd), R(0x10100,0x10102),
641
0
            R(0x10137,0x1013f), R(0x10179,0x10189), R(0x1018c,0x1018e), R(0x10190,0x1019c), S(0x101a0),
642
0
            R(0x101d0,0x101fc), S(0x1039f), S(0x103d0), S(0x1056f), S(0x10857), R(0x10877,0x10878), S(0x1091f),
643
0
            S(0x1093f), R(0x10a50,0x10a58), S(0x10a7f), S(0x10ac8), R(0x10af0,0x10af6), R(0x10b39,0x10b3f),
644
0
            R(0x10b99,0x10b9c), S(0x10d6e), R(0x10d8e,0x10d8f), S(0x10ead), R(0x10ec9,0x10eca), R(0x10ed0,0x10ed8),
645
0
            R(0x10f55,0x10f59), R(0x10f86,0x10f89), R(0x11047,0x1104d), R(0x110bb,0x110bc), R(0x110be,0x110c1),
646
0
            R(0x11140,0x11143), R(0x11174,0x11175), R(0x111c5,0x111c8), S(0x111cd), S(0x111db), R(0x111dd,0x111df),
647
0
            R(0x11238,0x1123d), S(0x112a9), R(0x113d4,0x113d5), R(0x113d7,0x113d8), R(0x1144b,0x1144f),
648
0
            R(0x1145a,0x1145b), S(0x1145d), S(0x114c6), R(0x115c1,0x115d7), R(0x11641,0x11643), R(0x11660,0x1166c),
649
0
            S(0x116b9), R(0x1173c,0x1173f), S(0x1183b), R(0x11944,0x11946), S(0x119e2), R(0x11a3f,0x11a46),
650
0
            R(0x11a9a,0x11a9c), R(0x11a9e,0x11aa2), R(0x11b00,0x11b09), S(0x11be1), R(0x11c41,0x11c45),
651
0
            R(0x11c70,0x11c71), R(0x11ef7,0x11ef8), R(0x11f43,0x11f4f), R(0x11fd5,0x11ff1), S(0x11fff),
652
0
            R(0x12470,0x12474), R(0x12ff1,0x12ff2), R(0x16a6e,0x16a6f), S(0x16af5), R(0x16b37,0x16b3f),
653
0
            R(0x16b44,0x16b45), R(0x16d6d,0x16d6f), R(0x16e97,0x16e9a), S(0x16fe2), S(0x1bc9c), S(0x1bc9f),
654
0
            R(0x1cc00,0x1ccef), R(0x1ccfa,0x1ccfc), R(0x1cd00,0x1ceb3), R(0x1ceba,0x1ced0), R(0x1ced2,0x1ced4),
655
0
            R(0x1cedd,0x1cefd), R(0x1cf50,0x1cfc3), R(0x1d000,0x1d0f5), R(0x1d100,0x1d126), R(0x1d129,0x1d164),
656
0
            R(0x1d16a,0x1d16c), R(0x1d183,0x1d184), R(0x1d18c,0x1d1a9), R(0x1d1ae,0x1d241), S(0x1d245),
657
0
            R(0x1d253,0x1d25a), R(0x1d25d,0x1d25e), R(0x1d260,0x1d27f), R(0x1d300,0x1d356), S(0x1d6c1), S(0x1d6db),
658
0
            S(0x1d6fb), S(0x1d715), S(0x1d735), S(0x1d74f), S(0x1d76f), S(0x1d789), S(0x1d7a9), S(0x1d7c3),
659
0
            R(0x1d800,0x1d9ff), R(0x1da37,0x1da3a), R(0x1da6d,0x1da74), R(0x1da76,0x1da83), R(0x1da85,0x1da8b),
660
0
            R(0x1db00,0x1db1c), S(0x1e14f), S(0x1e2ff), S(0x1e5ff), R(0x1e95e,0x1e95f), S(0x1ecac), S(0x1ecb0),
661
0
            S(0x1ed2e), R(0x1eef0,0x1eef1), R(0x1f000,0x1f02b), R(0x1f030,0x1f093), R(0x1f0a0,0x1f0ae),
662
0
            R(0x1f0b1,0x1f0bf), R(0x1f0c1,0x1f0cf), R(0x1f0d1,0x1f0f5), R(0x1f10d,0x1f1ae), R(0x1f1e6,0x1f202),
663
0
            R(0x1f210,0x1f23b), R(0x1f240,0x1f248), R(0x1f250,0x1f251), R(0x1f260,0x1f265), R(0x1f300,0x1f6d9),
664
0
            R(0x1f6dc,0x1f6ec), R(0x1f6f0,0x1f6fc), R(0x1f700,0x1f7db), R(0x1f7e0,0x1f7eb), R(0x1f7f0,0x1f80b),
665
0
            R(0x1f810,0x1f847), R(0x1f850,0x1f859), R(0x1f860,0x1f887), R(0x1f890,0x1f8ad), R(0x1f8b0,0x1f8bb),
666
0
            R(0x1f8c0,0x1f8c1), R(0x1f8d0,0x1f8d8), R(0x1f900,0x1fa57), R(0x1fa60,0x1fa6d), R(0x1fa70,0x1fa7c),
667
0
            R(0x1fa80,0x1fac6), S(0x1fac8), R(0x1facc,0x1fadd), R(0x1fadf,0x1faeb), R(0x1faef,0x1fafa),
668
0
            R(0x1fb00,0x1fb92), R(0x1fb94,0x1fbef), S(0x1fbfa)
669
0
        };
670
0
#undef R
671
0
#undef S
672
673
        /* The ASCII ones are the most frequently used ones, also CommonMark
674
         * specification requests few more in this range. */
675
0
        if(codepoint <= 0x7f)
676
0
            return ISPUNCT_(codepoint);
677
678
0
        return (md_unicode_bsearch__(codepoint, PUNCT_MAP, SIZEOF_ARRAY(PUNCT_MAP)) >= 0);
679
0
    }
680
681
    static void
682
    md_get_unicode_fold_info(unsigned codepoint, MD_UNICODE_FOLD_INFO* info)
683
0
    {
684
0
#define R(cp_min, cp_max)   ((cp_min) | 0x40000000), ((cp_max) | 0x80000000)
685
0
#define S(cp)               (cp)
686
        /* Unicode "Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps" categories.
687
         * (generated by scripts/build_folding_map.py) */
688
0
        static const unsigned FOLD_MAP_1[] = {
689
0
            R(0x0041,0x005a), S(0x00b5), R(0x00c0,0x00d6), R(0x00d8,0x00de), R(0x0100,0x012e), R(0x0132,0x0136),
690
0
            R(0x0139,0x0147), R(0x014a,0x0176), S(0x0178), R(0x0179,0x017d), S(0x017f), S(0x0181), S(0x0182),
691
0
            S(0x0184), S(0x0186), S(0x0187), S(0x0189), S(0x018a), S(0x018b), S(0x018e), S(0x018f), S(0x0190),
692
0
            S(0x0191), S(0x0193), S(0x0194), S(0x0196), S(0x0197), S(0x0198), S(0x019c), S(0x019d), S(0x019f),
693
0
            R(0x01a0,0x01a4), S(0x01a6), S(0x01a7), S(0x01a9), S(0x01ac), S(0x01ae), S(0x01af), S(0x01b1), S(0x01b2),
694
0
            S(0x01b3), S(0x01b5), S(0x01b7), S(0x01b8), S(0x01bc), S(0x01c4), S(0x01c5), S(0x01c7), S(0x01c8),
695
0
            S(0x01ca), R(0x01cb,0x01db), R(0x01de,0x01ee), S(0x01f1), S(0x01f2), S(0x01f4), S(0x01f6), S(0x01f7),
696
0
            R(0x01f8,0x021e), S(0x0220), R(0x0222,0x0232), S(0x023a), S(0x023b), S(0x023d), S(0x023e), S(0x0241),
697
0
            S(0x0243), S(0x0244), S(0x0245), R(0x0246,0x024e), S(0x0345), S(0x0370), S(0x0372), S(0x0376), S(0x037f),
698
0
            S(0x0386), R(0x0388,0x038a), S(0x038c), S(0x038e), S(0x038f), R(0x0391,0x03a1), R(0x03a3,0x03ab),
699
0
            S(0x03c2), S(0x03cf), S(0x03d0), S(0x03d1), S(0x03d5), S(0x03d6), R(0x03d8,0x03ee), S(0x03f0), S(0x03f1),
700
0
            S(0x03f4), S(0x03f5), S(0x03f7), S(0x03f9), S(0x03fa), R(0x03fd,0x03ff), R(0x0400,0x040f),
701
0
            R(0x0410,0x042f), R(0x0460,0x0480), R(0x048a,0x04be), S(0x04c0), R(0x04c1,0x04cd), R(0x04d0,0x052e),
702
0
            R(0x0531,0x0556), R(0x10a0,0x10c5), S(0x10c7), S(0x10cd), R(0x13f8,0x13fd), S(0x1c80), S(0x1c81),
703
0
            S(0x1c82), S(0x1c83), S(0x1c84), S(0x1c85), S(0x1c86), S(0x1c87), S(0x1c88), S(0x1c89), R(0x1c90,0x1cba),
704
0
            R(0x1cbd,0x1cbf), R(0x1e00,0x1e94), S(0x1e9b), R(0x1ea0,0x1efe), R(0x1f08,0x1f0f), R(0x1f18,0x1f1d),
705
0
            R(0x1f28,0x1f2f), R(0x1f38,0x1f3f), R(0x1f48,0x1f4d), S(0x1f59), S(0x1f5b), S(0x1f5d), S(0x1f5f),
706
0
            R(0x1f68,0x1f6f), S(0x1fb8), S(0x1fb9), S(0x1fba), S(0x1fbb), S(0x1fbe), R(0x1fc8,0x1fcb), S(0x1fd8),
707
0
            S(0x1fd9), S(0x1fda), S(0x1fdb), S(0x1fe8), S(0x1fe9), S(0x1fea), S(0x1feb), S(0x1fec), S(0x1ff8),
708
0
            S(0x1ff9), S(0x1ffa), S(0x1ffb), S(0x2126), S(0x212a), S(0x212b), S(0x2132), R(0x2160,0x216f), S(0x2183),
709
0
            R(0x24b6,0x24cf), R(0x2c00,0x2c2f), S(0x2c60), S(0x2c62), S(0x2c63), S(0x2c64), R(0x2c67,0x2c6b),
710
0
            S(0x2c6d), S(0x2c6e), S(0x2c6f), S(0x2c70), S(0x2c72), S(0x2c75), S(0x2c7e), S(0x2c7f), R(0x2c80,0x2ce2),
711
0
            S(0x2ceb), S(0x2ced), S(0x2cf2), R(0xa640,0xa66c), R(0xa680,0xa69a), R(0xa722,0xa72e), R(0xa732,0xa76e),
712
0
            S(0xa779), S(0xa77b), S(0xa77d), R(0xa77e,0xa786), S(0xa78b), S(0xa78d), S(0xa790), S(0xa792),
713
0
            R(0xa796,0xa7a8), S(0xa7aa), S(0xa7ab), S(0xa7ac), S(0xa7ad), S(0xa7ae), S(0xa7b0), S(0xa7b1), S(0xa7b2),
714
0
            S(0xa7b3), R(0xa7b4,0xa7c2), S(0xa7c4), S(0xa7c5), S(0xa7c6), S(0xa7c7), S(0xa7c9), S(0xa7cb),
715
0
            R(0xa7cc,0xa7da), S(0xa7dc), S(0xa7dd), S(0xa7e2), S(0xa7f5), S(0xab6c), S(0xab6d), R(0xab70,0xabbf),
716
0
            R(0xff21,0xff3a), R(0x10400,0x10427), R(0x104b0,0x104d3), R(0x10570,0x1057a), R(0x1057c,0x1058a),
717
0
            R(0x1058c,0x10592), S(0x10594), S(0x10595), R(0x10c80,0x10cb2), R(0x10d50,0x10d65), R(0x118a0,0x118bf),
718
0
            R(0x16e40,0x16e5f), R(0x16ea0,0x16eb8), S(0x1df40), S(0x1df48), S(0x1df4a), S(0x1df4d), S(0x1df51),
719
0
            R(0x1df68,0x1df6e), R(0x1df72,0x1df7e), R(0x1e900,0x1e921)
720
0
        };
721
0
        static const unsigned FOLD_MAP_1_DATA[] = {
722
0
            0x0061, 0x007a, 0x03bc, 0x00e0, 0x00f6, 0x00f8, 0x00fe, 0x0101, 0x012f, 0x0133, 0x0137, 0x013a, 0x0148,
723
0
            0x014b, 0x0177, 0x00ff, 0x017a, 0x017e, 0x0073, 0x0253, 0x0183, 0x0185, 0x0254, 0x0188, 0x0256, 0x0257,
724
0
            0x018c, 0x01dd, 0x0259, 0x025b, 0x0192, 0x0260, 0x0263, 0x0269, 0x0268, 0x0199, 0x026f, 0x0272, 0x0275,
725
0
            0x01a1, 0x01a5, 0x0280, 0x01a8, 0x0283, 0x01ad, 0x0288, 0x01b0, 0x028a, 0x028b, 0x01b4, 0x01b6, 0x0292,
726
0
            0x01b9, 0x01bd, 0x01c6, 0x01c6, 0x01c9, 0x01c9, 0x01cc, 0x01cc, 0x01dc, 0x01df, 0x01ef, 0x01f3, 0x01f3,
727
0
            0x01f5, 0x0195, 0x01bf, 0x01f9, 0x021f, 0x019e, 0x0223, 0x0233, 0x2c65, 0x023c, 0x019a, 0x2c66, 0x0242,
728
0
            0x0180, 0x0289, 0x028c, 0x0247, 0x024f, 0x03b9, 0x0371, 0x0373, 0x0377, 0x03f3, 0x03ac, 0x03ad, 0x03af,
729
0
            0x03cc, 0x03cd, 0x03ce, 0x03b1, 0x03c1, 0x03c3, 0x03cb, 0x03c3, 0x03d7, 0x03b2, 0x03b8, 0x03c6, 0x03c0,
730
0
            0x03d9, 0x03ef, 0x03ba, 0x03c1, 0x03b8, 0x03b5, 0x03f8, 0x03f2, 0x03fb, 0x037b, 0x037d, 0x0450, 0x045f,
731
0
            0x0430, 0x044f, 0x0461, 0x0481, 0x048b, 0x04bf, 0x04cf, 0x04c2, 0x04ce, 0x04d1, 0x052f, 0x0561, 0x0586,
732
0
            0x2d00, 0x2d25, 0x2d27, 0x2d2d, 0x13f0, 0x13f5, 0x0432, 0x0434, 0x043e, 0x0441, 0x0442, 0x0442, 0x044a,
733
0
            0x0463, 0xa64b, 0x1c8a, 0x10d0, 0x10fa, 0x10fd, 0x10ff, 0x1e01, 0x1e95, 0x1e61, 0x1ea1, 0x1eff, 0x1f00,
734
0
            0x1f07, 0x1f10, 0x1f15, 0x1f20, 0x1f27, 0x1f30, 0x1f37, 0x1f40, 0x1f45, 0x1f51, 0x1f53, 0x1f55, 0x1f57,
735
0
            0x1f60, 0x1f67, 0x1fb0, 0x1fb1, 0x1f70, 0x1f71, 0x03b9, 0x1f72, 0x1f75, 0x1fd0, 0x1fd1, 0x1f76, 0x1f77,
736
0
            0x1fe0, 0x1fe1, 0x1f7a, 0x1f7b, 0x1fe5, 0x1f78, 0x1f79, 0x1f7c, 0x1f7d, 0x03c9, 0x006b, 0x00e5, 0x214e,
737
0
            0x2170, 0x217f, 0x2184, 0x24d0, 0x24e9, 0x2c30, 0x2c5f, 0x2c61, 0x026b, 0x1d7d, 0x027d, 0x2c68, 0x2c6c,
738
0
            0x0251, 0x0271, 0x0250, 0x0252, 0x2c73, 0x2c76, 0x023f, 0x0240, 0x2c81, 0x2ce3, 0x2cec, 0x2cee, 0x2cf3,
739
0
            0xa641, 0xa66d, 0xa681, 0xa69b, 0xa723, 0xa72f, 0xa733, 0xa76f, 0xa77a, 0xa77c, 0x1d79, 0xa77f, 0xa787,
740
0
            0xa78c, 0x0265, 0xa791, 0xa793, 0xa797, 0xa7a9, 0x0266, 0x025c, 0x0261, 0x026c, 0x026a, 0x029e, 0x0287,
741
0
            0x029d, 0xab53, 0xa7b5, 0xa7c3, 0xa794, 0x0282, 0x1d8e, 0xa7c8, 0xa7ca, 0x0264, 0xa7cd, 0xa7db, 0x019b,
742
0
            0x0277, 0x027c, 0xa7f6, 0xab4b, 0xab4c, 0x13a0, 0x13ef, 0xff41, 0xff5a, 0x10428, 0x1044f, 0x104d8,
743
0
            0x104fb, 0x10597, 0x105a1, 0x105a3, 0x105b1, 0x105b3, 0x105b9, 0x105bb, 0x105bc, 0x10cc0, 0x10cf2,
744
0
            0x10d70, 0x10d85, 0x118c0, 0x118df, 0x16e60, 0x16e7f, 0x16ebb, 0x16ed3, 0x1df41, 0x1df49, 0x1df4b,
745
0
            0x1df4e, 0x1df52, 0x1df69, 0x1df6f, 0x1df73, 0x1df7f, 0x1e922, 0x1e943
746
0
        };
747
0
        static const unsigned FOLD_MAP_2[] = {
748
0
            S(0x00df), S(0x0130), S(0x0149), S(0x01f0), S(0x0587), S(0x1e96), S(0x1e97), S(0x1e98), S(0x1e99),
749
0
            S(0x1e9a), S(0x1e9e), S(0x1f50), R(0x1f80,0x1f87), R(0x1f88,0x1f8f), R(0x1f90,0x1f97), R(0x1f98,0x1f9f),
750
0
            R(0x1fa0,0x1fa7), R(0x1fa8,0x1faf), S(0x1fb2), S(0x1fb3), S(0x1fb4), S(0x1fb6), S(0x1fbc), S(0x1fc2),
751
0
            S(0x1fc3), S(0x1fc4), S(0x1fc6), S(0x1fcc), S(0x1fd6), S(0x1fe4), S(0x1fe6), S(0x1ff2), S(0x1ff3),
752
0
            S(0x1ff4), S(0x1ff6), S(0x1ffc), S(0xfb00), S(0xfb01), S(0xfb02), S(0xfb05), S(0xfb06), S(0xfb13),
753
0
            S(0xfb14), S(0xfb15), S(0xfb16), S(0xfb17), S(0x1df95)
754
0
        };
755
0
        static const unsigned FOLD_MAP_2_DATA[] = {
756
0
            0x0073,0x0073, 0x0069,0x0307, 0x02bc,0x006e, 0x006a,0x030c, 0x0565,0x0582, 0x0068,0x0331, 0x0074,0x0308,
757
0
            0x0077,0x030a, 0x0079,0x030a, 0x0061,0x02be, 0x0073,0x0073, 0x03c5,0x0313, 0x1f00,0x03b9, 0x1f07,0x03b9,
758
0
            0x1f00,0x03b9, 0x1f07,0x03b9, 0x1f20,0x03b9, 0x1f27,0x03b9, 0x1f20,0x03b9, 0x1f27,0x03b9, 0x1f60,0x03b9,
759
0
            0x1f67,0x03b9, 0x1f60,0x03b9, 0x1f67,0x03b9, 0x1f70,0x03b9, 0x03b1,0x03b9, 0x03ac,0x03b9, 0x03b1,0x0342,
760
0
            0x03b1,0x03b9, 0x1f74,0x03b9, 0x03b7,0x03b9, 0x03ae,0x03b9, 0x03b7,0x0342, 0x03b7,0x03b9, 0x03b9,0x0342,
761
0
            0x03c1,0x0313, 0x03c5,0x0342, 0x1f7c,0x03b9, 0x03c9,0x03b9, 0x03ce,0x03b9, 0x03c9,0x0342, 0x03c9,0x03b9,
762
0
            0x0066,0x0066, 0x0066,0x0069, 0x0066,0x006c, 0x0073,0x0074, 0x0073,0x0074, 0x0574,0x0576, 0x0574,0x0565,
763
0
            0x0574,0x056b, 0x057e,0x0576, 0x0574,0x056d, 0x0073,0x0073
764
0
        };
765
0
        static const unsigned FOLD_MAP_3[] = {
766
0
            S(0x0390), S(0x03b0), S(0x1f52), S(0x1f54), S(0x1f56), S(0x1fb7), S(0x1fc7), S(0x1fd2), S(0x1fd3),
767
0
            S(0x1fd7), S(0x1fe2), S(0x1fe3), S(0x1fe7), S(0x1ff7), S(0xfb03), S(0xfb04)
768
0
        };
769
0
        static const unsigned FOLD_MAP_3_DATA[] = {
770
0
            0x03b9,0x0308,0x0301, 0x03c5,0x0308,0x0301, 0x03c5,0x0313,0x0300, 0x03c5,0x0313,0x0301,
771
0
            0x03c5,0x0313,0x0342, 0x03b1,0x0342,0x03b9, 0x03b7,0x0342,0x03b9, 0x03b9,0x0308,0x0300,
772
0
            0x03b9,0x0308,0x0301, 0x03b9,0x0308,0x0342, 0x03c5,0x0308,0x0300, 0x03c5,0x0308,0x0301,
773
0
            0x03c5,0x0308,0x0342, 0x03c9,0x0342,0x03b9, 0x0066,0x0066,0x0069, 0x0066,0x0066,0x006c
774
0
        };
775
0
#undef R
776
0
#undef S
777
0
        static const struct {
778
0
            const unsigned* map;
779
0
            const unsigned* data;
780
0
            size_t map_size;
781
0
            unsigned n_codepoints;
782
0
        } FOLD_MAP_LIST[] = {
783
0
            { FOLD_MAP_1, FOLD_MAP_1_DATA, SIZEOF_ARRAY(FOLD_MAP_1), 1 },
784
0
            { FOLD_MAP_2, FOLD_MAP_2_DATA, SIZEOF_ARRAY(FOLD_MAP_2), 2 },
785
0
            { FOLD_MAP_3, FOLD_MAP_3_DATA, SIZEOF_ARRAY(FOLD_MAP_3), 3 }
786
0
        };
787
788
0
        int i;
789
790
        /* Fast path for ASCII characters. */
791
0
        if(codepoint <= 0x7f) {
792
0
            info->codepoints[0] = codepoint;
793
0
            if(ISUPPER_(codepoint))
794
0
                info->codepoints[0] += 'a' - 'A';
795
0
            info->n_codepoints = 1;
796
0
            return;
797
0
        }
798
799
        /* Try to locate the codepoint in any of the maps. */
800
0
        for(i = 0; i < (int) SIZEOF_ARRAY(FOLD_MAP_LIST); i++) {
801
0
            int index;
802
803
0
            index = md_unicode_bsearch__(codepoint, FOLD_MAP_LIST[i].map, FOLD_MAP_LIST[i].map_size);
804
0
            if(index >= 0) {
805
                /* Found the mapping. */
806
0
                unsigned n_codepoints = FOLD_MAP_LIST[i].n_codepoints;
807
0
                const unsigned* map = FOLD_MAP_LIST[i].map;
808
0
                const unsigned* codepoints = FOLD_MAP_LIST[i].data + (index * n_codepoints);
809
810
0
                memcpy(info->codepoints, codepoints, sizeof(unsigned) * n_codepoints);
811
0
                info->n_codepoints = n_codepoints;
812
813
0
                if(FOLD_MAP_LIST[i].map[index] != codepoint) {
814
                    /* The found mapping maps whole range of codepoints,
815
                     * i.e. we have to offset info->codepoints[0] accordingly. */
816
0
                    if((map[index] & 0x00ffffff)+1 == codepoints[0]) {
817
                        /* Alternating type of the range. */
818
0
                        info->codepoints[0] = codepoint + ((codepoint & 0x1) == (map[index] & 0x1) ? 1 : 0);
819
0
                    } else {
820
                        /* Range to range kind of mapping. */
821
0
                        info->codepoints[0] += (codepoint - (map[index] & 0x00ffffff));
822
0
                    }
823
0
                }
824
825
0
                return;
826
0
            }
827
0
        }
828
829
        /* No mapping found. Map the codepoint to itself. */
830
0
        info->codepoints[0] = codepoint;
831
0
        info->n_codepoints = 1;
832
0
    }
833
#endif
834
835
836
#if defined MD4C_USE_UTF16
837
    #define IS_UTF16_SURROGATE_HI(word)     (((WORD)(word) & 0xfc00) == 0xd800)
838
    #define IS_UTF16_SURROGATE_LO(word)     (((WORD)(word) & 0xfc00) == 0xdc00)
839
    #define UTF16_DECODE_SURROGATE(hi, lo)  (0x10000 + ((((unsigned)(hi) & 0x3ff) << 10) | (((unsigned)(lo) & 0x3ff) << 0)))
840
841
    static unsigned
842
    md_decode_utf16le__(const CHAR* str, SZ str_size, SZ* p_size)
843
    {
844
        if(IS_UTF16_SURROGATE_HI(str[0])) {
845
            if(1 < str_size && IS_UTF16_SURROGATE_LO(str[1])) {
846
                if(p_size != NULL)
847
                    *p_size = 2;
848
                return UTF16_DECODE_SURROGATE(str[0], str[1]);
849
            }
850
        }
851
852
        if(p_size != NULL)
853
            *p_size = 1;
854
        return str[0];
855
    }
856
857
    static unsigned
858
    md_decode_utf16le_before__(MD_CTX* ctx, OFF off)
859
    {
860
        if(off > 2 && IS_UTF16_SURROGATE_HI(CH(off-2)) && IS_UTF16_SURROGATE_LO(CH(off-1)))
861
            return UTF16_DECODE_SURROGATE(CH(off-2), CH(off-1));
862
863
        return CH(off-1);
864
    }
865
866
    /* No whitespace uses surrogates, so no decoding needed here. */
867
    #define ISUNICODEWHITESPACE_(codepoint) md_is_unicode_whitespace__(codepoint)
868
    #define ISUNICODEWHITESPACE(off)        md_is_unicode_whitespace__(CH(off))
869
    #define ISUNICODEWHITESPACEBEFORE(off)  md_is_unicode_whitespace__(CH((off)-1))
870
871
    #define ISUNICODEPUNCT(off)             md_is_unicode_punct__(md_decode_utf16le__(STR(off), ctx->size - (off), NULL))
872
    #define ISUNICODEPUNCTBEFORE(off)       md_is_unicode_punct__(md_decode_utf16le_before__(ctx, off))
873
874
    static inline int
875
    md_decode_unicode(const CHAR* str, OFF off, SZ str_size, SZ* p_char_size)
876
    {
877
        return md_decode_utf16le__(str+off, str_size-off, p_char_size);
878
    }
879
#elif defined MD4C_USE_UTF8
880
0
    #define IS_UTF8_LEAD1(byte)     ((unsigned char)(byte) <= 0x7f)
881
0
    #define IS_UTF8_LEAD2(byte)     (((unsigned char)(byte) & 0xe0) == 0xc0)
882
0
    #define IS_UTF8_LEAD3(byte)     (((unsigned char)(byte) & 0xf0) == 0xe0)
883
0
    #define IS_UTF8_LEAD4(byte)     (((unsigned char)(byte) & 0xf8) == 0xf0)
884
0
    #define IS_UTF8_TAIL(byte)      (((unsigned char)(byte) & 0xc0) == 0x80)
885
886
    static unsigned
887
    md_decode_utf8__(const CHAR* str, SZ str_size, SZ* p_size)
888
0
    {
889
0
        if(!IS_UTF8_LEAD1(str[0])) {
890
0
            if(IS_UTF8_LEAD2(str[0])) {
891
0
                if(1 < str_size && IS_UTF8_TAIL(str[1])) {
892
0
                    if(p_size != NULL)
893
0
                        *p_size = 2;
894
895
0
                    return (((unsigned int)str[0] & 0x1f) << 6) |
896
0
                           (((unsigned int)str[1] & 0x3f) << 0);
897
0
                }
898
0
            } else if(IS_UTF8_LEAD3(str[0])) {
899
0
                if(2 < str_size && IS_UTF8_TAIL(str[1]) && IS_UTF8_TAIL(str[2])) {
900
0
                    if(p_size != NULL)
901
0
                        *p_size = 3;
902
903
0
                    return (((unsigned int)str[0] & 0x0f) << 12) |
904
0
                           (((unsigned int)str[1] & 0x3f) << 6) |
905
0
                           (((unsigned int)str[2] & 0x3f) << 0);
906
0
                }
907
0
            } else if(IS_UTF8_LEAD4(str[0])) {
908
0
                if(3 < str_size && IS_UTF8_TAIL(str[1]) && IS_UTF8_TAIL(str[2]) && IS_UTF8_TAIL(str[3])) {
909
0
                    if(p_size != NULL)
910
0
                        *p_size = 4;
911
912
0
                    return (((unsigned int)str[0] & 0x07) << 18) |
913
0
                           (((unsigned int)str[1] & 0x3f) << 12) |
914
0
                           (((unsigned int)str[2] & 0x3f) << 6) |
915
0
                           (((unsigned int)str[3] & 0x3f) << 0);
916
0
                }
917
0
            }
918
0
        }
919
920
0
        if(p_size != NULL)
921
0
            *p_size = 1;
922
0
        return (unsigned) str[0];
923
0
    }
924
925
    static unsigned
926
    md_decode_utf8_before__(MD_CTX* ctx, OFF off)
927
0
    {
928
0
        if(!IS_UTF8_LEAD1(CH(off-1))) {
929
0
            if(off > 1 && IS_UTF8_LEAD2(CH(off-2)) && IS_UTF8_TAIL(CH(off-1)))
930
0
                return (((unsigned int)CH(off-2) & 0x1f) << 6) |
931
0
                       (((unsigned int)CH(off-1) & 0x3f) << 0);
932
933
0
            if(off > 2 && IS_UTF8_LEAD3(CH(off-3)) && IS_UTF8_TAIL(CH(off-2)) && IS_UTF8_TAIL(CH(off-1)))
934
0
                return (((unsigned int)CH(off-3) & 0x0f) << 12) |
935
0
                       (((unsigned int)CH(off-2) & 0x3f) << 6) |
936
0
                       (((unsigned int)CH(off-1) & 0x3f) << 0);
937
938
0
            if(off > 3 && IS_UTF8_LEAD4(CH(off-4)) && IS_UTF8_TAIL(CH(off-3)) && IS_UTF8_TAIL(CH(off-2)) && IS_UTF8_TAIL(CH(off-1)))
939
0
                return (((unsigned int)CH(off-4) & 0x07) << 18) |
940
0
                       (((unsigned int)CH(off-3) & 0x3f) << 12) |
941
0
                       (((unsigned int)CH(off-2) & 0x3f) << 6) |
942
0
                       (((unsigned int)CH(off-1) & 0x3f) << 0);
943
0
        }
944
945
0
        return (unsigned) CH(off-1);
946
0
    }
947
948
0
    #define ISUNICODEWHITESPACE_(codepoint) md_is_unicode_whitespace__(codepoint)
949
0
    #define ISUNICODEWHITESPACE(off)        md_is_unicode_whitespace__(md_decode_utf8__(STR(off), ctx->size - (off), NULL))
950
0
    #define ISUNICODEWHITESPACEBEFORE(off)  md_is_unicode_whitespace__(md_decode_utf8_before__(ctx, off))
951
952
0
    #define ISUNICODEPUNCT(off)             md_is_unicode_punct__(md_decode_utf8__(STR(off), ctx->size - (off), NULL))
953
0
    #define ISUNICODEPUNCTBEFORE(off)       md_is_unicode_punct__(md_decode_utf8_before__(ctx, off))
954
955
    static inline unsigned
956
    md_decode_unicode(const CHAR* str, OFF off, SZ str_size, SZ* p_char_size)
957
0
    {
958
0
        return md_decode_utf8__(str+off, str_size-off, p_char_size);
959
0
    }
960
#else
961
    #define ISUNICODEWHITESPACE_(codepoint) ISWHITESPACE_(codepoint)
962
    #define ISUNICODEWHITESPACE(off)        ISWHITESPACE(off)
963
    #define ISUNICODEWHITESPACEBEFORE(off)  ISWHITESPACE((off)-1)
964
965
    #define ISUNICODEPUNCT(off)             ISPUNCT(off)
966
    #define ISUNICODEPUNCTBEFORE(off)       ISPUNCT((off)-1)
967
968
    static inline void
969
    md_get_unicode_fold_info(unsigned codepoint, MD_UNICODE_FOLD_INFO* info)
970
    {
971
        info->codepoints[0] = codepoint;
972
        if(ISUPPER_(codepoint))
973
            info->codepoints[0] += 'a' - 'A';
974
        info->n_codepoints = 1;
975
    }
976
977
    static inline unsigned
978
    md_decode_unicode(const CHAR* str, OFF off, SZ str_size, SZ* p_size)
979
    {
980
        *p_size = 1;
981
        return (unsigned) str[off];
982
    }
983
#endif
984
985
986
/*************************************
987
 ***  Helper string manipulations  ***
988
 *************************************/
989
990
/* Fill buffer with copy of the string between 'beg' and 'end' but replace any
991
 * line breaks with given replacement character.
992
 *
993
 * NOTE: Caller is responsible to make sure the buffer is large enough.
994
 * (Given the output is always shorter than input, (end - beg) is good idea
995
 * what the caller should allocate.)
996
 */
997
static void
998
md_merge_lines(MD_CTX* ctx, OFF beg, OFF end, const MD_LINE* lines, MD_SIZE n_lines,
999
               CHAR line_break_replacement_char, CHAR* buffer, SZ* p_size)
1000
0
{
1001
0
    CHAR* ptr = buffer;
1002
0
    int line_index = 0;
1003
0
    OFF off = beg;
1004
1005
0
    MD_UNUSED(n_lines);
1006
1007
0
    while(1) {
1008
0
        const MD_LINE* line = &lines[line_index];
1009
0
        OFF line_end = line->end;
1010
0
        if(end < line_end)
1011
0
            line_end = end;
1012
1013
0
        while(off < line_end) {
1014
0
            *ptr = CH(off);
1015
0
            ptr++;
1016
0
            off++;
1017
0
        }
1018
1019
0
        if(off >= end) {
1020
0
            *p_size = (MD_SIZE)(ptr - buffer);
1021
0
            return;
1022
0
        }
1023
1024
0
        *ptr = line_break_replacement_char;
1025
0
        ptr++;
1026
1027
0
        line_index++;
1028
0
        off = lines[line_index].beg;
1029
0
    }
1030
0
}
1031
1032
/* Wrapper of md_merge_lines() which allocates new buffer for the output string.
1033
 */
1034
static int
1035
md_merge_lines_alloc(MD_CTX* ctx, OFF beg, OFF end, const MD_LINE* lines, MD_SIZE n_lines,
1036
                    CHAR line_break_replacement_char, CHAR** p_str, SZ* p_size)
1037
0
{
1038
0
    CHAR* buffer;
1039
1040
0
    buffer = (CHAR*) malloc(sizeof(CHAR) * (end - beg));
1041
0
    if(buffer == NULL) {
1042
0
        MD_LOG("malloc() failed.");
1043
0
        return -1;
1044
0
    }
1045
1046
0
    md_merge_lines(ctx, beg, end, lines, n_lines,
1047
0
                line_break_replacement_char, buffer, p_size);
1048
1049
0
    *p_str = buffer;
1050
0
    return 0;
1051
0
}
1052
1053
static OFF
1054
md_skip_unicode_whitespace(const CHAR* label, OFF off, SZ size)
1055
0
{
1056
0
    SZ char_size;
1057
0
    unsigned codepoint;
1058
1059
0
    while(off < size) {
1060
0
        codepoint = md_decode_unicode(label, off, size, &char_size);
1061
0
        if(!ISUNICODEWHITESPACE_(codepoint)  &&  !ISNEWLINE_(label[off]))
1062
0
            break;
1063
0
        off += char_size;
1064
0
    }
1065
1066
0
    return off;
1067
0
}
1068
1069
1070
/******************************
1071
 ***  Recognizing raw HTML  ***
1072
 ******************************/
1073
1074
/* md_is_html_tag() may be called when processing inlines (inline raw HTML)
1075
 * or when breaking document to blocks (checking for start of HTML block type 7).
1076
 *
1077
 * When breaking document to blocks, we do not yet know line boundaries, but
1078
 * in that case the whole tag has to live on a single line. We distinguish this
1079
 * by n_lines == 0.
1080
 */
1081
static int
1082
md_is_html_tag(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end)
1083
0
{
1084
0
    int attr_state;
1085
0
    OFF off = beg;
1086
0
    OFF line_end = (n_lines > 0) ? lines[0].end : ctx->size;
1087
0
    MD_SIZE line_index = 0;
1088
1089
0
    MD_ASSERT(CH(beg) == _T('<'));
1090
1091
0
    if(off + 1 >= line_end)
1092
0
        return FALSE;
1093
0
    off++;
1094
1095
    /* For parsing attributes, we need a little state automaton below.
1096
     * State -1: no attributes are allowed.
1097
     * State 0: attribute could follow after some whitespace.
1098
     * State 1: after a whitespace (attribute name may follow).
1099
     * State 2: after attribute name ('=' MAY follow).
1100
     * State 3: after '=' (value specification MUST follow).
1101
     * State 41: in middle of unquoted attribute value.
1102
     * State 42: in middle of single-quoted attribute value.
1103
     * State 43: in middle of double-quoted attribute value.
1104
     */
1105
0
    attr_state = 0;
1106
1107
0
    if(CH(off) == _T('/')) {
1108
        /* Closer tag "</ ... >". No attributes may be present. */
1109
0
        attr_state = -1;
1110
0
        off++;
1111
0
    }
1112
1113
    /* Tag name */
1114
0
    if(off >= line_end  ||  !ISALPHA(off))
1115
0
        return FALSE;
1116
0
    off++;
1117
0
    while(off < line_end  &&  (ISALNUM(off)  ||  CH(off) == _T('-')))
1118
0
        off++;
1119
1120
    /* (Optional) attributes (if not closer), (optional) '/' (if not closer)
1121
     * and final '>'. */
1122
0
    while(1) {
1123
0
        while(off < line_end  &&  !ISNEWLINE(off)) {
1124
0
            if(attr_state > 40) {
1125
0
                if(attr_state == 41 && (ISBLANK(off) || ISANYOF(off, _T("\"'=<>`")))) {
1126
0
                    attr_state = 0;
1127
0
                    off--;  /* Put the char back for re-inspection in the new state. */
1128
0
                } else if(attr_state == 42 && CH(off) == _T('\'')) {
1129
0
                    attr_state = 0;
1130
0
                } else if(attr_state == 43 && CH(off) == _T('"')) {
1131
0
                    attr_state = 0;
1132
0
                }
1133
0
                off++;
1134
0
            } else if(ISWHITESPACE(off)) {
1135
0
                if(attr_state == 0)
1136
0
                    attr_state = 1;
1137
0
                off++;
1138
0
            } else if(attr_state <= 2 && CH(off) == _T('>')) {
1139
                /* End. */
1140
0
                goto done;
1141
0
            } else if(attr_state <= 2 && CH(off) == _T('/') && off+1 < line_end && CH(off+1) == _T('>')) {
1142
                /* End with digraph '/>' */
1143
0
                off++;
1144
0
                goto done;
1145
0
            } else if((attr_state == 1 || attr_state == 2) && (ISALPHA(off) || CH(off) == _T('_') || CH(off) == _T(':'))) {
1146
0
                off++;
1147
                /* Attribute name */
1148
0
                while(off < line_end && (ISALNUM(off) || ISANYOF(off, _T("_.:-"))))
1149
0
                    off++;
1150
0
                attr_state = 2;
1151
0
            } else if(attr_state == 2 && CH(off) == _T('=')) {
1152
                /* Attribute assignment sign */
1153
0
                off++;
1154
0
                attr_state = 3;
1155
0
            } else if(attr_state == 3) {
1156
                /* Expecting start of attribute value. */
1157
0
                if(CH(off) == _T('"'))
1158
0
                    attr_state = 43;
1159
0
                else if(CH(off) == _T('\''))
1160
0
                    attr_state = 42;
1161
0
                else if(!ISANYOF(off, _T("\"'=<>`"))  &&  !ISNEWLINE(off))
1162
0
                    attr_state = 41;
1163
0
                else
1164
0
                    return FALSE;
1165
0
                off++;
1166
0
            } else {
1167
                /* Anything unexpected. */
1168
0
                return FALSE;
1169
0
            }
1170
0
        }
1171
1172
        /* We have to be on a single line. See definition of start condition
1173
         * of HTML block, type 7. */
1174
0
        if(n_lines == 0)
1175
0
            return FALSE;
1176
1177
0
        line_index++;
1178
0
        if(line_index >= n_lines)
1179
0
            return FALSE;
1180
1181
0
        off = lines[line_index].beg;
1182
0
        line_end = lines[line_index].end;
1183
1184
0
        if(attr_state == 0  ||  attr_state == 41)
1185
0
            attr_state = 1;
1186
1187
0
        if(off >= max_end)
1188
0
            return FALSE;
1189
0
    }
1190
1191
0
done:
1192
0
    if(off >= max_end)
1193
0
        return FALSE;
1194
1195
0
    *p_end = off+1;
1196
0
    return TRUE;
1197
0
}
1198
1199
static int
1200
md_scan_for_html_closer(MD_CTX* ctx, const MD_CHAR* str, MD_SIZE len,
1201
                        const MD_LINE* lines, MD_SIZE n_lines,
1202
                        OFF beg, OFF max_end, OFF* p_end,
1203
                        OFF* p_scan_horizon)
1204
0
{
1205
0
    OFF off = beg;
1206
0
    MD_SIZE line_index = 0;
1207
1208
0
    if(off < *p_scan_horizon  &&  *p_scan_horizon >= max_end - len) {
1209
        /* We have already scanned the range up to the max_end so we know
1210
         * there is nothing to see. */
1211
0
        return FALSE;
1212
0
    }
1213
1214
0
    while(TRUE) {
1215
0
        while(off + len <= lines[line_index].end  &&  off + len <= max_end) {
1216
0
            if(md_ascii_eq(STR(off), str, len)) {
1217
                /* Success. */
1218
0
                *p_end = off + len;
1219
0
                return TRUE;
1220
0
            }
1221
0
            off++;
1222
0
        }
1223
1224
0
        line_index++;
1225
0
        if(off >= max_end  ||  line_index >= n_lines) {
1226
            /* Failure. */
1227
0
            *p_scan_horizon = off;
1228
0
            return FALSE;
1229
0
        }
1230
1231
0
        off = lines[line_index].beg;
1232
0
    }
1233
0
}
1234
1235
static int
1236
md_is_html_comment(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end)
1237
0
{
1238
0
    OFF off = beg;
1239
1240
0
    MD_ASSERT(CH(beg) == _T('<'));
1241
1242
0
    if(off + 4 >= lines[0].end)
1243
0
        return FALSE;
1244
0
    if(CH(off+1) != _T('!')  ||  CH(off+2) != _T('-')  ||  CH(off+3) != _T('-'))
1245
0
        return FALSE;
1246
1247
    /* Skip only "<!" so that we accept also "<!-->" or "<!--->" */
1248
0
    off += 2;
1249
1250
    /* Scan for ordinary comment closer "-->". */
1251
0
    return md_scan_for_html_closer(ctx, _T("-->"), 3,
1252
0
                lines, n_lines, off, max_end, p_end, &ctx->html_comment_horizon);
1253
0
}
1254
1255
static int
1256
md_is_html_processing_instruction(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end)
1257
0
{
1258
0
    OFF off = beg;
1259
1260
0
    if(off + 2 >= lines[0].end)
1261
0
        return FALSE;
1262
0
    if(CH(off+1) != _T('?'))
1263
0
        return FALSE;
1264
0
    off += 2;
1265
1266
0
    return md_scan_for_html_closer(ctx, _T("?>"), 2,
1267
0
                lines, n_lines, off, max_end, p_end, &ctx->html_proc_instr_horizon);
1268
0
}
1269
1270
static int
1271
md_is_html_declaration(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end)
1272
0
{
1273
0
    OFF off = beg;
1274
1275
0
    if(off + 2 >= lines[0].end)
1276
0
        return FALSE;
1277
0
    if(CH(off+1) != _T('!'))
1278
0
        return FALSE;
1279
0
    off += 2;
1280
1281
    /* Declaration name. */
1282
0
    if(off >= lines[0].end  ||  !ISALPHA(off))
1283
0
        return FALSE;
1284
0
    off++;
1285
0
    while(off < lines[0].end  &&  ISALPHA(off))
1286
0
        off++;
1287
1288
0
    return md_scan_for_html_closer(ctx, _T(">"), 1,
1289
0
                lines, n_lines, off, max_end, p_end, &ctx->html_decl_horizon);
1290
0
}
1291
1292
static int
1293
md_is_html_cdata(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end)
1294
0
{
1295
0
    static const CHAR open_str[] = _T("<![CDATA[");
1296
0
    static const SZ open_size = SIZEOF_ARRAY(open_str) - 1;
1297
1298
0
    OFF off = beg;
1299
1300
0
    if(off + open_size >= lines[0].end)
1301
0
        return FALSE;
1302
0
    if(memcmp(STR(off), open_str, open_size) != 0)
1303
0
        return FALSE;
1304
0
    off += open_size;
1305
1306
0
    return md_scan_for_html_closer(ctx, _T("]]>"), 3,
1307
0
                lines, n_lines, off, max_end, p_end, &ctx->html_cdata_horizon);
1308
0
}
1309
1310
static int
1311
md_is_html_any(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg, OFF max_end, OFF* p_end)
1312
0
{
1313
0
    MD_ASSERT(CH(beg) == _T('<'));
1314
0
    return (md_is_html_tag(ctx, lines, n_lines, beg, max_end, p_end)  ||
1315
0
            md_is_html_comment(ctx, lines, n_lines, beg, max_end, p_end)  ||
1316
0
            md_is_html_processing_instruction(ctx, lines, n_lines, beg, max_end, p_end)  ||
1317
0
            md_is_html_declaration(ctx, lines, n_lines, beg, max_end, p_end)  ||
1318
0
            md_is_html_cdata(ctx, lines, n_lines, beg, max_end, p_end));
1319
0
}
1320
1321
1322
/****************************
1323
 ***  Recognizing Entity  ***
1324
 ****************************/
1325
1326
static int
1327
md_is_hex_entity_contents(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end)
1328
0
{
1329
0
    OFF off = beg;
1330
0
    MD_UNUSED(ctx);
1331
1332
0
    while(off < max_end  &&  ISXDIGIT_(text[off])  &&  off - beg <= 8)
1333
0
        off++;
1334
1335
0
    if(1 <= off - beg  &&  off - beg <= 6) {
1336
0
        *p_end = off;
1337
0
        return TRUE;
1338
0
    } else {
1339
0
        return FALSE;
1340
0
    }
1341
0
}
1342
1343
static int
1344
md_is_dec_entity_contents(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end)
1345
0
{
1346
0
    OFF off = beg;
1347
0
    MD_UNUSED(ctx);
1348
1349
0
    while(off < max_end  &&  ISDIGIT_(text[off])  &&  off - beg <= 8)
1350
0
        off++;
1351
1352
0
    if(1 <= off - beg  &&  off - beg <= 7) {
1353
0
        *p_end = off;
1354
0
        return TRUE;
1355
0
    } else {
1356
0
        return FALSE;
1357
0
    }
1358
0
}
1359
1360
static int
1361
md_is_named_entity_contents(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end)
1362
0
{
1363
0
    OFF off = beg;
1364
0
    MD_UNUSED(ctx);
1365
1366
0
    if(off < max_end  &&  ISALPHA_(text[off]))
1367
0
        off++;
1368
0
    else
1369
0
        return FALSE;
1370
1371
0
    while(off < max_end  &&  ISALNUM_(text[off])  &&  off - beg <= 48)
1372
0
        off++;
1373
1374
0
    if(2 <= off - beg  &&  off - beg <= 48) {
1375
0
        *p_end = off;
1376
0
        return TRUE;
1377
0
    } else {
1378
0
        return FALSE;
1379
0
    }
1380
0
}
1381
1382
static int
1383
md_is_entity_str(MD_CTX* ctx, const CHAR* text, OFF beg, OFF max_end, OFF* p_end)
1384
0
{
1385
0
    int is_contents;
1386
0
    OFF off = beg;
1387
1388
0
    MD_ASSERT(text[off] == _T('&'));
1389
0
    off++;
1390
1391
0
    if(off+2 < max_end  &&  text[off] == _T('#')  &&  (text[off+1] == _T('x') || text[off+1] == _T('X')))
1392
0
        is_contents = md_is_hex_entity_contents(ctx, text, off+2, max_end, &off);
1393
0
    else if(off+1 < max_end  &&  text[off] == _T('#'))
1394
0
        is_contents = md_is_dec_entity_contents(ctx, text, off+1, max_end, &off);
1395
0
    else
1396
0
        is_contents = md_is_named_entity_contents(ctx, text, off, max_end, &off);
1397
1398
0
    if(is_contents  &&  off < max_end  &&  text[off] == _T(';')) {
1399
0
        *p_end = off+1;
1400
0
        return TRUE;
1401
0
    } else {
1402
0
        return FALSE;
1403
0
    }
1404
0
}
1405
1406
static inline int
1407
md_is_entity(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end)
1408
0
{
1409
0
    return md_is_entity_str(ctx, ctx->text, beg, max_end, p_end);
1410
0
}
1411
1412
1413
/******************************
1414
 ***  Attribute Management  ***
1415
 ******************************/
1416
1417
typedef struct MD_ATTRIBUTE_BUILD_tag MD_ATTRIBUTE_BUILD;
1418
struct MD_ATTRIBUTE_BUILD_tag {
1419
    CHAR* text;
1420
    MD_TEXTTYPE* substr_types;
1421
    OFF* substr_offsets;
1422
    int substr_count;
1423
    int substr_alloc;
1424
    MD_TEXTTYPE trivial_types[1];
1425
    OFF trivial_offsets[2];
1426
};
1427
1428
1429
0
#define MD_BUILD_ATTR_NO_ESCAPES    0x0001
1430
1431
static int
1432
md_build_attr_append_substr(MD_CTX* ctx, MD_ATTRIBUTE_BUILD* build,
1433
                            MD_TEXTTYPE type, OFF off)
1434
0
{
1435
0
    if(build->substr_count >= build->substr_alloc) {
1436
0
        MD_TEXTTYPE* new_substr_types;
1437
0
        OFF* new_substr_offsets;
1438
1439
0
        build->substr_alloc = (build->substr_alloc > 0
1440
0
                ? build->substr_alloc + build->substr_alloc / 2
1441
0
                : 8);
1442
0
        new_substr_types = (MD_TEXTTYPE*) realloc(build->substr_types,
1443
0
                                    build->substr_alloc * sizeof(MD_TEXTTYPE));
1444
0
        if(new_substr_types == NULL) {
1445
0
            MD_LOG("realloc() failed.");
1446
0
            return -1;
1447
0
        }
1448
        /* Note +1 to reserve space for final offset (== raw_size). */
1449
0
        new_substr_offsets = (OFF*) realloc(build->substr_offsets,
1450
0
                                    (build->substr_alloc+1) * sizeof(OFF));
1451
0
        if(new_substr_offsets == NULL) {
1452
0
            MD_LOG("realloc() failed.");
1453
0
            free(new_substr_types);
1454
0
            return -1;
1455
0
        }
1456
1457
0
        build->substr_types = new_substr_types;
1458
0
        build->substr_offsets = new_substr_offsets;
1459
0
    }
1460
1461
0
    build->substr_types[build->substr_count] = type;
1462
0
    build->substr_offsets[build->substr_count] = off;
1463
0
    build->substr_count++;
1464
0
    return 0;
1465
0
}
1466
1467
static void
1468
md_free_attribute(MD_CTX* ctx, MD_ATTRIBUTE_BUILD* build)
1469
0
{
1470
0
    MD_UNUSED(ctx);
1471
1472
0
    if(build->substr_alloc > 0) {
1473
0
        free(build->text);
1474
0
        free(build->substr_types);
1475
0
        free(build->substr_offsets);
1476
0
    }
1477
0
}
1478
1479
static int
1480
md_build_attribute(MD_CTX* ctx, const CHAR* raw_text, SZ raw_size,
1481
                   unsigned flags, MD_ATTRIBUTE* attr, MD_ATTRIBUTE_BUILD* build)
1482
0
{
1483
0
    OFF raw_off, off;
1484
0
    int is_trivial;
1485
0
    int ret = 0;
1486
1487
0
    memset(build, 0, sizeof(MD_ATTRIBUTE_BUILD));
1488
1489
    /* If there is no backslash and no ampersand, build trivial attribute
1490
     * without any malloc(). */
1491
0
    is_trivial = TRUE;
1492
0
    for(raw_off = 0; raw_off < raw_size; raw_off++) {
1493
0
        if(ISANYOF3_(raw_text[raw_off], _T('\\'), _T('&'), _T('\0'))) {
1494
0
            is_trivial = FALSE;
1495
0
            break;
1496
0
        }
1497
0
    }
1498
1499
0
    if(is_trivial) {
1500
0
        build->text = (CHAR*) (raw_size ? raw_text : NULL);
1501
0
        build->substr_types = build->trivial_types;
1502
0
        build->substr_offsets = build->trivial_offsets;
1503
0
        build->substr_count = 1;
1504
0
        build->substr_alloc = 0;
1505
0
        build->trivial_types[0] = MD_TEXT_NORMAL;
1506
0
        build->trivial_offsets[0] = 0;
1507
0
        build->trivial_offsets[1] = raw_size;
1508
0
        off = raw_size;
1509
0
    } else {
1510
0
        build->text = (CHAR*) malloc(raw_size * sizeof(CHAR));
1511
0
        if(build->text == NULL) {
1512
0
            MD_LOG("malloc() failed.");
1513
0
            goto abort;
1514
0
        }
1515
1516
0
        raw_off = 0;
1517
0
        off = 0;
1518
1519
0
        while(raw_off < raw_size) {
1520
0
            if(raw_text[raw_off] == _T('\0')) {
1521
0
                MD_CHECK(md_build_attr_append_substr(ctx, build, MD_TEXT_NULLCHAR, off));
1522
0
                memcpy(build->text + off, raw_text + raw_off, 1);
1523
0
                off++;
1524
0
                raw_off++;
1525
0
                continue;
1526
0
            }
1527
1528
0
            if(raw_text[raw_off] == _T('&')) {
1529
0
                OFF ent_end;
1530
1531
0
                if(md_is_entity_str(ctx, raw_text, raw_off, raw_size, &ent_end)) {
1532
0
                    MD_CHECK(md_build_attr_append_substr(ctx, build, MD_TEXT_ENTITY, off));
1533
0
                    memcpy(build->text + off, raw_text + raw_off, ent_end - raw_off);
1534
0
                    off += ent_end - raw_off;
1535
0
                    raw_off = ent_end;
1536
0
                    continue;
1537
0
                }
1538
0
            }
1539
1540
0
            if(build->substr_count == 0  ||  build->substr_types[build->substr_count-1] != MD_TEXT_NORMAL)
1541
0
                MD_CHECK(md_build_attr_append_substr(ctx, build, MD_TEXT_NORMAL, off));
1542
1543
0
            if(!(flags & MD_BUILD_ATTR_NO_ESCAPES)  &&
1544
0
               raw_text[raw_off] == _T('\\')  &&  raw_off+1 < raw_size  &&
1545
0
               (ISPUNCT_(raw_text[raw_off+1]) || ISNEWLINE_(raw_text[raw_off+1])))
1546
0
                raw_off++;
1547
1548
0
            build->text[off++] = raw_text[raw_off++];
1549
0
        }
1550
0
        build->substr_offsets[build->substr_count] = off;
1551
0
    }
1552
1553
0
    attr->text = build->text;
1554
0
    attr->size = off;
1555
0
    attr->substr_offsets = build->substr_offsets;
1556
0
    attr->substr_types = build->substr_types;
1557
0
    return 0;
1558
1559
0
abort:
1560
0
    md_free_attribute(ctx, build);
1561
0
    return -1;
1562
0
}
1563
1564
1565
/*********************************************
1566
 ***  Dictionary of Reference Definitions  ***
1567
 *********************************************/
1568
1569
0
#define MD_FNV1A_BASE       2166136261U
1570
0
#define MD_FNV1A_PRIME      16777619U
1571
1572
static inline unsigned
1573
md_fnv1a(unsigned base, const void* data, size_t n)
1574
0
{
1575
0
    const unsigned char* buf = (const unsigned char*) data;
1576
0
    unsigned hash = base;
1577
0
    size_t i;
1578
1579
0
    for(i = 0; i < n; i++) {
1580
0
        hash ^= buf[i];
1581
0
        hash *= MD_FNV1A_PRIME;
1582
0
    }
1583
1584
0
    return hash;
1585
0
}
1586
1587
1588
struct MD_REF_DEF_tag {
1589
    CHAR* label;
1590
    CHAR* title;
1591
    unsigned hash;
1592
    SZ label_size;
1593
    SZ title_size;
1594
    OFF dest_beg;
1595
    OFF dest_end;
1596
    unsigned char label_needs_free : 1;
1597
    unsigned char title_needs_free : 1;
1598
};
1599
1600
/* Label equivalence is quite complicated with regards to whitespace and case
1601
 * folding. This complicates computing a hash of it as well as direct comparison
1602
 * of two labels. */
1603
1604
static unsigned
1605
md_link_label_hash(const CHAR* label, SZ size)
1606
0
{
1607
0
    unsigned hash = MD_FNV1A_BASE;
1608
0
    OFF off;
1609
0
    unsigned codepoint;
1610
0
    int is_whitespace = FALSE;
1611
1612
0
    off = md_skip_unicode_whitespace(label, 0, size);
1613
0
    while(off < size) {
1614
0
        SZ char_size;
1615
1616
0
        codepoint = md_decode_unicode(label, off, size, &char_size);
1617
0
        is_whitespace = ISUNICODEWHITESPACE_(codepoint) || ISNEWLINE_(label[off]);
1618
1619
0
        if(is_whitespace) {
1620
0
            codepoint = ' ';
1621
0
            hash = md_fnv1a(hash, &codepoint, sizeof(unsigned));
1622
0
            off = md_skip_unicode_whitespace(label, off, size);
1623
0
        } else {
1624
0
            MD_UNICODE_FOLD_INFO fold_info;
1625
1626
0
            md_get_unicode_fold_info(codepoint, &fold_info);
1627
0
            hash = md_fnv1a(hash, fold_info.codepoints, fold_info.n_codepoints * sizeof(unsigned));
1628
0
            off += char_size;
1629
0
        }
1630
0
    }
1631
1632
0
    return hash;
1633
0
}
1634
1635
static OFF
1636
md_link_label_cmp_load_fold_info(const CHAR* label, OFF off, SZ size,
1637
                                 MD_UNICODE_FOLD_INFO* fold_info)
1638
0
{
1639
0
    unsigned codepoint;
1640
0
    SZ char_size;
1641
1642
0
    if(off >= size) {
1643
        /* Treat end of a link label as a whitespace. */
1644
0
        goto whitespace;
1645
0
    }
1646
1647
0
    codepoint = md_decode_unicode(label, off, size, &char_size);
1648
0
    off += char_size;
1649
0
    if(ISUNICODEWHITESPACE_(codepoint)) {
1650
        /* Treat all whitespace as equivalent */
1651
0
        goto whitespace;
1652
0
    }
1653
1654
    /* Get real folding info. */
1655
0
    md_get_unicode_fold_info(codepoint, fold_info);
1656
0
    return off;
1657
1658
0
whitespace:
1659
0
    fold_info->codepoints[0] = _T(' ');
1660
0
    fold_info->n_codepoints = 1;
1661
0
    return md_skip_unicode_whitespace(label, off, size);
1662
0
}
1663
1664
static int
1665
md_link_label_cmp(const CHAR* a_label, SZ a_size, const CHAR* b_label, SZ b_size)
1666
0
{
1667
0
    OFF a_off;
1668
0
    OFF b_off;
1669
0
    MD_UNICODE_FOLD_INFO a_fi = { { 0 }, 0 };
1670
0
    MD_UNICODE_FOLD_INFO b_fi = { { 0 }, 0 };
1671
0
    OFF a_fi_off = 0;
1672
0
    OFF b_fi_off = 0;
1673
0
    int cmp;
1674
1675
0
    a_off = md_skip_unicode_whitespace(a_label, 0, a_size);
1676
0
    b_off = md_skip_unicode_whitespace(b_label, 0, b_size);
1677
0
    while(a_off < a_size || a_fi_off < a_fi.n_codepoints ||
1678
0
          b_off < b_size || b_fi_off < b_fi.n_codepoints)
1679
0
    {
1680
        /* If needed, load fold info for next char. */
1681
0
        if(a_fi_off >= a_fi.n_codepoints) {
1682
0
            a_fi_off = 0;
1683
0
            a_off = md_link_label_cmp_load_fold_info(a_label, a_off, a_size, &a_fi);
1684
0
        }
1685
0
        if(b_fi_off >= b_fi.n_codepoints) {
1686
0
            b_fi_off = 0;
1687
0
            b_off = md_link_label_cmp_load_fold_info(b_label, b_off, b_size, &b_fi);
1688
0
        }
1689
1690
0
        cmp = b_fi.codepoints[b_fi_off] - a_fi.codepoints[a_fi_off];
1691
0
        if(cmp != 0)
1692
0
            return cmp;
1693
1694
0
        a_fi_off++;
1695
0
        b_fi_off++;
1696
0
    }
1697
1698
0
    return 0;
1699
0
}
1700
1701
typedef struct MD_REF_DEF_LIST_tag MD_REF_DEF_LIST;
1702
struct MD_REF_DEF_LIST_tag {
1703
    int n_ref_defs;
1704
    int alloc_ref_defs;
1705
    MD_REF_DEF* ref_defs[];  /* Valid items always  point into ctx->ref_defs[] */
1706
};
1707
1708
static int
1709
md_ref_def_cmp(const void* a, const void* b)
1710
0
{
1711
0
    const MD_REF_DEF* a_ref = *(const MD_REF_DEF**)a;
1712
0
    const MD_REF_DEF* b_ref = *(const MD_REF_DEF**)b;
1713
1714
0
    if(a_ref->hash < b_ref->hash)
1715
0
        return -1;
1716
0
    else if(a_ref->hash > b_ref->hash)
1717
0
        return +1;
1718
0
    else
1719
0
        return md_link_label_cmp(a_ref->label, a_ref->label_size, b_ref->label, b_ref->label_size);
1720
0
}
1721
1722
static int
1723
md_ref_def_cmp_for_sort(const void* a, const void* b)
1724
0
{
1725
0
    int cmp;
1726
1727
0
    cmp = md_ref_def_cmp(a, b);
1728
1729
    /* Ensure stability of the sorting. */
1730
0
    if(cmp == 0) {
1731
0
        const MD_REF_DEF* a_ref = *(const MD_REF_DEF**)a;
1732
0
        const MD_REF_DEF* b_ref = *(const MD_REF_DEF**)b;
1733
1734
0
        if(a_ref < b_ref)
1735
0
            cmp = -1;
1736
0
        else if(a_ref > b_ref)
1737
0
            cmp = +1;
1738
0
        else
1739
0
            cmp = 0;
1740
0
    }
1741
1742
0
    return cmp;
1743
0
}
1744
1745
static int
1746
md_build_ref_def_hashtable(MD_CTX* ctx)
1747
0
{
1748
0
    int i, j;
1749
1750
0
    if(ctx->n_ref_defs == 0)
1751
0
        return 0;
1752
1753
0
    ctx->ref_def_hashtable_size = (ctx->n_ref_defs * 5) / 4;
1754
0
    ctx->ref_def_hashtable = malloc(ctx->ref_def_hashtable_size * sizeof(void*));
1755
0
    if(ctx->ref_def_hashtable == NULL) {
1756
0
        MD_LOG("malloc() failed.");
1757
0
        goto abort;
1758
0
    }
1759
0
    memset(ctx->ref_def_hashtable, 0, ctx->ref_def_hashtable_size * sizeof(void*));
1760
1761
    /* Each member of ctx->ref_def_hashtable[] can be:
1762
     *  -- NULL,
1763
     *  -- pointer to the MD_REF_DEF in ctx->ref_defs[], or
1764
     *  -- pointer to a MD_REF_DEF_LIST, which holds multiple pointers to
1765
     *     such MD_REF_DEFs.
1766
     */
1767
0
    for(i = 0; i < ctx->n_ref_defs; i++) {
1768
0
        MD_REF_DEF* def = &ctx->ref_defs[i];
1769
0
        void* bucket;
1770
0
        MD_REF_DEF_LIST* list;
1771
1772
0
        def->hash = md_link_label_hash(def->label, def->label_size);
1773
0
        bucket = ctx->ref_def_hashtable[def->hash % ctx->ref_def_hashtable_size];
1774
1775
0
        if(bucket == NULL) {
1776
            /* The bucket is empty. Make it just point to the def. */
1777
0
            ctx->ref_def_hashtable[def->hash % ctx->ref_def_hashtable_size] = def;
1778
0
            continue;
1779
0
        }
1780
1781
0
        if(ctx->ref_defs <= (MD_REF_DEF*) bucket  &&  (MD_REF_DEF*) bucket < ctx->ref_defs + ctx->n_ref_defs) {
1782
            /* The bucket already contains one ref. def. Lets see whether it
1783
             * is the same label (ref. def. duplicate) or different one
1784
             * (hash conflict). */
1785
0
            MD_REF_DEF* old_def = (MD_REF_DEF*) bucket;
1786
1787
0
            if(md_link_label_cmp(def->label, def->label_size, old_def->label, old_def->label_size) == 0) {
1788
                /* Duplicate label: Ignore this ref. def. */
1789
0
                continue;
1790
0
            }
1791
1792
            /* Make the bucket complex, i.e. able to hold more ref. defs. */
1793
0
            list = (MD_REF_DEF_LIST*) malloc(sizeof(MD_REF_DEF_LIST) + 2 * sizeof(MD_REF_DEF*));
1794
0
            if(list == NULL) {
1795
0
                MD_LOG("malloc() failed.");
1796
0
                goto abort;
1797
0
            }
1798
0
            list->ref_defs[0] = old_def;
1799
0
            list->ref_defs[1] = def;
1800
0
            list->n_ref_defs = 2;
1801
0
            list->alloc_ref_defs = 2;
1802
0
            ctx->ref_def_hashtable[def->hash % ctx->ref_def_hashtable_size] = list;
1803
0
            continue;
1804
0
        }
1805
1806
        /* Append the def to the complex bucket list.
1807
         *
1808
         * Note in this case we ignore potential duplicates to avoid expensive
1809
         * iterating over the complex bucket. Below, we revisit all the complex
1810
         * buckets and handle it more cheaply after the complex bucket contents
1811
         * is sorted. */
1812
0
        list = (MD_REF_DEF_LIST*) bucket;
1813
0
        if(list->n_ref_defs >= list->alloc_ref_defs) {
1814
0
            int alloc_ref_defs = list->alloc_ref_defs + list->alloc_ref_defs / 2;
1815
0
            MD_REF_DEF_LIST* list_tmp = (MD_REF_DEF_LIST*) realloc(list,
1816
0
                        sizeof(MD_REF_DEF_LIST) + alloc_ref_defs * sizeof(MD_REF_DEF*));
1817
0
            if(list_tmp == NULL) {
1818
0
                MD_LOG("realloc() failed.");
1819
0
                goto abort;
1820
0
            }
1821
0
            list = list_tmp;
1822
0
            list->alloc_ref_defs = alloc_ref_defs;
1823
0
            ctx->ref_def_hashtable[def->hash % ctx->ref_def_hashtable_size] = list;
1824
0
        }
1825
1826
0
        list->ref_defs[list->n_ref_defs] = def;
1827
0
        list->n_ref_defs++;
1828
0
    }
1829
1830
    /* Sort the complex buckets so we can use bsearch() with them. */
1831
0
    for(i = 0; i < ctx->ref_def_hashtable_size; i++) {
1832
0
        void* bucket = ctx->ref_def_hashtable[i];
1833
0
        MD_REF_DEF_LIST* list;
1834
1835
0
        if(bucket == NULL)
1836
0
            continue;
1837
0
        if(ctx->ref_defs <= (MD_REF_DEF*) bucket  &&  (MD_REF_DEF*) bucket < ctx->ref_defs + ctx->n_ref_defs)
1838
0
            continue;
1839
1840
0
        list = (MD_REF_DEF_LIST*) bucket;
1841
0
        qsort(list->ref_defs, list->n_ref_defs, sizeof(MD_REF_DEF*), md_ref_def_cmp_for_sort);
1842
1843
        /* Disable all duplicates in the complex bucket by forcing all such
1844
         * records to point to the 1st such ref. def. I.e. no matter which
1845
         * record is found during the lookup, it will always point to the right
1846
         * ref. def. in ctx->ref_defs[]. */
1847
0
        for(j = 1; j < list->n_ref_defs; j++) {
1848
0
            if(md_ref_def_cmp(&list->ref_defs[j-1], &list->ref_defs[j]) == 0)
1849
0
                list->ref_defs[j] = list->ref_defs[j-1];
1850
0
        }
1851
0
    }
1852
1853
0
    return 0;
1854
1855
0
abort:
1856
0
    return -1;
1857
0
}
1858
1859
static void
1860
md_free_ref_def_hashtable(MD_CTX* ctx)
1861
0
{
1862
0
    if(ctx->ref_def_hashtable != NULL) {
1863
0
        int i;
1864
1865
0
        for(i = 0; i < ctx->ref_def_hashtable_size; i++) {
1866
0
            void* bucket = ctx->ref_def_hashtable[i];
1867
0
            if(bucket == NULL)
1868
0
                continue;
1869
0
            if(ctx->ref_defs <= (MD_REF_DEF*) bucket  &&  (MD_REF_DEF*) bucket < ctx->ref_defs + ctx->n_ref_defs)
1870
0
                continue;
1871
0
            free(bucket);
1872
0
        }
1873
1874
0
        free(ctx->ref_def_hashtable);
1875
0
    }
1876
0
}
1877
1878
static const MD_REF_DEF*
1879
md_lookup_ref_def(MD_CTX* ctx, const CHAR* label, SZ label_size)
1880
0
{
1881
0
    unsigned hash;
1882
0
    void* bucket;
1883
1884
0
    if(ctx->ref_def_hashtable_size == 0)
1885
0
        return NULL;
1886
1887
0
    hash = md_link_label_hash(label, label_size);
1888
0
    bucket = ctx->ref_def_hashtable[hash % ctx->ref_def_hashtable_size];
1889
1890
0
    if(bucket == NULL) {
1891
0
        return NULL;
1892
0
    } else if(ctx->ref_defs <= (MD_REF_DEF*) bucket  &&  (MD_REF_DEF*) bucket < ctx->ref_defs + ctx->n_ref_defs) {
1893
0
        const MD_REF_DEF* def = (MD_REF_DEF*) bucket;
1894
1895
0
        if(md_link_label_cmp(def->label, def->label_size, label, label_size) == 0)
1896
0
            return def;
1897
0
        else
1898
0
            return NULL;
1899
0
    } else {
1900
0
        MD_REF_DEF_LIST* list = (MD_REF_DEF_LIST*) bucket;
1901
0
        MD_REF_DEF key_buf;
1902
0
        const MD_REF_DEF* key = &key_buf;
1903
0
        const MD_REF_DEF** ret;
1904
1905
0
        key_buf.label = (CHAR*) label;
1906
0
        key_buf.label_size = label_size;
1907
0
        key_buf.hash = md_link_label_hash(key_buf.label, key_buf.label_size);
1908
1909
0
        ret = (const MD_REF_DEF**) bsearch(&key, list->ref_defs,
1910
0
                    list->n_ref_defs, sizeof(MD_REF_DEF*), md_ref_def_cmp);
1911
0
        if(ret != NULL)
1912
0
            return *ret;
1913
0
        else
1914
0
            return NULL;
1915
0
    }
1916
0
}
1917
1918
1919
/***************************
1920
 ***  Recognizing Links  ***
1921
 ***************************/
1922
1923
/* Note this code is partially shared between processing inlines and blocks
1924
 * as reference definitions and links share some helper parser functions.
1925
 */
1926
1927
typedef struct MD_LINK_ATTR_tag MD_LINK_ATTR;
1928
struct MD_LINK_ATTR_tag {
1929
    OFF dest_beg;
1930
    OFF dest_end;
1931
1932
    CHAR* title;
1933
    SZ title_size;
1934
    int title_needs_free;
1935
};
1936
1937
1938
static int
1939
md_is_link_label(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg,
1940
                 OFF* p_end, MD_SIZE* p_beg_line_index, MD_SIZE* p_end_line_index,
1941
                 OFF* p_contents_beg, OFF* p_contents_end)
1942
0
{
1943
0
    OFF off = beg;
1944
0
    OFF contents_beg = 0;
1945
0
    OFF contents_end = 0;
1946
0
    MD_SIZE line_index = 0;
1947
0
    int len = 0;
1948
1949
0
    *p_beg_line_index = 0;
1950
1951
0
    if(CH(off) != _T('['))
1952
0
        return FALSE;
1953
0
    off++;
1954
1955
0
    while(1) {
1956
0
        OFF line_end = lines[line_index].end;
1957
1958
0
        while(off < line_end) {
1959
0
            if(CH(off) == _T('\\')  &&  off+1 < ctx->size  &&  (ISPUNCT(off+1) || ISNEWLINE(off+1))) {
1960
0
                if(contents_end == 0) {
1961
0
                    contents_beg = off;
1962
0
                    *p_beg_line_index = line_index;
1963
0
                }
1964
0
                contents_end = off + 2;
1965
0
                off += 2;
1966
0
            } else if(CH(off) == _T('[')) {
1967
0
                return FALSE;
1968
0
            } else if(CH(off) == _T(']')) {
1969
0
                if(contents_beg < contents_end) {
1970
                    /* Success. */
1971
0
                    *p_contents_beg = contents_beg;
1972
0
                    *p_contents_end = contents_end;
1973
0
                    *p_end = off+1;
1974
0
                    *p_end_line_index = line_index;
1975
0
                    return TRUE;
1976
0
                } else {
1977
                    /* Link label must have some non-whitespace contents. */
1978
0
                    return FALSE;
1979
0
                }
1980
0
            } else {
1981
0
                unsigned codepoint;
1982
0
                SZ char_size;
1983
1984
0
                codepoint = md_decode_unicode(ctx->text, off, ctx->size, &char_size);
1985
0
                if(!ISUNICODEWHITESPACE_(codepoint)) {
1986
0
                    if(contents_end == 0) {
1987
0
                        contents_beg = off;
1988
0
                        *p_beg_line_index = line_index;
1989
0
                    }
1990
0
                    contents_end = off + char_size;
1991
0
                }
1992
1993
0
                off += char_size;
1994
0
            }
1995
1996
0
            len++;
1997
0
            if(len > 999)
1998
0
                return FALSE;
1999
0
        }
2000
2001
0
        line_index++;
2002
0
        len++;
2003
0
        if(line_index < n_lines)
2004
0
            off = lines[line_index].beg;
2005
0
        else
2006
0
            break;
2007
0
    }
2008
2009
0
    return FALSE;
2010
0
}
2011
2012
static int
2013
md_is_link_destination_A(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end,
2014
                         OFF* p_contents_beg, OFF* p_contents_end)
2015
0
{
2016
0
    OFF off = beg;
2017
2018
0
    if(off >= max_end  ||  CH(off) != _T('<'))
2019
0
        return FALSE;
2020
0
    off++;
2021
2022
0
    while(off < max_end) {
2023
0
        if(CH(off) == _T('\\')  &&  off+1 < max_end  &&  ISPUNCT(off+1)) {
2024
0
            off += 2;
2025
0
            continue;
2026
0
        }
2027
2028
0
        if(ISNEWLINE(off)  ||  CH(off) == _T('<'))
2029
0
            return FALSE;
2030
2031
0
        if(CH(off) == _T('>')) {
2032
            /* Success. */
2033
0
            *p_contents_beg = beg+1;
2034
0
            *p_contents_end = off;
2035
0
            *p_end = off+1;
2036
0
            return TRUE;
2037
0
        }
2038
2039
0
        off++;
2040
0
    }
2041
2042
0
    return FALSE;
2043
0
}
2044
2045
static int
2046
md_is_link_destination_B(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end,
2047
                         OFF* p_contents_beg, OFF* p_contents_end)
2048
0
{
2049
0
    OFF off = beg;
2050
0
    int parenthesis_level = 0;
2051
2052
0
    while(off < max_end) {
2053
0
        if(CH(off) == _T('\\')  &&  off+1 < max_end  &&  ISPUNCT(off+1)) {
2054
0
            off += 2;
2055
0
            continue;
2056
0
        }
2057
2058
0
        if(ISWHITESPACE(off) || ISCNTRL(off))
2059
0
            break;
2060
2061
        /* Link destination may include balanced pairs of unescaped '(' ')'.
2062
         * Note we limit the maximal nesting level by 32 to protect us from
2063
         * https://github.com/jgm/cmark/issues/214 */
2064
0
        if(CH(off) == _T('(')) {
2065
0
            parenthesis_level++;
2066
0
            if(parenthesis_level > 32)
2067
0
                return FALSE;
2068
0
        } else if(CH(off) == _T(')')) {
2069
0
            if(parenthesis_level == 0)
2070
0
                break;
2071
0
            parenthesis_level--;
2072
0
        }
2073
2074
0
        off++;
2075
0
    }
2076
2077
0
    if(parenthesis_level != 0  ||  off == beg)
2078
0
        return FALSE;
2079
2080
    /* Success. */
2081
0
    *p_contents_beg = beg;
2082
0
    *p_contents_end = off;
2083
0
    *p_end = off;
2084
0
    return TRUE;
2085
0
}
2086
2087
static inline int
2088
md_is_link_destination(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end,
2089
                       OFF* p_contents_beg, OFF* p_contents_end)
2090
0
{
2091
0
    if(CH(beg) == _T('<'))
2092
0
        return md_is_link_destination_A(ctx, beg, max_end, p_end, p_contents_beg, p_contents_end);
2093
0
    else
2094
0
        return md_is_link_destination_B(ctx, beg, max_end, p_end, p_contents_beg, p_contents_end);
2095
0
}
2096
2097
static int
2098
md_is_link_title(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg,
2099
                 OFF* p_end, MD_SIZE* p_beg_line_index, MD_SIZE* p_end_line_index,
2100
                 OFF* p_contents_beg, OFF* p_contents_end)
2101
0
{
2102
0
    OFF off = beg;
2103
0
    CHAR closer_char;
2104
0
    MD_SIZE line_index = 0;
2105
2106
    /* White space with up to one line break. */
2107
0
    while(off < lines[line_index].end  &&  ISWHITESPACE(off))
2108
0
        off++;
2109
0
    if(off >= lines[line_index].end) {
2110
0
        line_index++;
2111
0
        if(line_index >= n_lines)
2112
0
            return FALSE;
2113
0
        off = lines[line_index].beg;
2114
0
    }
2115
0
    if(off == beg)
2116
0
        return FALSE;
2117
2118
0
    *p_beg_line_index = line_index;
2119
2120
    /* First char determines how to detect end of it. */
2121
0
    switch(CH(off)) {
2122
0
        case _T('"'):   closer_char = _T('"'); break;
2123
0
        case _T('\''):  closer_char = _T('\''); break;
2124
0
        case _T('('):   closer_char = _T(')'); break;
2125
0
        default:        return FALSE;
2126
0
    }
2127
0
    off++;
2128
2129
0
    *p_contents_beg = off;
2130
2131
0
    while(line_index < n_lines) {
2132
0
        OFF line_end = lines[line_index].end;
2133
2134
0
        while(off < line_end) {
2135
0
            if(CH(off) == _T('\\')  &&  off+1 < ctx->size  &&  (ISPUNCT(off+1) || ISNEWLINE(off+1))) {
2136
0
                off++;
2137
0
            } else if(CH(off) == closer_char) {
2138
                /* Success. */
2139
0
                *p_contents_end = off;
2140
0
                *p_end = off+1;
2141
0
                *p_end_line_index = line_index;
2142
0
                return TRUE;
2143
0
            } else if(closer_char == _T(')')  &&  CH(off) == _T('(')) {
2144
                /* ()-style title cannot contain (unescaped '(')) */
2145
0
                return FALSE;
2146
0
            }
2147
2148
0
            off++;
2149
0
        }
2150
2151
0
        line_index++;
2152
0
    }
2153
2154
0
    return FALSE;
2155
0
}
2156
2157
/* Returns 0 if it is not a reference definition.
2158
 *
2159
 * Returns N > 0 if it is a reference definition. N then corresponds to the
2160
 * number of lines forming it). In this case the definition is stored for
2161
 * resolving any links referring to it.
2162
 *
2163
 * Returns -1 in case of an error (out of memory).
2164
 */
2165
static int
2166
md_is_link_reference_definition(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines)
2167
0
{
2168
0
    OFF label_contents_beg;
2169
0
    OFF label_contents_end;
2170
0
    MD_SIZE label_contents_line_index;
2171
0
    int label_is_multiline = FALSE;
2172
0
    OFF dest_contents_beg;
2173
0
    OFF dest_contents_end;
2174
0
    OFF title_contents_beg;
2175
0
    OFF title_contents_end;
2176
0
    MD_SIZE title_contents_line_index;
2177
0
    int title_is_multiline = FALSE;
2178
0
    OFF off;
2179
0
    MD_SIZE line_index = 0;
2180
0
    MD_SIZE tmp_line_index;
2181
0
    MD_REF_DEF* def = NULL;
2182
0
    int ret = 0;
2183
2184
    /* Link label. */
2185
0
    if(!md_is_link_label(ctx, lines, n_lines, lines[0].beg,
2186
0
                &off, &label_contents_line_index, &line_index,
2187
0
                &label_contents_beg, &label_contents_end))
2188
0
        return FALSE;
2189
0
    label_is_multiline = (label_contents_line_index != line_index);
2190
2191
    /* Colon. */
2192
0
    if(off >= lines[line_index].end  ||  CH(off) != _T(':'))
2193
0
        return FALSE;
2194
0
    off++;
2195
2196
    /* Optional white space with up to one line break. */
2197
0
    while(off < lines[line_index].end  &&  ISWHITESPACE(off))
2198
0
        off++;
2199
0
    if(off >= lines[line_index].end) {
2200
0
        line_index++;
2201
0
        if(line_index >= n_lines)
2202
0
            return FALSE;
2203
0
        off = lines[line_index].beg;
2204
0
    }
2205
2206
    /* Link destination. */
2207
0
    if(!md_is_link_destination(ctx, off, lines[line_index].end,
2208
0
                &off, &dest_contents_beg, &dest_contents_end))
2209
0
        return FALSE;
2210
2211
    /* (Optional) title. Note we interpret it as an title only if nothing
2212
     * more follows on its last line. */
2213
0
    if(md_is_link_title(ctx, lines + line_index, n_lines - line_index, off,
2214
0
                &off, &title_contents_line_index, &tmp_line_index,
2215
0
                &title_contents_beg, &title_contents_end)
2216
0
        &&  off >= lines[line_index + tmp_line_index].end)
2217
0
    {
2218
0
        title_is_multiline = (tmp_line_index != title_contents_line_index);
2219
0
        title_contents_line_index += line_index;
2220
0
        line_index += tmp_line_index;
2221
0
    } else {
2222
        /* Not a title. */
2223
0
        title_is_multiline = FALSE;
2224
0
        title_contents_beg = off;
2225
0
        title_contents_end = off;
2226
0
        title_contents_line_index = 0;
2227
0
    }
2228
2229
    /* Nothing more can follow on the last line. */
2230
0
    if(off < lines[line_index].end)
2231
0
        return FALSE;
2232
2233
    /* So, it _is_ a reference definition. Remember it. */
2234
0
    if(ctx->n_ref_defs >= ctx->alloc_ref_defs) {
2235
0
        MD_REF_DEF* new_defs;
2236
2237
0
        ctx->alloc_ref_defs = (ctx->alloc_ref_defs > 0
2238
0
                ? ctx->alloc_ref_defs + ctx->alloc_ref_defs / 2
2239
0
                : 16);
2240
0
        new_defs = (MD_REF_DEF*) realloc(ctx->ref_defs, ctx->alloc_ref_defs * sizeof(MD_REF_DEF));
2241
0
        if(new_defs == NULL) {
2242
0
            MD_LOG("realloc() failed.");
2243
0
            goto abort;
2244
0
        }
2245
2246
0
        ctx->ref_defs = new_defs;
2247
0
    }
2248
0
    def = &ctx->ref_defs[ctx->n_ref_defs];
2249
0
    memset(def, 0, sizeof(MD_REF_DEF));
2250
2251
0
    if(label_is_multiline) {
2252
0
        MD_CHECK(md_merge_lines_alloc(ctx, label_contents_beg, label_contents_end,
2253
0
                    lines + label_contents_line_index, n_lines - label_contents_line_index,
2254
0
                    _T(' '), &def->label, &def->label_size));
2255
0
        def->label_needs_free = TRUE;
2256
0
    } else {
2257
0
        def->label = (CHAR*) STR(label_contents_beg);
2258
0
        def->label_size = label_contents_end - label_contents_beg;
2259
0
    }
2260
2261
0
    if(title_is_multiline) {
2262
0
        MD_CHECK(md_merge_lines_alloc(ctx, title_contents_beg, title_contents_end,
2263
0
                    lines + title_contents_line_index, n_lines - title_contents_line_index,
2264
0
                    _T('\n'), &def->title, &def->title_size));
2265
0
        def->title_needs_free = TRUE;
2266
0
    } else {
2267
0
        def->title = (CHAR*) STR(title_contents_beg);
2268
0
        def->title_size = title_contents_end - title_contents_beg;
2269
0
    }
2270
2271
0
    def->dest_beg = dest_contents_beg;
2272
0
    def->dest_end = dest_contents_end;
2273
2274
    /* Success. */
2275
0
    ctx->n_ref_defs++;
2276
0
    return line_index + 1;
2277
2278
0
abort:
2279
    /* Failure. */
2280
0
    if(def != NULL  &&  def->label_needs_free)
2281
0
        free(def->label);
2282
0
    if(def != NULL  &&  def->title_needs_free)
2283
0
        free(def->title);
2284
0
    return ret;
2285
0
}
2286
2287
static int
2288
md_is_link_reference(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines,
2289
                     OFF beg, OFF end, MD_LINK_ATTR* attr)
2290
0
{
2291
0
    const MD_REF_DEF* def;
2292
0
    const MD_LINE* beg_line;
2293
0
    int is_multiline;
2294
0
    CHAR* label;
2295
0
    SZ label_size;
2296
0
    int ret = FALSE;
2297
2298
0
    MD_ASSERT(CH(beg) == _T('[') || CH(beg) == _T('!'));
2299
0
    MD_ASSERT(CH(end-1) == _T(']'));
2300
2301
0
    if(ctx->max_ref_def_output == 0)
2302
0
        return FALSE;
2303
2304
0
    beg += (CH(beg) == _T('!') ? 2 : 1);
2305
0
    end--;
2306
2307
    /* Find lines corresponding to the beg and end positions. */
2308
0
    beg_line = md_lookup_line(beg, lines, n_lines, NULL);
2309
0
    is_multiline = (end > beg_line->end);
2310
2311
0
    if(is_multiline) {
2312
0
        MD_CHECK(md_merge_lines_alloc(ctx, beg, end, beg_line,
2313
0
                 (int)(n_lines - (beg_line - lines)), _T(' '), &label, &label_size));
2314
0
    } else {
2315
0
        label = (CHAR*) STR(beg);
2316
0
        label_size = end - beg;
2317
0
    }
2318
2319
0
    def = md_lookup_ref_def(ctx, label, label_size);
2320
0
    if(def != NULL) {
2321
0
        attr->dest_beg = def->dest_beg;
2322
0
        attr->dest_end = def->dest_end;
2323
0
        attr->title = def->title;
2324
0
        attr->title_size = def->title_size;
2325
0
        attr->title_needs_free = FALSE;
2326
0
    }
2327
2328
0
    if(is_multiline)
2329
0
        free(label);
2330
2331
0
    if(def != NULL) {
2332
        /* See https://github.com/mity/md4c/issues/238 */
2333
0
        MD_SIZE output_size_estimation = def->label_size + def->title_size + def->dest_end - def->dest_beg;
2334
0
        if(output_size_estimation < ctx->max_ref_def_output) {
2335
0
            ctx->max_ref_def_output -= output_size_estimation;
2336
0
            ret = TRUE;
2337
0
        } else {
2338
0
            MD_LOG("Too many link reference definition instantiations.");
2339
0
            ctx->max_ref_def_output = 0;
2340
0
        }
2341
0
    }
2342
2343
0
abort:
2344
0
    return ret;
2345
0
}
2346
2347
static int
2348
md_is_inline_link_spec(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines,
2349
                       OFF beg, OFF* p_end, MD_LINK_ATTR* attr)
2350
0
{
2351
0
    MD_SIZE line_index = 0;
2352
0
    MD_SIZE tmp_line_index;
2353
0
    OFF title_contents_beg;
2354
0
    OFF title_contents_end;
2355
0
    MD_SIZE title_contents_line_index;
2356
0
    int title_is_multiline;
2357
0
    OFF off = beg;
2358
0
    int ret = FALSE;
2359
2360
0
    md_lookup_line(off, lines, n_lines, &line_index);
2361
2362
0
    MD_ASSERT(CH(off) == _T('('));
2363
0
    off++;
2364
2365
    /* Optional white space with up to one line break. */
2366
0
    while(off < lines[line_index].end  &&  ISWHITESPACE(off))
2367
0
        off++;
2368
0
    if(off >= lines[line_index].end  &&  (off >= ctx->size  ||  ISNEWLINE(off))) {
2369
0
        line_index++;
2370
0
        if(line_index >= n_lines)
2371
0
            return FALSE;
2372
0
        off = lines[line_index].beg;
2373
0
    }
2374
2375
    /* Link destination may be omitted, but only when not also having a title. */
2376
0
    if(off < ctx->size  &&  CH(off) == _T(')')) {
2377
0
        attr->dest_beg = off;
2378
0
        attr->dest_end = off;
2379
0
        attr->title = NULL;
2380
0
        attr->title_size = 0;
2381
0
        attr->title_needs_free = FALSE;
2382
0
        off++;
2383
0
        *p_end = off;
2384
0
        return TRUE;
2385
0
    }
2386
2387
    /* Link destination. */
2388
0
    if(!md_is_link_destination(ctx, off, lines[line_index].end,
2389
0
                        &off, &attr->dest_beg, &attr->dest_end))
2390
0
        return FALSE;
2391
2392
    /* (Optional) title. */
2393
0
    if(md_is_link_title(ctx, lines + line_index, n_lines - line_index, off,
2394
0
                &off, &title_contents_line_index, &tmp_line_index,
2395
0
                &title_contents_beg, &title_contents_end))
2396
0
    {
2397
0
        title_is_multiline = (tmp_line_index != title_contents_line_index);
2398
0
        title_contents_line_index += line_index;
2399
0
        line_index += tmp_line_index;
2400
0
    } else {
2401
        /* Not a title. */
2402
0
        title_is_multiline = FALSE;
2403
0
        title_contents_beg = off;
2404
0
        title_contents_end = off;
2405
0
        title_contents_line_index = 0;
2406
0
    }
2407
2408
    /* Optional whitespace followed with final ')'. */
2409
0
    while(off < lines[line_index].end  &&  ISWHITESPACE(off))
2410
0
        off++;
2411
0
    if(off >= lines[line_index].end) {
2412
0
        line_index++;
2413
0
        if(line_index >= n_lines)
2414
0
            return FALSE;
2415
0
        off = lines[line_index].beg;
2416
0
    }
2417
0
    if(CH(off) != _T(')'))
2418
0
        goto abort;
2419
0
    off++;
2420
2421
0
    if(title_contents_beg >= title_contents_end) {
2422
0
        attr->title = NULL;
2423
0
        attr->title_size = 0;
2424
0
        attr->title_needs_free = FALSE;
2425
0
    } else if(!title_is_multiline) {
2426
0
        attr->title = (CHAR*) STR(title_contents_beg);
2427
0
        attr->title_size = title_contents_end - title_contents_beg;
2428
0
        attr->title_needs_free = FALSE;
2429
0
    } else {
2430
0
        MD_CHECK(md_merge_lines_alloc(ctx, title_contents_beg, title_contents_end,
2431
0
                    lines + title_contents_line_index, n_lines - title_contents_line_index,
2432
0
                    _T('\n'), &attr->title, &attr->title_size));
2433
0
        attr->title_needs_free = TRUE;
2434
0
    }
2435
2436
0
    *p_end = off;
2437
0
    ret = TRUE;
2438
2439
0
abort:
2440
0
    return ret;
2441
0
}
2442
2443
static void
2444
md_free_ref_defs(MD_CTX* ctx)
2445
0
{
2446
0
    int i;
2447
2448
0
    for(i = 0; i < ctx->n_ref_defs; i++) {
2449
0
        MD_REF_DEF* def = &ctx->ref_defs[i];
2450
2451
0
        if(def->label_needs_free)
2452
0
            free(def->label);
2453
0
        if(def->title_needs_free)
2454
0
            free(def->title);
2455
0
    }
2456
2457
0
    free(ctx->ref_defs);
2458
0
}
2459
2460
2461
/******************************************
2462
 ***  Processing Inlines (a.k.a Spans)  ***
2463
 ******************************************/
2464
2465
/* We process inlines in few phases:
2466
 *
2467
 * (1) We go through the block text and collect all significant characters
2468
 *     which may start/end a span or some other significant position into
2469
 *     ctx->marks[]. Core of this is what md_collect_marks() does.
2470
 *
2471
 *     We also do some very brief preliminary context-less analysis, whether
2472
 *     it might be opener or closer (e.g. of an emphasis span).
2473
 *
2474
 *     This speeds the other steps as we do not need to re-iterate over all
2475
 *     characters anymore.
2476
 *
2477
 * (2) We analyze each potential mark types, in order by their precedence.
2478
 *
2479
 *     In each md_analyze_XXX() function, we re-iterate list of the marks,
2480
 *     skipping already resolved regions (in preceding precedences) and try to
2481
 *     resolve them.
2482
 *
2483
 * (2.1) For trivial marks, which are single (e.g. HTML entity), we just mark
2484
 *       them as resolved.
2485
 *
2486
 * (2.2) For range-type marks, we analyze whether the mark could be closer
2487
 *       and, if yes, whether there is some preceding opener it could satisfy.
2488
 *
2489
 *       If not we check whether it could be really an opener and if yes, we
2490
 *       remember it so subsequent closers may resolve it.
2491
 *
2492
 * (3) Finally, when all marks were analyzed, we render the block contents
2493
 *     by calling MD_RENDERER::text() callback, interrupting by ::enter_span()
2494
 *     or ::close_span() whenever we reach a resolved mark.
2495
 */
2496
2497
2498
/* The mark structure.
2499
 *
2500
 * '\\': Maybe escape sequence.
2501
 * '\0': NULL char.
2502
 *  '*': Maybe (strong) emphasis start/end.
2503
 *  '_': Maybe (strong) emphasis start/end.
2504
 *  '~': Maybe strikethrough start/end (needs MD_FLAG_STRIKETHROUGH).
2505
 *  '`': Maybe code span start/end.
2506
 *  '&': Maybe start of entity.
2507
 *  ';': Maybe end of entity.
2508
 *  '<': Maybe start of raw HTML or autolink.
2509
 *  '>': Maybe end of raw HTML or autolink.
2510
 *  '[': Maybe start of link label or link text.
2511
 *  '!': Equivalent of '[' for image.
2512
 *  ']': Maybe end of link label or link text.
2513
 *  '@': Maybe permissive e-mail auto-link (needs MD_FLAG_PERMISSIVEEMAILAUTOLINKS).
2514
 *  ':': Maybe permissive URL auto-link (needs MD_FLAG_PERMISSIVEURLAUTOLINKS).
2515
 *  '.': Maybe permissive WWW auto-link (needs MD_FLAG_PERMISSIVEWWWAUTOLINKS).
2516
 *  'D': Dummy mark, it reserves a space for splitting a previous mark
2517
 *       (e.g. emphasis) or to make more space for storing some special data
2518
 *       related to the preceding mark (e.g. link).
2519
 *
2520
 * Note that not all instances of these chars in the text imply creation of the
2521
 * structure. Only those which have (or may have, after we see more context)
2522
 * the special meaning.
2523
 *
2524
 * (Keep this struct as small as possible to fit as much of them into CPU
2525
 * cache line.)
2526
 */
2527
struct MD_MARK_tag {
2528
    union {
2529
        struct {
2530
            OFF beg;
2531
            OFF end;
2532
        };
2533
        void* pointer; // Dummy marks can sometimes store a pointer
2534
    };
2535
2536
    /* For unresolved openers, 'next' may be used to form a stack of
2537
     * unresolved open openers.
2538
     *
2539
     * When resolved with MD_MARK_OPENER/CLOSER flag, next/prev is index of the
2540
     * respective closer/opener.
2541
     */
2542
    int prev;
2543
    int next;
2544
    CHAR ch;
2545
    unsigned char flags;
2546
};
2547
2548
/* Mark flags (these apply to ALL mark types). */
2549
0
#define MD_MARK_POTENTIAL_OPENER            0x01  /* Maybe opener. */
2550
0
#define MD_MARK_POTENTIAL_CLOSER            0x02  /* Maybe closer. */
2551
0
#define MD_MARK_OPENER                      0x04  /* Definitely opener. */
2552
0
#define MD_MARK_CLOSER                      0x08  /* Definitely closer. */
2553
0
#define MD_MARK_RESOLVED                    0x10  /* Resolved in any definite way. */
2554
2555
/* Mark flags specific for various mark types (so they can share bits). */
2556
0
#define MD_MARK_EMPH_OC                     0x20  /* Opener/closer mixed candidate. Helper for the "rule of 3". */
2557
0
#define MD_MARK_EMPH_MOD3_0                 0x40
2558
0
#define MD_MARK_EMPH_MOD3_1                 0x80
2559
0
#define MD_MARK_EMPH_MOD3_2                 (0x40 | 0x80)
2560
0
#define MD_MARK_EMPH_MOD3_MASK              (0x40 | 0x80)
2561
0
#define MD_MARK_AUTOLINK                    0x20  /* Distinguisher for '<', '>'. */
2562
0
#define MD_MARK_AUTOLINK_MISSING_MAILTO     0x40
2563
0
#define MD_MARK_VALIDPERMISSIVEAUTOLINK     0x20  /* For permissive autolinks. */
2564
0
#define MD_MARK_HASNESTEDBRACKETS           0x20  /* For '[' to rule out invalid link labels early */
2565
2566
static MD_MARKSTACK*
2567
md_emph_stack(MD_CTX* ctx, MD_CHAR ch, unsigned flags)
2568
0
{
2569
0
    MD_MARKSTACK* stack;
2570
2571
0
    switch(ch) {
2572
0
        case '*':   stack = &ASTERISK_OPENERS_oo_mod3_0; break;
2573
0
        case '_':   stack = &UNDERSCORE_OPENERS_oo_mod3_0; break;
2574
0
        default:    MD_UNREACHABLE();
2575
0
    }
2576
2577
0
    if(flags & MD_MARK_EMPH_OC)
2578
0
        stack += 3;
2579
2580
0
    switch(flags & MD_MARK_EMPH_MOD3_MASK) {
2581
0
        case MD_MARK_EMPH_MOD3_0:   stack += 0; break;
2582
0
        case MD_MARK_EMPH_MOD3_1:   stack += 1; break;
2583
0
        case MD_MARK_EMPH_MOD3_2:   stack += 2; break;
2584
0
        default:                    MD_UNREACHABLE();
2585
0
    }
2586
2587
0
    return stack;
2588
0
}
2589
2590
static MD_MARKSTACK*
2591
md_opener_stack(MD_CTX* ctx, int mark_index)
2592
0
{
2593
0
    MD_MARK* mark = &ctx->marks[mark_index];
2594
2595
0
    switch(mark->ch) {
2596
0
        case _T('*'):
2597
0
        case _T('_'):   return md_emph_stack(ctx, mark->ch, mark->flags);
2598
2599
0
        case _T('~'):   return (mark->end - mark->beg == 1) ? &TILDE_OPENERS_1 : &TILDE_OPENERS_2;
2600
2601
0
        case _T('!'):
2602
0
        case _T('['):   return &BRACKET_OPENERS;
2603
2604
0
        default:        MD_UNREACHABLE();
2605
0
    }
2606
0
}
2607
2608
static MD_MARK*
2609
md_add_mark(MD_CTX* ctx)
2610
0
{
2611
0
    if(ctx->n_marks >= ctx->alloc_marks) {
2612
0
        MD_MARK* new_marks;
2613
2614
0
        ctx->alloc_marks = (ctx->alloc_marks > 0
2615
0
                ? ctx->alloc_marks + ctx->alloc_marks / 2
2616
0
                : 64);
2617
0
        new_marks = realloc(ctx->marks, ctx->alloc_marks * sizeof(MD_MARK));
2618
0
        if(new_marks == NULL) {
2619
0
            MD_LOG("realloc() failed.");
2620
0
            return NULL;
2621
0
        }
2622
2623
0
        ctx->marks = new_marks;
2624
0
    }
2625
2626
0
    return &ctx->marks[ctx->n_marks++];
2627
0
}
2628
2629
#define ADD_MARK_()                                                     \
2630
0
        do {                                                            \
2631
0
            mark = md_add_mark(ctx);                                    \
2632
0
            if(mark == NULL) {                                          \
2633
0
                ret = -1;                                               \
2634
0
                goto abort;                                             \
2635
0
            }                                                           \
2636
0
        } while(0)
2637
2638
#define ADD_MARK(ch_, beg_, end_, flags_)                               \
2639
0
        do {                                                            \
2640
0
            ADD_MARK_();                                                \
2641
0
            mark->beg = (beg_);                                         \
2642
0
            mark->end = (end_);                                         \
2643
0
            mark->prev = -1;                                            \
2644
0
            mark->next = -1;                                            \
2645
0
            mark->ch = (char)(ch_);                                     \
2646
0
            mark->flags = (flags_);                                     \
2647
0
        } while(0)
2648
2649
2650
static inline void
2651
md_mark_stack_push(MD_CTX* ctx, MD_MARKSTACK* stack, int mark_index)
2652
0
{
2653
0
    ctx->marks[mark_index].next = stack->top;
2654
0
    stack->top = mark_index;
2655
0
}
2656
2657
static inline int
2658
md_mark_stack_pop(MD_CTX* ctx, MD_MARKSTACK* stack)
2659
0
{
2660
0
    int top = stack->top;
2661
0
    if(top >= 0)
2662
0
        stack->top = ctx->marks[top].next;
2663
0
    return top;
2664
0
}
2665
2666
/* Sometimes, we need to store a pointer into the mark. It can only happen
2667
 * for dummy marks. */
2668
static inline void
2669
md_mark_store_ptr(MD_CTX* ctx, int mark_index, void* ptr)
2670
0
{
2671
0
    MD_ASSERT(ctx->marks[mark_index].ch == 'D');
2672
0
    ctx->marks[mark_index].pointer = ptr;
2673
0
}
2674
2675
static inline void*
2676
md_mark_get_ptr(MD_CTX* ctx, int mark_index)
2677
0
{
2678
0
    MD_ASSERT(ctx->marks[mark_index].ch == 'D');
2679
0
    return ctx->marks[mark_index].pointer;
2680
0
}
2681
2682
static inline void
2683
md_resolve_range(MD_CTX* ctx, int opener_index, int closer_index)
2684
0
{
2685
0
    MD_MARK* opener = &ctx->marks[opener_index];
2686
0
    MD_MARK* closer = &ctx->marks[closer_index];
2687
2688
    /* Interconnect opener and closer and mark both as resolved. */
2689
0
    opener->next = closer_index;
2690
0
    closer->prev = opener_index;
2691
2692
0
    opener->flags |= MD_MARK_OPENER | MD_MARK_RESOLVED;
2693
0
    closer->flags |= MD_MARK_CLOSER | MD_MARK_RESOLVED;
2694
0
}
2695
2696
/* Pop all opener records in the activated chains after the given mark.
2697
 * This makes sure, we have no crossing ranges. */
2698
static void
2699
md_pop_openers(MD_CTX* ctx, int opener_index)
2700
0
{
2701
0
    int i;
2702
2703
0
    for(i = 0; i < (int) SIZEOF_ARRAY(ctx->opener_stacks); i++) {
2704
0
        MD_MARKSTACK* stack = &ctx->opener_stacks[i];
2705
0
        while(stack->top >= opener_index)
2706
0
            md_mark_stack_pop(ctx, stack);
2707
0
    }
2708
0
}
2709
2710
static void
2711
md_disable_marks(MD_CTX* ctx, int mark_index0, int mark_index1)
2712
0
{
2713
0
    int i;
2714
2715
0
    for(i = mark_index0; i < mark_index1; i++) {
2716
0
        ctx->marks[i].ch = 'D';
2717
0
        ctx->marks[i].flags &= ~MD_MARK_RESOLVED;
2718
0
    }
2719
0
}
2720
2721
static void
2722
md_build_mark_char_map(MD_CTX* ctx)
2723
0
{
2724
0
    memset(ctx->mark_char_map, 0, sizeof(ctx->mark_char_map));
2725
2726
0
    ctx->mark_char_map['\\'] = 1;
2727
0
    ctx->mark_char_map['*'] = 1;
2728
0
    ctx->mark_char_map['_'] = 1;
2729
0
    ctx->mark_char_map['`'] = 1;
2730
0
    ctx->mark_char_map['&'] = 1;
2731
0
    ctx->mark_char_map[';'] = 1;
2732
0
    ctx->mark_char_map['<'] = 1;
2733
0
    ctx->mark_char_map['>'] = 1;
2734
0
    ctx->mark_char_map['['] = 1;
2735
0
    ctx->mark_char_map['!'] = 1;
2736
0
    ctx->mark_char_map[']'] = 1;
2737
0
    ctx->mark_char_map['\0'] = 1;
2738
2739
0
    if(ctx->parser.flags & MD_FLAG_STRIKETHROUGH)
2740
0
        ctx->mark_char_map['~'] = 1;
2741
2742
0
    if(ctx->parser.flags & MD_FLAG_LATEXMATHSPANS)
2743
0
        ctx->mark_char_map['$'] = 1;
2744
2745
0
    if(ctx->parser.flags & MD_FLAG_PERMISSIVEEMAILAUTOLINKS)
2746
0
        ctx->mark_char_map['@'] = 1;
2747
2748
0
    if(ctx->parser.flags & MD_FLAG_PERMISSIVEURLAUTOLINKS)
2749
0
        ctx->mark_char_map[':'] = 1;
2750
2751
0
    if(ctx->parser.flags & MD_FLAG_PERMISSIVEWWWAUTOLINKS)
2752
0
        ctx->mark_char_map['.'] = 1;
2753
2754
0
    if((ctx->parser.flags & MD_FLAG_TABLES) || (ctx->parser.flags & MD_FLAG_WIKILINKS))
2755
0
        ctx->mark_char_map['|'] = 1;
2756
2757
0
    if(ctx->parser.flags & MD_FLAG_COLLAPSEWHITESPACE) {
2758
0
        int i;
2759
2760
0
        for(i = 0; i < (int) sizeof(ctx->mark_char_map); i++) {
2761
0
            if(ISWHITESPACE_(i))
2762
0
                ctx->mark_char_map[i] = 1;
2763
0
        }
2764
0
    }
2765
0
}
2766
2767
static int
2768
md_is_code_span(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, OFF beg,
2769
                MD_MARK* opener, MD_MARK* closer,
2770
                OFF last_potential_closers[CODESPAN_MARK_MAXLEN],
2771
                int* p_reached_paragraph_end)
2772
0
{
2773
0
    OFF opener_beg = beg;
2774
0
    OFF opener_end;
2775
0
    OFF closer_beg;
2776
0
    OFF closer_end;
2777
0
    SZ mark_len;
2778
0
    OFF line_end;
2779
0
    int has_space_after_opener = FALSE;
2780
0
    int has_eol_after_opener = FALSE;
2781
0
    int has_space_before_closer = FALSE;
2782
0
    int has_eol_before_closer = FALSE;
2783
0
    int has_only_space = TRUE;
2784
0
    MD_SIZE line_index = 0;
2785
2786
0
    line_end = lines[0].end;
2787
0
    opener_end = opener_beg;
2788
0
    while(opener_end < line_end  &&  CH(opener_end) == _T('`'))
2789
0
        opener_end++;
2790
0
    has_space_after_opener = (opener_end < line_end && CH(opener_end) == _T(' '));
2791
0
    has_eol_after_opener = (opener_end == line_end);
2792
2793
    /* The caller needs to know end of the opening mark even if we fail. */
2794
0
    opener->end = opener_end;
2795
2796
0
    mark_len = opener_end - opener_beg;
2797
0
    if(mark_len > CODESPAN_MARK_MAXLEN)
2798
0
        return FALSE;
2799
2800
    /* Check whether we already know there is no closer of this length.
2801
     * If so, re-scan does no sense. This fixes issue #59. */
2802
0
    if(last_potential_closers[mark_len-1] >= lines[n_lines-1].end  ||
2803
0
       (*p_reached_paragraph_end  &&  last_potential_closers[mark_len-1] < opener_end))
2804
0
        return FALSE;
2805
2806
0
    closer_beg = opener_end;
2807
0
    closer_end = opener_end;
2808
2809
    /* Find closer mark. */
2810
0
    while(TRUE) {
2811
0
        while(closer_beg < line_end  &&  CH(closer_beg) != _T('`')) {
2812
0
            if(CH(closer_beg) != _T(' '))
2813
0
                has_only_space = FALSE;
2814
0
            closer_beg++;
2815
0
        }
2816
0
        closer_end = closer_beg;
2817
0
        while(closer_end < line_end  &&  CH(closer_end) == _T('`'))
2818
0
            closer_end++;
2819
2820
0
        if(closer_end - closer_beg == mark_len) {
2821
            /* Success. */
2822
0
            has_space_before_closer = (closer_beg > lines[line_index].beg && CH(closer_beg-1) == _T(' '));
2823
0
            has_eol_before_closer = (closer_beg == lines[line_index].beg);
2824
0
            break;
2825
0
        }
2826
2827
0
        if(closer_end - closer_beg > 0) {
2828
            /* We have found a back-tick which is not part of the closer. */
2829
0
            has_only_space = FALSE;
2830
2831
            /* But if we eventually fail, remember it as a potential closer
2832
             * of its own length for future attempts. This mitigates needs for
2833
             * rescans. */
2834
0
            if(closer_end - closer_beg < CODESPAN_MARK_MAXLEN) {
2835
0
                if(closer_beg > last_potential_closers[closer_end - closer_beg - 1])
2836
0
                    last_potential_closers[closer_end - closer_beg - 1] = closer_beg;
2837
0
            }
2838
0
        }
2839
2840
0
        if(closer_end >= line_end) {
2841
0
            line_index++;
2842
0
            if(line_index >= n_lines) {
2843
                /* Reached end of the paragraph and still nothing. */
2844
0
                *p_reached_paragraph_end = TRUE;
2845
0
                return FALSE;
2846
0
            }
2847
            /* Try on the next line. */
2848
0
            line_end = lines[line_index].end;
2849
0
            closer_beg = lines[line_index].beg;
2850
0
        } else {
2851
0
            closer_beg = closer_end;
2852
0
        }
2853
0
    }
2854
2855
    /* If there is a space or a new line both after and before the opener
2856
     * (and if the code span is not made of spaces only), consume one initial
2857
     * and one trailing space as part of the marks. */
2858
0
    if(!has_only_space  &&
2859
0
       (has_space_after_opener || has_eol_after_opener)  &&
2860
0
       (has_space_before_closer || has_eol_before_closer))
2861
0
    {
2862
0
        if(has_space_after_opener)
2863
0
            opener_end++;
2864
0
        else
2865
0
            opener_end = lines[1].beg;
2866
2867
0
        if(has_space_before_closer)
2868
0
            closer_beg--;
2869
0
        else {
2870
            /* Go back to the end of prev line */
2871
0
            closer_beg = lines[line_index-1].end;
2872
            /* But restore any trailing whitespace */
2873
0
            while(closer_beg < ctx->size  &&  ISBLANK(closer_beg))
2874
0
                closer_beg++;
2875
0
        }
2876
0
    }
2877
2878
0
    opener->ch = _T('`');
2879
0
    opener->beg = opener_beg;
2880
0
    opener->end = opener_end;
2881
0
    opener->flags = MD_MARK_POTENTIAL_OPENER;
2882
0
    closer->ch = _T('`');
2883
0
    closer->beg = closer_beg;
2884
0
    closer->end = closer_end;
2885
0
    closer->flags = MD_MARK_POTENTIAL_CLOSER;
2886
0
    return TRUE;
2887
0
}
2888
2889
static int
2890
md_is_autolink_uri(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end)
2891
0
{
2892
0
    OFF off = beg+1;
2893
2894
0
    MD_ASSERT(CH(beg) == _T('<'));
2895
2896
    /* Check for scheme. */
2897
0
    if(off >= max_end  ||  !ISASCII(off))
2898
0
        return FALSE;
2899
0
    off++;
2900
0
    while(1) {
2901
0
        if(off >= max_end)
2902
0
            return FALSE;
2903
0
        if(off - beg > 32)
2904
0
            return FALSE;
2905
0
        if(CH(off) == _T(':')  &&  off - beg >= 3)
2906
0
            break;
2907
0
        if(!ISALNUM(off) && CH(off) != _T('+') && CH(off) != _T('-') && CH(off) != _T('.'))
2908
0
            return FALSE;
2909
0
        off++;
2910
0
    }
2911
2912
    /* Check the path after the scheme. */
2913
0
    while(off < max_end  &&  CH(off) != _T('>')) {
2914
0
        if(ISWHITESPACE(off) || ISCNTRL(off) || CH(off) == _T('<'))
2915
0
            return FALSE;
2916
0
        off++;
2917
0
    }
2918
2919
0
    if(off >= max_end)
2920
0
        return FALSE;
2921
2922
0
    MD_ASSERT(CH(off) == _T('>'));
2923
0
    *p_end = off+1;
2924
0
    return TRUE;
2925
0
}
2926
2927
static int
2928
md_is_autolink_email(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end)
2929
0
{
2930
0
    OFF off = beg + 1;
2931
0
    int label_len;
2932
2933
0
    MD_ASSERT(CH(beg) == _T('<'));
2934
2935
    /* The code should correspond to this regexp:
2936
            /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+
2937
            @[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?
2938
            (?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
2939
     */
2940
2941
    /* Username (before '@'). */
2942
0
    while(off < max_end  &&  (ISALNUM(off) || ISANYOF(off, _T(".!#$%&'*+/=?^_`{|}~-"))))
2943
0
        off++;
2944
0
    if(off <= beg+1)
2945
0
        return FALSE;
2946
2947
    /* '@' */
2948
0
    if(off >= max_end  ||  CH(off) != _T('@'))
2949
0
        return FALSE;
2950
0
    off++;
2951
2952
    /* Labels delimited with '.'; each label is sequence of 1 - 63 alnum
2953
     * characters or '-', but '-' is not allowed as first or last char. */
2954
0
    label_len = 0;
2955
0
    while(off < max_end) {
2956
0
        if(ISALNUM(off))
2957
0
            label_len++;
2958
0
        else if(CH(off) == _T('-')  &&  label_len > 0)
2959
0
            label_len++;
2960
0
        else if(CH(off) == _T('.')  &&  label_len > 0  &&  CH(off-1) != _T('-'))
2961
0
            label_len = 0;
2962
0
        else
2963
0
            break;
2964
2965
0
        if(label_len > 63)
2966
0
            return FALSE;
2967
2968
0
        off++;
2969
0
    }
2970
2971
0
    if(label_len <= 0  || off >= max_end  ||  CH(off) != _T('>') ||  CH(off-1) == _T('-'))
2972
0
        return FALSE;
2973
2974
0
    *p_end = off+1;
2975
0
    return TRUE;
2976
0
}
2977
2978
static int
2979
md_is_autolink(MD_CTX* ctx, OFF beg, OFF max_end, OFF* p_end, int* p_missing_mailto)
2980
0
{
2981
0
    if(md_is_autolink_uri(ctx, beg, max_end, p_end)) {
2982
0
        *p_missing_mailto = FALSE;
2983
0
        return TRUE;
2984
0
    }
2985
2986
0
    if(md_is_autolink_email(ctx, beg, max_end, p_end)) {
2987
0
        *p_missing_mailto = TRUE;
2988
0
        return TRUE;
2989
0
    }
2990
2991
0
    return FALSE;
2992
0
}
2993
2994
static int
2995
md_collect_marks(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, int table_mode)
2996
0
{
2997
0
    MD_SIZE line_index;
2998
0
    int ret = 0;
2999
0
    MD_MARK* mark;
3000
0
    OFF codespan_last_potential_closers[CODESPAN_MARK_MAXLEN] = { 0 };
3001
0
    int codespan_scanned_till_paragraph_end = FALSE;
3002
3003
0
    for(line_index = 0; line_index < n_lines; line_index++) {
3004
0
        const MD_LINE* line = &lines[line_index];
3005
0
        OFF off = line->beg;
3006
3007
0
        while(TRUE) {
3008
0
            CHAR ch;
3009
3010
#ifdef MD4C_USE_UTF16
3011
    /* For UTF-16, mark_char_map[] covers only ASCII. */
3012
    #define IS_MARK_CHAR(off)   ((CH(off) < SIZEOF_ARRAY(ctx->mark_char_map))  &&  \
3013
                                (ctx->mark_char_map[(unsigned char) CH(off)]))
3014
#else
3015
    /* For 8-bit encodings, mark_char_map[] covers all 256 elements. */
3016
0
    #define IS_MARK_CHAR(off)   (ctx->mark_char_map[(unsigned char) CH(off)])
3017
0
#endif
3018
3019
            /* Optimization: Use some loop unrolling. */
3020
0
            while(off + 3 < line->end  &&  !IS_MARK_CHAR(off+0)  &&  !IS_MARK_CHAR(off+1)
3021
0
                                       &&  !IS_MARK_CHAR(off+2)  &&  !IS_MARK_CHAR(off+3))
3022
0
                off += 4;
3023
0
            while(off < line->end  &&  !IS_MARK_CHAR(off+0))
3024
0
                off++;
3025
3026
0
            if(off >= line->end)
3027
0
                break;
3028
3029
0
            ch = CH(off);
3030
3031
            /* A backslash escape.
3032
             * It can go beyond line->end as it may involve escaped new
3033
             * line to form a hard break. */
3034
0
            if(ch == _T('\\')  &&  off+1 < ctx->size  &&  (ISPUNCT(off+1) || ISNEWLINE(off+1))) {
3035
                /* Hard-break cannot be on the last line of the block. */
3036
0
                if(!ISNEWLINE(off+1)  ||  line_index+1 < n_lines)
3037
0
                    ADD_MARK(ch, off, off+2, MD_MARK_RESOLVED);
3038
0
                off += 2;
3039
0
                continue;
3040
0
            }
3041
3042
            /* A potential (string) emphasis start/end. */
3043
0
            if(ch == _T('*')  ||  ch == _T('_')) {
3044
0
                OFF tmp = off+1;
3045
0
                int left_level;     /* What precedes: 0 = whitespace; 1 = punctuation; 2 = other char. */
3046
0
                int right_level;    /* What follows: 0 = whitespace; 1 = punctuation; 2 = other char. */
3047
3048
0
                while(tmp < line->end  &&  CH(tmp) == ch)
3049
0
                    tmp++;
3050
3051
0
                if(off == line->beg  ||  ISUNICODEWHITESPACEBEFORE(off))
3052
0
                    left_level = 0;
3053
0
                else if(ISUNICODEPUNCTBEFORE(off))
3054
0
                    left_level = 1;
3055
0
                else
3056
0
                    left_level = 2;
3057
3058
0
                if(tmp == line->end  ||  ISUNICODEWHITESPACE(tmp))
3059
0
                    right_level = 0;
3060
0
                else if(ISUNICODEPUNCT(tmp))
3061
0
                    right_level = 1;
3062
0
                else
3063
0
                    right_level = 2;
3064
3065
                /* Intra-word underscore doesn't have special meaning. */
3066
0
                if(ch == _T('_')  &&  left_level == 2  &&  right_level == 2) {
3067
0
                    left_level = 0;
3068
0
                    right_level = 0;
3069
0
                }
3070
3071
0
                if(left_level != 0  ||  right_level != 0) {
3072
0
                    unsigned flags = 0;
3073
3074
0
                    if(left_level > 0  &&  left_level >= right_level)
3075
0
                        flags |= MD_MARK_POTENTIAL_CLOSER;
3076
0
                    if(right_level > 0  &&  right_level >= left_level)
3077
0
                        flags |= MD_MARK_POTENTIAL_OPENER;
3078
0
                    if(flags == (MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER))
3079
0
                        flags |= MD_MARK_EMPH_OC;
3080
3081
                    /* For "the rule of three" we need to remember the original
3082
                     * size of the mark (modulo three), before we potentially
3083
                     * split the mark when being later resolved partially by some
3084
                     * shorter closer. */
3085
0
                    switch((tmp - off) % 3) {
3086
0
                        case 0: flags |= MD_MARK_EMPH_MOD3_0; break;
3087
0
                        case 1: flags |= MD_MARK_EMPH_MOD3_1; break;
3088
0
                        case 2: flags |= MD_MARK_EMPH_MOD3_2; break;
3089
0
                    }
3090
3091
0
                    ADD_MARK(ch, off, tmp, flags);
3092
3093
                    /* During resolving, multiple asterisks may have to be
3094
                     * split into independent span start/ends. Consider e.g.
3095
                     * "**foo* bar*". Therefore we push also some empty dummy
3096
                     * marks to have enough space for that. */
3097
0
                    off++;
3098
0
                    while(off < tmp) {
3099
0
                        ADD_MARK('D', off, off, 0);
3100
0
                        off++;
3101
0
                    }
3102
0
                    continue;
3103
0
                }
3104
3105
0
                off = tmp;
3106
0
                continue;
3107
0
            }
3108
3109
            /* A potential code span start/end. */
3110
0
            if(ch == _T('`')) {
3111
0
                MD_MARK opener;
3112
0
                MD_MARK closer;
3113
0
                int is_code_span;
3114
3115
0
                is_code_span = md_is_code_span(ctx, line, n_lines - line_index, off,
3116
0
                            &opener, &closer, codespan_last_potential_closers,
3117
0
                            &codespan_scanned_till_paragraph_end);
3118
0
                if(is_code_span) {
3119
0
                    ADD_MARK(opener.ch, opener.beg, opener.end, opener.flags);
3120
0
                    ADD_MARK(closer.ch, closer.beg, closer.end, closer.flags);
3121
0
                    md_resolve_range(ctx, ctx->n_marks-2, ctx->n_marks-1);
3122
0
                    off = closer.end;
3123
3124
                    /* Advance the current line accordingly. */
3125
0
                    if(off > line->end)
3126
0
                        line = md_lookup_line(off, lines, n_lines, &line_index);
3127
0
                    continue;
3128
0
                }
3129
3130
0
                off = opener.end;
3131
0
                continue;
3132
0
            }
3133
3134
            /* A potential entity start. */
3135
0
            if(ch == _T('&')) {
3136
0
                ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_OPENER);
3137
0
                off++;
3138
0
                continue;
3139
0
            }
3140
3141
            /* A potential entity end. */
3142
0
            if(ch == _T(';')) {
3143
                /* We surely cannot be entity unless the previous mark is '&'. */
3144
0
                if(ctx->n_marks > 0  &&  ctx->marks[ctx->n_marks-1].ch == _T('&'))
3145
0
                    ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_CLOSER);
3146
3147
0
                off++;
3148
0
                continue;
3149
0
            }
3150
3151
            /* A potential autolink or raw HTML start/end. */
3152
0
            if(ch == _T('<')) {
3153
0
                int is_autolink;
3154
0
                OFF autolink_end;
3155
0
                int missing_mailto;
3156
3157
0
                if(!(ctx->parser.flags & MD_FLAG_NOHTMLSPANS)) {
3158
0
                    int is_html;
3159
0
                    OFF html_end;
3160
3161
                    /* Given the nature of the raw HTML, we have to recognize
3162
                     * it here. Doing so later in md_analyze_lt_gt() could
3163
                     * open can of worms of quadratic complexity. */
3164
0
                    is_html = md_is_html_any(ctx, line, n_lines - line_index, off,
3165
0
                                    lines[n_lines-1].end, &html_end);
3166
0
                    if(is_html) {
3167
0
                        ADD_MARK(_T('<'), off, off, MD_MARK_OPENER | MD_MARK_RESOLVED);
3168
0
                        ADD_MARK(_T('>'), html_end, html_end, MD_MARK_CLOSER | MD_MARK_RESOLVED);
3169
0
                        ctx->marks[ctx->n_marks-2].next = ctx->n_marks-1;
3170
0
                        ctx->marks[ctx->n_marks-1].prev = ctx->n_marks-2;
3171
0
                        off = html_end;
3172
3173
                        /* Advance the current line accordingly. */
3174
0
                        if(off > line->end)
3175
0
                            line = md_lookup_line(off, lines, n_lines, &line_index);
3176
0
                        continue;
3177
0
                    }
3178
0
                }
3179
3180
0
                is_autolink = md_is_autolink(ctx, off, lines[n_lines-1].end,
3181
0
                                    &autolink_end, &missing_mailto);
3182
0
                if(is_autolink) {
3183
0
                    unsigned flags = MD_MARK_RESOLVED | MD_MARK_AUTOLINK;
3184
0
                    if(missing_mailto)
3185
0
                        flags |= MD_MARK_AUTOLINK_MISSING_MAILTO;
3186
3187
0
                    ADD_MARK(_T('<'), off, off+1, MD_MARK_OPENER | flags);
3188
0
                    ADD_MARK(_T('>'), autolink_end-1, autolink_end, MD_MARK_CLOSER | flags);
3189
0
                    ctx->marks[ctx->n_marks-2].next = ctx->n_marks-1;
3190
0
                    ctx->marks[ctx->n_marks-1].prev = ctx->n_marks-2;
3191
0
                    off = autolink_end;
3192
0
                    continue;
3193
0
                }
3194
3195
0
                off++;
3196
0
                continue;
3197
0
            }
3198
3199
            /* A potential link or its part. */
3200
0
            if(ch == _T('[')  ||  (ch == _T('!') && off+1 < line->end && CH(off+1) == _T('['))) {
3201
0
                OFF tmp = (ch == _T('[') ? off+1 : off+2);
3202
0
                ADD_MARK(ch, off, tmp, MD_MARK_POTENTIAL_OPENER);
3203
0
                off = tmp;
3204
                /* Two dummies to make enough place for data we need if it is
3205
                 * a link. */
3206
0
                ADD_MARK('D', off, off, 0);
3207
0
                ADD_MARK('D', off, off, 0);
3208
0
                continue;
3209
0
            }
3210
0
            if(ch == _T(']')) {
3211
0
                ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_CLOSER);
3212
0
                off++;
3213
0
                continue;
3214
0
            }
3215
3216
            /* A potential permissive e-mail autolink. */
3217
0
            if(ch == _T('@')) {
3218
0
                if(line->beg + 1 <= off  &&  ISALNUM(off-1)  &&
3219
0
                    off + 3 < line->end  &&  ISALNUM(off+1))
3220
0
                {
3221
0
                    ADD_MARK(ch, off, off+1, MD_MARK_POTENTIAL_OPENER);
3222
                    /* Push a dummy as a reserve for a closer. */
3223
0
                    ADD_MARK('D', line->beg, line->end, 0);
3224
0
                }
3225
3226
0
                off++;
3227
0
                continue;
3228
0
            }
3229
3230
            /* A potential permissive URL autolink. */
3231
0
            if(ch == _T(':')) {
3232
0
                static const struct {
3233
0
                    const CHAR* scheme;
3234
0
                    SZ scheme_size;
3235
0
                    const CHAR* suffix;
3236
0
                    SZ suffix_size;
3237
0
                } scheme_map[] = {
3238
                    /* In the order from the most frequently used, arguably. */
3239
0
                    { _T("http"), 4,    _T("//"), 2 },
3240
0
                    { _T("https"), 5,   _T("//"), 2 },
3241
0
                    { _T("ftp"), 3,     _T("//"), 2 }
3242
0
                };
3243
0
                int scheme_index;
3244
3245
0
                for(scheme_index = 0; scheme_index < (int) SIZEOF_ARRAY(scheme_map); scheme_index++) {
3246
0
                    const CHAR* scheme = scheme_map[scheme_index].scheme;
3247
0
                    const SZ scheme_size = scheme_map[scheme_index].scheme_size;
3248
0
                    const CHAR* suffix = scheme_map[scheme_index].suffix;
3249
0
                    const SZ suffix_size = scheme_map[scheme_index].suffix_size;
3250
3251
0
                    if(line->beg + scheme_size <= off  &&  md_ascii_eq(STR(off-scheme_size), scheme, scheme_size)  &&
3252
0
                        off + 1 + suffix_size < line->end  &&  md_ascii_eq(STR(off+1), suffix, suffix_size))
3253
0
                    {
3254
0
                        ADD_MARK(ch, off-scheme_size, off+1+suffix_size, MD_MARK_POTENTIAL_OPENER);
3255
                        /* Push a dummy as a reserve for a closer. */
3256
0
                        ADD_MARK('D', line->beg, line->end, 0);
3257
0
                        off += 1 + suffix_size;
3258
0
                        break;
3259
0
                    }
3260
0
                }
3261
3262
0
                off++;
3263
0
                continue;
3264
0
            }
3265
3266
            /* A potential permissive WWW autolink. */
3267
0
            if(ch == _T('.')) {
3268
0
                if(line->beg + 3 <= off  &&  md_ascii_eq(STR(off-3), _T("www"), 3)  &&
3269
0
                   (off-3 == line->beg || ISUNICODEWHITESPACEBEFORE(off-3) || ISUNICODEPUNCTBEFORE(off-3)))
3270
0
                {
3271
0
                    ADD_MARK(ch, off-3, off+1, MD_MARK_POTENTIAL_OPENER);
3272
                    /* Push a dummy as a reserve for a closer. */
3273
0
                    ADD_MARK('D', line->beg, line->end, 0);
3274
0
                    off++;
3275
0
                    continue;
3276
0
                }
3277
3278
0
                off++;
3279
0
                continue;
3280
0
            }
3281
3282
            /* A potential table cell boundary or wiki link label delimiter. */
3283
0
            if((table_mode || ctx->parser.flags & MD_FLAG_WIKILINKS) && ch == _T('|')) {
3284
0
                ADD_MARK(ch, off, off+1, 0);
3285
0
                off++;
3286
0
                continue;
3287
0
            }
3288
3289
            /* A potential strikethrough/equation start/end. */
3290
0
            if(ch == _T('$') || ch == _T('~')) {
3291
0
                OFF tmp = off+1;
3292
3293
0
                while(tmp < line->end && CH(tmp) == ch)
3294
0
                    tmp++;
3295
3296
0
                if(tmp - off <= 2) {
3297
0
                    unsigned flags = MD_MARK_POTENTIAL_OPENER | MD_MARK_POTENTIAL_CLOSER;
3298
3299
0
                    if(off > line->beg  &&  !ISUNICODEWHITESPACEBEFORE(off)  &&  !ISUNICODEPUNCTBEFORE(off))
3300
0
                        flags &= ~MD_MARK_POTENTIAL_OPENER;
3301
0
                    if(tmp < line->end  &&  !ISUNICODEWHITESPACE(tmp)  &&  !ISUNICODEPUNCT(tmp))
3302
0
                        flags &= ~MD_MARK_POTENTIAL_CLOSER;
3303
0
                    if(flags != 0)
3304
0
                        ADD_MARK(ch, off, tmp, flags);
3305
0
                }
3306
3307
0
                off = tmp;
3308
0
                continue;
3309
0
            }
3310
3311
            /* Turn non-trivial whitespace into single space. */
3312
0
            if(ISWHITESPACE_(ch)) {
3313
0
                OFF tmp = off+1;
3314
3315
0
                while(tmp < line->end  &&  ISWHITESPACE(tmp))
3316
0
                    tmp++;
3317
3318
0
                if(tmp - off > 1  ||  ch != _T(' '))
3319
0
                    ADD_MARK(ch, off, tmp, MD_MARK_RESOLVED);
3320
3321
0
                off = tmp;
3322
0
                continue;
3323
0
            }
3324
3325
            /* NULL character. */
3326
0
            if(ch == _T('\0')) {
3327
0
                ADD_MARK(ch, off, off+1, MD_MARK_RESOLVED);
3328
0
                off++;
3329
0
                continue;
3330
0
            }
3331
3332
0
            off++;
3333
0
        }
3334
0
    }
3335
3336
    /* Add a dummy mark at the end of the mark vector to simplify
3337
     * process_inlines(). */
3338
0
    ADD_MARK(127, ctx->size, ctx->size, MD_MARK_RESOLVED);
3339
3340
0
abort:
3341
0
    return ret;
3342
0
}
3343
3344
static void
3345
md_analyze_bracket(MD_CTX* ctx, int mark_index)
3346
0
{
3347
    /* We cannot really resolve links here as for that we would need
3348
     * more context. E.g. a following pair of brackets (reference link),
3349
     * or enclosing pair of brackets (if the inner is the link, the outer
3350
     * one cannot be.)
3351
     *
3352
     * Therefore we here only construct a list of '[' ']' pairs ordered by
3353
     * position of the closer. This allows us to analyze what is or is not
3354
     * link in the right order, from inside to outside in case of nested
3355
     * brackets.
3356
     *
3357
     * The resolving itself is deferred to md_resolve_links().
3358
     */
3359
3360
0
    MD_MARK* mark = &ctx->marks[mark_index];
3361
3362
0
    if(mark->flags & MD_MARK_POTENTIAL_OPENER) {
3363
0
        if(BRACKET_OPENERS.top >= 0)
3364
0
            ctx->marks[BRACKET_OPENERS.top].flags |= MD_MARK_HASNESTEDBRACKETS;
3365
3366
0
        md_mark_stack_push(ctx, &BRACKET_OPENERS, mark_index);
3367
0
        return;
3368
0
    }
3369
3370
0
    if(BRACKET_OPENERS.top >= 0) {
3371
0
        int opener_index = md_mark_stack_pop(ctx, &BRACKET_OPENERS);
3372
0
        MD_MARK* opener = &ctx->marks[opener_index];
3373
3374
        /* Interconnect the opener and closer. */
3375
0
        opener->next = mark_index;
3376
0
        mark->prev = opener_index;
3377
3378
        /* Add the pair into a list of potential links for md_resolve_links().
3379
         * Note we misuse opener->prev for this as opener->next points to its
3380
         * closer. */
3381
0
        if(ctx->unresolved_link_tail >= 0)
3382
0
            ctx->marks[ctx->unresolved_link_tail].prev = opener_index;
3383
0
        else
3384
0
            ctx->unresolved_link_head = opener_index;
3385
0
        ctx->unresolved_link_tail = opener_index;
3386
0
        opener->prev = -1;
3387
0
    }
3388
0
}
3389
3390
/* Forward declaration. */
3391
static void md_analyze_link_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines,
3392
                                     int mark_beg, int mark_end);
3393
3394
static int
3395
md_resolve_links(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines)
3396
0
{
3397
0
    int opener_index = ctx->unresolved_link_head;
3398
0
    OFF last_link_beg = 0;
3399
0
    OFF last_link_end = 0;
3400
0
    OFF last_img_beg = 0;
3401
0
    OFF last_img_end = 0;
3402
3403
0
    while(opener_index >= 0) {
3404
0
        MD_MARK* opener = &ctx->marks[opener_index];
3405
0
        int closer_index = opener->next;
3406
0
        MD_MARK* closer = &ctx->marks[closer_index];
3407
0
        int next_index = opener->prev;
3408
0
        MD_MARK* next_opener;
3409
0
        MD_MARK* next_closer;
3410
0
        MD_LINK_ATTR attr;
3411
0
        int is_link = FALSE;
3412
3413
0
        if(next_index >= 0) {
3414
0
            next_opener = &ctx->marks[next_index];
3415
0
            next_closer = &ctx->marks[next_opener->next];
3416
0
        } else {
3417
0
            next_opener = NULL;
3418
0
            next_closer = NULL;
3419
0
        }
3420
3421
        /* If nested ("[ [ ] ]"), we need to make sure that:
3422
         *   - The outer does not end inside of (...) belonging to the inner.
3423
         *   - The outer cannot be link if the inner is link (i.e. not image).
3424
         *
3425
         * (Note we here analyze from inner to outer as the marks are ordered
3426
         * by closer->beg.)
3427
         */
3428
0
        if((opener->beg < last_link_beg  &&  closer->end < last_link_end)  ||
3429
0
           (opener->beg < last_img_beg  &&  closer->end < last_img_end)  ||
3430
0
           (opener->beg < last_link_end  &&  opener->ch == '['))
3431
0
        {
3432
0
            opener_index = next_index;
3433
0
            continue;
3434
0
        }
3435
3436
        /* Recognize and resolve wiki links.
3437
         * Wiki-links maybe '[[destination]]' or '[[destination|label]]'.
3438
         */
3439
0
        if ((ctx->parser.flags & MD_FLAG_WIKILINKS) &&
3440
0
            (opener->end - opener->beg == 1) &&         /* not image */
3441
0
            next_opener != NULL &&                      /* double '[' opener */
3442
0
            next_opener->ch == '[' &&
3443
0
            (next_opener->beg == opener->beg - 1) &&
3444
0
            (next_opener->end - next_opener->beg == 1) &&
3445
0
            next_closer != NULL &&                      /* double ']' closer */
3446
0
            next_closer->ch == ']' &&
3447
0
            (next_closer->beg == closer->beg + 1) &&
3448
0
            (next_closer->end - next_closer->beg == 1))
3449
0
        {
3450
0
            MD_MARK* delim = NULL;
3451
0
            int delim_index;
3452
0
            OFF dest_beg, dest_end;
3453
3454
0
            is_link = TRUE;
3455
3456
            /* We don't allow destination to be longer than 100 characters.
3457
             * Lets scan to see whether there is '|'. (If not then the whole
3458
             * wiki-link has to be below the 100 characters.) */
3459
0
            delim_index = opener_index + 1;
3460
0
            while(delim_index < closer_index) {
3461
0
                MD_MARK* m = &ctx->marks[delim_index];
3462
0
                if(m->ch == '|') {
3463
0
                    delim = m;
3464
0
                    break;
3465
0
                }
3466
0
                if(m->ch != 'D') {
3467
0
                    if(m->beg - opener->end > 100)
3468
0
                        break;
3469
0
                    if(m->ch != 'D'  &&  (m->flags & MD_MARK_OPENER))
3470
0
                        delim_index = m->next;
3471
0
                }
3472
0
                delim_index++;
3473
0
            }
3474
3475
0
            dest_beg = opener->end;
3476
0
            dest_end = (delim != NULL) ? delim->beg : closer->beg;
3477
0
            if(dest_end - dest_beg == 0 || dest_end - dest_beg > 100)
3478
0
                is_link = FALSE;
3479
3480
            /* There may not be any new line in the destination. */
3481
0
            if(is_link) {
3482
0
                OFF off;
3483
0
                for(off = dest_beg; off < dest_end; off++) {
3484
0
                    if(ISNEWLINE(off)) {
3485
0
                        is_link = FALSE;
3486
0
                        break;
3487
0
                    }
3488
0
                }
3489
0
            }
3490
3491
0
            if(is_link) {
3492
0
                md_pop_openers(ctx, opener_index);
3493
3494
0
                if(delim != NULL) {
3495
0
                    if(delim->end < closer->beg) {
3496
0
                        md_disable_marks(ctx, delim_index+1, delim_index);
3497
0
                        delim->flags |= MD_MARK_RESOLVED;
3498
0
                        opener->end = delim->beg;
3499
0
                    } else {
3500
                        /* The pipe is just before the closer: [[foo|]] */
3501
0
                        md_disable_marks(ctx, opener_index+1, closer_index);
3502
0
                        closer->beg = delim->beg;
3503
0
                    }
3504
0
                }
3505
3506
0
                opener->beg = next_opener->beg;
3507
0
                opener->next = closer_index;
3508
0
                opener->flags |= MD_MARK_OPENER | MD_MARK_RESOLVED;
3509
3510
0
                closer->end = next_closer->end;
3511
0
                closer->prev = opener_index;
3512
0
                closer->flags |= MD_MARK_CLOSER | MD_MARK_RESOLVED;
3513
3514
0
                last_link_beg = opener->beg;
3515
0
                last_link_end = closer->end;
3516
3517
0
                if(delim != NULL)
3518
0
                    md_analyze_link_contents(ctx, lines, n_lines, delim_index+1, closer_index);
3519
3520
0
                opener_index = next_opener->prev;
3521
0
                continue;
3522
0
            }
3523
0
        }
3524
3525
0
        if(next_opener != NULL  &&  next_opener->beg == closer->end) {
3526
0
            if(next_closer->beg > closer->end + 1) {
3527
                /* Might be full reference link. */
3528
0
                if(!(next_opener->flags & MD_MARK_HASNESTEDBRACKETS))
3529
0
                    is_link = md_is_link_reference(ctx, lines, n_lines, next_opener->beg, next_closer->end, &attr);
3530
0
            } else {
3531
                /* Might be shortcut reference link. */
3532
0
                if(!(opener->flags & MD_MARK_HASNESTEDBRACKETS))
3533
0
                    is_link = md_is_link_reference(ctx, lines, n_lines, opener->beg, closer->end, &attr);
3534
0
            }
3535
3536
0
            if(is_link < 0)
3537
0
                return -1;
3538
3539
0
            if(is_link) {
3540
                /* Eat the 2nd "[...]". */
3541
0
                closer->end = next_closer->end;
3542
3543
                /* Do not analyze the label as a standalone link in the next
3544
                 * iteration. */
3545
0
                next_index = ctx->marks[next_index].prev;
3546
0
            }
3547
0
        } else {
3548
0
            if(closer->end < ctx->size  &&  CH(closer->end) == _T('(')) {
3549
                /* Might be inline link. */
3550
0
                OFF inline_link_end = UINT_MAX;
3551
0
                int following_mark_index = closer_index + 1;
3552
3553
0
                is_link = md_is_inline_link_spec(ctx, lines, n_lines, closer->end, &inline_link_end, &attr);
3554
0
                if(is_link < 0)
3555
0
                    return -1;
3556
3557
                /* Check the closing ')' is not inside an already resolved range
3558
                 * (i.e. a range with a higher priority), e.g. a code span. */
3559
0
                if(is_link) {
3560
0
                    while(following_mark_index < ctx->n_marks) {
3561
0
                        MD_MARK* mark = &ctx->marks[following_mark_index];
3562
3563
0
                        if(mark->beg >= inline_link_end)
3564
0
                            break;
3565
0
                        if((mark->flags & (MD_MARK_OPENER | MD_MARK_RESOLVED)) == (MD_MARK_OPENER | MD_MARK_RESOLVED)) {
3566
0
                            if(ctx->marks[mark->next].beg >= inline_link_end) {
3567
                                /* Cancel the link status. */
3568
0
                                if(attr.title_needs_free)
3569
0
                                    free(attr.title);
3570
0
                                is_link = FALSE;
3571
0
                                break;
3572
0
                            }
3573
3574
0
                            following_mark_index = mark->next + 1;
3575
0
                        } else {
3576
0
                            following_mark_index++;
3577
0
                        }
3578
0
                    }
3579
0
                }
3580
3581
0
                if(is_link) {
3582
                    /* Eat the "(...)" */
3583
0
                    closer->end = inline_link_end;
3584
0
                    md_disable_marks(ctx, closer_index+1, following_mark_index);
3585
0
                }
3586
0
            }
3587
3588
0
            if(!is_link) {
3589
                /* Might be collapsed reference link. */
3590
0
                if(!(opener->flags & MD_MARK_HASNESTEDBRACKETS))
3591
0
                    is_link = md_is_link_reference(ctx, lines, n_lines, opener->beg, closer->end, &attr);
3592
0
                if(is_link < 0)
3593
0
                    return -1;
3594
0
            }
3595
0
        }
3596
3597
0
        if(is_link) {
3598
            /* Resolve the brackets as a link. */
3599
0
            opener->flags |= MD_MARK_OPENER | MD_MARK_RESOLVED;
3600
0
            closer->flags |= MD_MARK_CLOSER | MD_MARK_RESOLVED;
3601
3602
            /* If it is a link, we store the destination and title in the two
3603
             * dummy marks after the opener. */
3604
0
            MD_ASSERT(ctx->marks[opener_index+1].ch == 'D');
3605
0
            ctx->marks[opener_index+1].beg = attr.dest_beg;
3606
0
            ctx->marks[opener_index+1].end = attr.dest_end;
3607
3608
0
            MD_ASSERT(ctx->marks[opener_index+2].ch == 'D');
3609
0
            md_mark_store_ptr(ctx, opener_index+2, attr.title);
3610
            /* The title might or might not have been allocated for us. */
3611
0
            if(attr.title_needs_free)
3612
0
                md_mark_stack_push(ctx, &ctx->ptr_stack, opener_index+2);
3613
0
            ctx->marks[opener_index+2].prev = attr.title_size;
3614
3615
0
            if(opener->ch == '[') {
3616
0
                last_link_beg = opener->beg;
3617
0
                last_link_end = closer->end;
3618
0
            } else {
3619
0
                last_img_beg = opener->beg;
3620
0
                last_img_end = closer->end;
3621
0
            }
3622
3623
0
            md_analyze_link_contents(ctx, lines, n_lines, opener_index+1, closer_index);
3624
3625
            /* If the link text is formed by nothing but permissive autolink,
3626
             * suppress the autolink.
3627
             * See https://github.com/mity/md4c/issues/152 for more info. */
3628
0
            if(ctx->parser.flags & MD_FLAG_PERMISSIVEAUTOLINKS) {
3629
0
                MD_MARK* first_nested;
3630
0
                MD_MARK* last_nested;
3631
3632
0
                first_nested = opener + 1;
3633
0
                while(first_nested->ch == _T('D')  &&  first_nested < closer)
3634
0
                    first_nested++;
3635
3636
0
                last_nested = closer - 1;
3637
0
                while(first_nested->ch == _T('D')  &&  last_nested > opener)
3638
0
                    last_nested--;
3639
3640
0
                if((first_nested->flags & MD_MARK_RESOLVED)  &&
3641
0
                   first_nested->beg == opener->end  &&
3642
0
                   ISANYOF_(first_nested->ch, _T("@:."))  &&
3643
0
                   first_nested->next == (last_nested - ctx->marks)  &&
3644
0
                   last_nested->end == closer->beg)
3645
0
                {
3646
0
                    first_nested->ch = _T('D');
3647
0
                    first_nested->flags &= ~MD_MARK_RESOLVED;
3648
0
                    last_nested->ch = _T('D');
3649
0
                    last_nested->flags &= ~MD_MARK_RESOLVED;
3650
0
                }
3651
0
            }
3652
0
        }
3653
3654
0
        opener_index = next_index;
3655
0
    }
3656
3657
0
    return 0;
3658
0
}
3659
3660
/* Analyze whether the mark '&' starts a HTML entity.
3661
 * If so, update its flags as well as flags of corresponding closer ';'. */
3662
static void
3663
md_analyze_entity(MD_CTX* ctx, int mark_index)
3664
0
{
3665
0
    MD_MARK* opener = &ctx->marks[mark_index];
3666
0
    MD_MARK* closer;
3667
0
    OFF off;
3668
3669
    /* Cannot be entity if there is no closer as the next mark.
3670
     * (Any other mark between would mean strange character which cannot be
3671
     * part of the entity.
3672
     *
3673
     * So we can do all the work on '&' and do not call this later for the
3674
     * closing mark ';'.
3675
     */
3676
0
    if(mark_index + 1 >= ctx->n_marks)
3677
0
        return;
3678
0
    closer = &ctx->marks[mark_index+1];
3679
0
    if(closer->ch != ';')
3680
0
        return;
3681
3682
0
    if(md_is_entity(ctx, opener->beg, closer->end, &off)) {
3683
0
        MD_ASSERT(off == closer->end);
3684
3685
0
        md_resolve_range(ctx, mark_index, mark_index+1);
3686
0
        opener->end = closer->end;
3687
0
    }
3688
0
}
3689
3690
static void
3691
md_analyze_table_cell_boundary(MD_CTX* ctx, int mark_index)
3692
0
{
3693
0
    MD_MARK* mark = &ctx->marks[mark_index];
3694
0
    mark->flags |= MD_MARK_RESOLVED;
3695
0
    mark->next = -1;
3696
3697
0
    if(ctx->table_cell_boundaries_head < 0)
3698
0
        ctx->table_cell_boundaries_head = mark_index;
3699
0
    else
3700
0
        ctx->marks[ctx->table_cell_boundaries_tail].next = mark_index;
3701
0
    ctx->table_cell_boundaries_tail = mark_index;
3702
0
    ctx->n_table_cell_boundaries++;
3703
0
}
3704
3705
/* Split a longer mark into two. The new mark takes the given count of
3706
 * characters. May only be called if an adequate number of dummy 'D' marks
3707
 * follows.
3708
 */
3709
static int
3710
md_split_emph_mark(MD_CTX* ctx, int mark_index, SZ n)
3711
0
{
3712
0
    MD_MARK* mark = &ctx->marks[mark_index];
3713
0
    int new_mark_index = mark_index + (mark->end - mark->beg - n);
3714
0
    MD_MARK* dummy = &ctx->marks[new_mark_index];
3715
3716
0
    MD_ASSERT(mark->end - mark->beg > n);
3717
0
    MD_ASSERT(dummy->ch == 'D');
3718
3719
0
    memcpy(dummy, mark, sizeof(MD_MARK));
3720
0
    mark->end -= n;
3721
0
    dummy->beg = mark->end;
3722
3723
0
    return new_mark_index;
3724
0
}
3725
3726
static void
3727
md_analyze_emph(MD_CTX* ctx, int mark_index)
3728
0
{
3729
0
    MD_MARK* mark = &ctx->marks[mark_index];
3730
3731
    /* If we can be a closer, try to resolve with the preceding opener. */
3732
0
    if(mark->flags & MD_MARK_POTENTIAL_CLOSER) {
3733
0
        MD_MARK* opener = NULL;
3734
0
        int opener_index = 0;
3735
0
        MD_MARKSTACK* opener_stacks[6];
3736
0
        int i, n_opener_stacks;
3737
0
        unsigned flags = mark->flags;
3738
3739
0
        n_opener_stacks = 0;
3740
3741
        /* Apply the rule of 3 */
3742
0
        opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_0 | MD_MARK_EMPH_OC);
3743
0
        if((flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_2)
3744
0
            opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_1 | MD_MARK_EMPH_OC);
3745
0
        if((flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_1)
3746
0
            opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_2 | MD_MARK_EMPH_OC);
3747
0
        opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_0);
3748
0
        if(!(flags & MD_MARK_EMPH_OC)  ||  (flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_2)
3749
0
            opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_1);
3750
0
        if(!(flags & MD_MARK_EMPH_OC)  ||  (flags & MD_MARK_EMPH_MOD3_MASK) != MD_MARK_EMPH_MOD3_1)
3751
0
            opener_stacks[n_opener_stacks++] = md_emph_stack(ctx, mark->ch, MD_MARK_EMPH_MOD3_2);
3752
3753
        /* Opener is the most recent mark from the allowed stacks. */
3754
0
        for(i = 0; i < n_opener_stacks; i++) {
3755
0
            if(opener_stacks[i]->top >= 0) {
3756
0
                int m_index = opener_stacks[i]->top;
3757
0
                MD_MARK* m = &ctx->marks[m_index];
3758
3759
0
                if(opener == NULL  ||  m->end > opener->end) {
3760
0
                    opener_index = m_index;
3761
0
                    opener = m;
3762
0
                }
3763
0
            }
3764
0
        }
3765
3766
        /* Resolve, if we have found matching opener. */
3767
0
        if(opener != NULL) {
3768
0
            SZ opener_size = opener->end - opener->beg;
3769
0
            SZ closer_size = mark->end - mark->beg;
3770
0
            MD_MARKSTACK* stack = md_opener_stack(ctx, opener_index);
3771
3772
0
            if(opener_size > closer_size) {
3773
0
                opener_index = md_split_emph_mark(ctx, opener_index, closer_size);
3774
0
                md_mark_stack_push(ctx, stack, opener_index);
3775
0
            } else if(opener_size < closer_size) {
3776
0
                md_split_emph_mark(ctx, mark_index, closer_size - opener_size);
3777
0
            }
3778
3779
0
            md_pop_openers(ctx, opener_index);
3780
0
            md_resolve_range(ctx, opener_index, mark_index);
3781
0
            return;
3782
0
        }
3783
0
    }
3784
3785
    /* If we could not resolve as closer, we may be yet be an opener. */
3786
0
    if(mark->flags & MD_MARK_POTENTIAL_OPENER)
3787
0
        md_mark_stack_push(ctx, md_emph_stack(ctx, mark->ch, mark->flags), mark_index);
3788
0
}
3789
3790
static void
3791
md_analyze_tilde(MD_CTX* ctx, int mark_index)
3792
0
{
3793
0
    MD_MARK* mark = &ctx->marks[mark_index];
3794
0
    MD_MARKSTACK* stack = md_opener_stack(ctx, mark_index);
3795
3796
    /* We attempt to be Github Flavored Markdown compatible here. GFM accepts
3797
     * only tildes sequences of length 1 and 2, and the length of the opener
3798
     * and closer has to match. */
3799
3800
0
    if((mark->flags & MD_MARK_POTENTIAL_CLOSER)  &&  stack->top >= 0) {
3801
0
        int opener_index = stack->top;
3802
3803
0
        md_pop_openers(ctx, opener_index);
3804
0
        md_resolve_range(ctx, opener_index, mark_index);
3805
0
        return;
3806
0
    }
3807
3808
0
    if(mark->flags & MD_MARK_POTENTIAL_OPENER)
3809
0
        md_mark_stack_push(ctx, stack, mark_index);
3810
0
}
3811
3812
static void
3813
md_analyze_dollar(MD_CTX* ctx, int mark_index)
3814
0
{
3815
0
    MD_MARK* mark = &ctx->marks[mark_index];
3816
3817
0
    if((mark->flags & MD_MARK_POTENTIAL_CLOSER)  &&  DOLLAR_OPENERS.top >= 0) {
3818
        /* If the potential closer has a non-matching number of $, discard */
3819
0
        MD_MARK* opener = &ctx->marks[DOLLAR_OPENERS.top];
3820
0
        int opener_index = DOLLAR_OPENERS.top;
3821
0
        MD_MARK* closer = mark;
3822
0
        int closer_index = mark_index;
3823
3824
0
        if(opener->end - opener->beg == closer->end - closer->beg) {
3825
            /* We are the matching closer */
3826
0
            md_pop_openers(ctx, opener_index);
3827
0
            md_disable_marks(ctx, opener_index+1, closer_index);
3828
0
            md_resolve_range(ctx, opener_index, closer_index);
3829
3830
            /* Discard all pending openers: Latex math span do not allow
3831
             * nesting. */
3832
0
            DOLLAR_OPENERS.top = -1;
3833
0
            return;
3834
0
        }
3835
0
    }
3836
3837
0
    if(mark->flags & MD_MARK_POTENTIAL_OPENER)
3838
0
        md_mark_stack_push(ctx, &DOLLAR_OPENERS, mark_index);
3839
0
}
3840
3841
static MD_MARK*
3842
md_scan_left_for_resolved_mark(MD_CTX* ctx, MD_MARK* mark_from, OFF off, MD_MARK** p_cursor)
3843
0
{
3844
0
    MD_MARK* mark;
3845
3846
0
    for(mark = mark_from; mark >= ctx->marks; mark--) {
3847
0
        if(mark->ch == 'D'  ||  mark->beg > off)
3848
0
            continue;
3849
0
        if(mark->beg <= off  &&  off < mark->end  &&  (mark->flags & MD_MARK_RESOLVED)) {
3850
0
            if(p_cursor != NULL)
3851
0
                *p_cursor = mark;
3852
0
            return mark;
3853
0
        }
3854
0
        if(mark->end <= off)
3855
0
            break;
3856
0
    }
3857
3858
0
    if(p_cursor != NULL)
3859
0
        *p_cursor = mark;
3860
0
    return NULL;
3861
0
}
3862
3863
static MD_MARK*
3864
md_scan_right_for_resolved_mark(MD_CTX* ctx, MD_MARK* mark_from, OFF off, MD_MARK** p_cursor)
3865
0
{
3866
0
    MD_MARK* mark;
3867
3868
0
    for(mark = mark_from; mark < ctx->marks + ctx->n_marks; mark++) {
3869
0
        if(mark->ch == 'D'  ||  mark->end <= off)
3870
0
            continue;
3871
0
        if(mark->beg <= off  &&  off < mark->end  &&  (mark->flags & MD_MARK_RESOLVED)) {
3872
0
            if(p_cursor != NULL)
3873
0
                *p_cursor = mark;
3874
0
            return mark;
3875
0
        }
3876
0
        if(mark->beg > off)
3877
0
            break;
3878
0
    }
3879
3880
0
    if(p_cursor != NULL)
3881
0
        *p_cursor = mark;
3882
0
    return NULL;
3883
0
}
3884
3885
static void
3886
md_analyze_permissive_autolink(MD_CTX* ctx, int mark_index)
3887
0
{
3888
0
    static const struct {
3889
0
        const MD_CHAR start_char;
3890
0
        const MD_CHAR delim_char;
3891
0
        const MD_CHAR* allowed_nonalnum_chars_inside;
3892
0
        const MD_CHAR* allowed_nonalnum_chars_anywhere;
3893
0
        int min_components;
3894
0
        const MD_CHAR optional_end_char;
3895
0
    } URL_MAP[] = {
3896
0
        { _T('\0'), _T('.'),  _T(".-_"),      _T(""),   2, _T('\0') },    /* host, mandatory */
3897
0
        { _T('/'),  _T('/'),  _T("/._"),      _T("+-"), 0, _T('/') },     /* path */
3898
0
        { _T('?'),  _T('&'),  _T("&.-+_=()"), _T(""),   1, _T('\0') },    /* query */
3899
0
        { _T('#'),  _T('\0'), _T(".-+_") ,    _T(""),   1, _T('\0') }     /* fragment */
3900
0
    };
3901
3902
0
    MD_MARK* opener = &ctx->marks[mark_index];
3903
0
    MD_MARK* closer = &ctx->marks[mark_index + 1];  /* The dummy. */
3904
0
    OFF line_beg = closer->beg;     /* md_collect_mark() set this for us */
3905
0
    OFF line_end = closer->end;     /* ditto */
3906
0
    OFF beg = opener->beg;
3907
0
    OFF end = opener->end;
3908
0
    MD_MARK* left_cursor = opener;
3909
0
    int left_boundary_ok = FALSE;
3910
0
    MD_MARK* right_cursor = opener;
3911
0
    int right_boundary_ok = FALSE;
3912
0
    unsigned i;
3913
3914
0
    MD_ASSERT(closer->ch == 'D');
3915
3916
0
    if(opener->ch == '@') {
3917
0
        MD_ASSERT(CH(opener->beg) == _T('@'));
3918
3919
        /* Scan backwards for the user name (before '@'). */
3920
0
        while(beg > line_beg) {
3921
0
            if(ISALNUM(beg-1))
3922
0
                beg--;
3923
0
            else if(beg >= line_beg+2  &&  ISALNUM(beg-2)  &&
3924
0
                        ISANYOF(beg-1, _T(".-_+"))  &&
3925
0
                        md_scan_left_for_resolved_mark(ctx, left_cursor, beg-1, &left_cursor) == NULL  &&
3926
0
                        ISALNUM(beg))
3927
0
                beg--;
3928
0
            else
3929
0
                break;
3930
0
        }
3931
0
        if(beg == opener->beg)      /* empty user name */
3932
0
            return;
3933
0
    }
3934
3935
    /* Verify there's line boundary, whitespace, allowed punctuation or
3936
     * resolved emphasis mark just before the suspected autolink. */
3937
0
    if(beg == line_beg  ||  ISUNICODEWHITESPACEBEFORE(beg)  ||  ISANYOF(beg-1, _T("({["))) {
3938
0
        left_boundary_ok = TRUE;
3939
0
    } else if(ISANYOF(beg-1, _T("*_~"))) {
3940
0
        MD_MARK* left_mark;
3941
3942
0
        left_mark = md_scan_left_for_resolved_mark(ctx, left_cursor, beg-1, &left_cursor);
3943
0
        if(left_mark != NULL  &&  (left_mark->flags & MD_MARK_OPENER))
3944
0
            left_boundary_ok = TRUE;
3945
0
    }
3946
0
    if(!left_boundary_ok)
3947
0
        return;
3948
3949
0
    for(i = 0; i < SIZEOF_ARRAY(URL_MAP); i++) {
3950
0
        int n_components = 0;
3951
0
        int n_open_brackets = 0;
3952
0
        int component_len = 0;
3953
3954
0
        if(URL_MAP[i].start_char != _T('\0')) {
3955
0
            if(end >= line_end  ||  CH(end) != URL_MAP[i].start_char)
3956
0
                continue;
3957
0
            if(URL_MAP[i].min_components > 0  &&  (end+1 >= line_end  ||  !ISALNUM(end+1)))
3958
0
                continue;
3959
0
            end++;
3960
0
        }
3961
3962
0
        while(end < line_end) {
3963
0
            if(ISALNUM(end)  ||  ISANYOF(end, URL_MAP[i].allowed_nonalnum_chars_anywhere)) {
3964
0
                if(n_components == 0)
3965
0
                    n_components++;
3966
0
                component_len++;
3967
0
                end++;
3968
0
            } else if(component_len > 0  &&  CH(end) == URL_MAP[i].delim_char  &&  end+1 < line_end  &&
3969
0
                      (ISALNUM(end+1)  ||  ISANYOF(end+1, URL_MAP[i].allowed_nonalnum_chars_anywhere))) {
3970
0
                n_components++;
3971
0
                component_len = 0;
3972
0
                end++;
3973
0
            } else if(ISANYOF(end, URL_MAP[i].allowed_nonalnum_chars_inside)  &&
3974
0
                      md_scan_right_for_resolved_mark(ctx, right_cursor, end, &right_cursor) == NULL  &&
3975
0
                      ((end > line_beg && (ISALNUM(end-1) || CH(end-1) == _T(')')))  ||  CH(end) == _T('('))  &&
3976
0
                      ((end+1 < line_end && (ISALNUM(end+1) || CH(end+1) == _T('(')))  ||  CH(end) == _T(')')))
3977
0
            {
3978
                /* brackets have to be balanced. */
3979
0
                if(CH(end) == _T('(')) {
3980
0
                    n_open_brackets++;
3981
0
                } else if(CH(end) == _T(')')) {
3982
0
                    if(n_open_brackets <= 0)
3983
0
                        break;
3984
0
                    n_open_brackets--;
3985
0
                }
3986
3987
0
                component_len++;
3988
0
                end++;
3989
0
            } else {
3990
0
                break;
3991
0
            }
3992
0
        }
3993
3994
0
        if(end < line_end  &&  URL_MAP[i].optional_end_char != _T('\0')  &&
3995
0
                CH(end) == URL_MAP[i].optional_end_char)
3996
0
            end++;
3997
3998
0
        if(n_components < URL_MAP[i].min_components  ||  n_open_brackets != 0)
3999
0
            return;
4000
4001
0
        if(opener->ch == '@')   /* E-mail autolinks wants only the host. */
4002
0
            break;
4003
0
    }
4004
4005
    /* Verify there's line boundary, whitespace, allowed punctuation or
4006
     * resolved emphasis mark just after the suspected autolink. */
4007
0
    if(end == line_end  ||  ISUNICODEWHITESPACE(end)  ||  ISANYOF(end, _T(")}].!?,;"))) {
4008
0
        right_boundary_ok = TRUE;
4009
0
    } else {
4010
0
        MD_MARK* right_mark;
4011
4012
0
        right_mark = md_scan_right_for_resolved_mark(ctx, right_cursor, end, &right_cursor);
4013
0
        if(right_mark != NULL  &&  (right_mark->flags & MD_MARK_CLOSER))
4014
0
            right_boundary_ok = TRUE;
4015
0
    }
4016
0
    if(!right_boundary_ok)
4017
0
        return;
4018
4019
    /* Success, we are an autolink. */
4020
0
    opener->beg = beg;
4021
0
    opener->end = beg;
4022
0
    closer->beg = end;
4023
0
    closer->end = end;
4024
0
    closer->ch = opener->ch;
4025
0
    md_resolve_range(ctx, mark_index, mark_index + 1);
4026
0
}
4027
4028
0
#define MD_ANALYZE_NOSKIP_EMPH  0x01
4029
4030
static inline void
4031
md_analyze_marks(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines,
4032
                 int mark_beg, int mark_end, const CHAR* mark_chars, unsigned flags)
4033
0
{
4034
0
    int i = mark_beg;
4035
0
    OFF last_end = lines[0].beg;
4036
4037
0
    MD_UNUSED(lines);
4038
0
    MD_UNUSED(n_lines);
4039
4040
0
    while(i < mark_end) {
4041
0
        MD_MARK* mark = &ctx->marks[i];
4042
4043
        /* Skip resolved spans. */
4044
0
        if(mark->flags & MD_MARK_RESOLVED) {
4045
0
            if((mark->flags & MD_MARK_OPENER)  &&
4046
0
               !((flags & MD_ANALYZE_NOSKIP_EMPH) && ISANYOF_(mark->ch, "*_~")))
4047
0
            {
4048
0
                MD_ASSERT(i < mark->next);
4049
0
                i = mark->next + 1;
4050
0
            } else {
4051
0
                i++;
4052
0
            }
4053
0
            continue;
4054
0
        }
4055
4056
        /* Skip marks we do not want to deal with. */
4057
0
        if(!ISANYOF_(mark->ch, mark_chars)) {
4058
0
            i++;
4059
0
            continue;
4060
0
        }
4061
4062
        /* The resolving in previous step could have expanded a mark. */
4063
0
        if(mark->beg < last_end) {
4064
0
            i++;
4065
0
            continue;
4066
0
        }
4067
4068
        /* Analyze the mark. */
4069
0
        switch(mark->ch) {
4070
0
            case '[':   /* Pass through. */
4071
0
            case '!':   /* Pass through. */
4072
0
            case ']':   md_analyze_bracket(ctx, i); break;
4073
0
            case '&':   md_analyze_entity(ctx, i); break;
4074
0
            case '|':   md_analyze_table_cell_boundary(ctx, i); break;
4075
0
            case '_':   /* Pass through. */
4076
0
            case '*':   md_analyze_emph(ctx, i); break;
4077
0
            case '~':   md_analyze_tilde(ctx, i); break;
4078
0
            case '$':   md_analyze_dollar(ctx, i); break;
4079
0
            case '.':   /* Pass through. */
4080
0
            case ':':   /* Pass through. */
4081
0
            case '@':   md_analyze_permissive_autolink(ctx, i); break;
4082
0
        }
4083
4084
0
        if(mark->flags & MD_MARK_RESOLVED) {
4085
0
            if(mark->flags & MD_MARK_OPENER)
4086
0
                last_end = ctx->marks[mark->next].end;
4087
0
            else
4088
0
                last_end = mark->end;
4089
0
        }
4090
4091
0
        i++;
4092
0
    }
4093
0
}
4094
4095
/* Analyze marks (build ctx->marks). */
4096
static int
4097
md_analyze_inlines(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines, int table_mode)
4098
0
{
4099
0
    int ret;
4100
4101
    /* Reset the previously collected stack of marks. */
4102
0
    ctx->n_marks = 0;
4103
4104
    /* Collect all marks. */
4105
0
    MD_CHECK(md_collect_marks(ctx, lines, n_lines, table_mode));
4106
4107
    /* (1) Links. */
4108
0
    md_analyze_marks(ctx, lines, n_lines, 0, ctx->n_marks, _T("[]!"), 0);
4109
0
    MD_CHECK(md_resolve_links(ctx, lines, n_lines));
4110
0
    BRACKET_OPENERS.top = -1;
4111
0
    ctx->unresolved_link_head = -1;
4112
0
    ctx->unresolved_link_tail = -1;
4113
4114
0
    if(table_mode) {
4115
        /* (2) Analyze table cell boundaries. */
4116
0
        MD_ASSERT(n_lines == 1);
4117
0
        ctx->n_table_cell_boundaries = 0;
4118
0
        md_analyze_marks(ctx, lines, n_lines, 0, ctx->n_marks, _T("|"), 0);
4119
0
        return ret;
4120
0
    }
4121
4122
    /* (3) Emphasis and strong emphasis; permissive autolinks. */
4123
0
    md_analyze_link_contents(ctx, lines, n_lines, 0, ctx->n_marks);
4124
4125
0
abort:
4126
0
    return ret;
4127
0
}
4128
4129
static void
4130
md_analyze_link_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines,
4131
                         int mark_beg, int mark_end)
4132
0
{
4133
0
    int i;
4134
4135
0
    md_analyze_marks(ctx, lines, n_lines, mark_beg, mark_end, _T("&"), 0);
4136
0
    md_analyze_marks(ctx, lines, n_lines, mark_beg, mark_end, _T("*_~$"), 0);
4137
4138
0
    if((ctx->parser.flags & MD_FLAG_PERMISSIVEAUTOLINKS) != 0) {
4139
        /* These have to be processed last, as they may be greedy and expand
4140
         * from their original mark. Also their implementation must be careful
4141
         * not to cross any (previously) resolved marks when doing so. */
4142
0
        md_analyze_marks(ctx, lines, n_lines, mark_beg, mark_end, _T("@:."), MD_ANALYZE_NOSKIP_EMPH);
4143
0
    }
4144
4145
0
    for(i = 0; i < (int) SIZEOF_ARRAY(ctx->opener_stacks); i++)
4146
0
        ctx->opener_stacks[i].top = -1;
4147
0
}
4148
4149
static int
4150
md_enter_leave_span_a(MD_CTX* ctx, int enter, MD_SPANTYPE type,
4151
                      const CHAR* dest, SZ dest_size, int is_autolink,
4152
                      const CHAR* title, SZ title_size)
4153
0
{
4154
0
    MD_ATTRIBUTE_BUILD href_build = { 0 };
4155
0
    MD_ATTRIBUTE_BUILD title_build = { 0 };
4156
0
    MD_SPAN_A_DETAIL det;
4157
0
    int ret = 0;
4158
4159
    /* Note we here rely on fact that MD_SPAN_A_DETAIL and
4160
     * MD_SPAN_IMG_DETAIL are binary-compatible. */
4161
0
    memset(&det, 0, sizeof(MD_SPAN_A_DETAIL));
4162
0
    MD_CHECK(md_build_attribute(ctx, dest, dest_size,
4163
0
                    (is_autolink ? MD_BUILD_ATTR_NO_ESCAPES : 0),
4164
0
                    &det.href, &href_build));
4165
0
    MD_CHECK(md_build_attribute(ctx, title, title_size, 0, &det.title, &title_build));
4166
0
    det.is_autolink = is_autolink;
4167
0
    if(enter)
4168
0
        MD_ENTER_SPAN(type, &det);
4169
0
    else
4170
0
        MD_LEAVE_SPAN(type, &det);
4171
4172
0
abort:
4173
0
    md_free_attribute(ctx, &href_build);
4174
0
    md_free_attribute(ctx, &title_build);
4175
0
    return ret;
4176
0
}
4177
4178
static int
4179
md_enter_leave_span_wikilink(MD_CTX* ctx, int enter, const CHAR* target, SZ target_size)
4180
0
{
4181
0
    MD_ATTRIBUTE_BUILD target_build = { 0 };
4182
0
    MD_SPAN_WIKILINK_DETAIL det;
4183
0
    int ret = 0;
4184
4185
0
    memset(&det, 0, sizeof(MD_SPAN_WIKILINK_DETAIL));
4186
0
    MD_CHECK(md_build_attribute(ctx, target, target_size, 0, &det.target, &target_build));
4187
4188
0
    if (enter)
4189
0
        MD_ENTER_SPAN(MD_SPAN_WIKILINK, &det);
4190
0
    else
4191
0
        MD_LEAVE_SPAN(MD_SPAN_WIKILINK, &det);
4192
4193
0
abort:
4194
0
    md_free_attribute(ctx, &target_build);
4195
0
    return ret;
4196
0
}
4197
4198
4199
/* Render the output, accordingly to the analyzed ctx->marks. */
4200
static int
4201
md_process_inlines(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines)
4202
0
{
4203
0
    MD_TEXTTYPE text_type;
4204
0
    const MD_LINE* line = lines;
4205
0
    MD_MARK* prev_mark = NULL;
4206
0
    MD_MARK* mark;
4207
0
    OFF off = lines[0].beg;
4208
0
    OFF end = lines[n_lines-1].end;
4209
0
    OFF tmp;
4210
0
    int enforce_hardbreak = 0;
4211
0
    int ret = 0;
4212
4213
    /* Find first resolved mark. Note there is always at least one resolved
4214
     * mark,  the dummy last one after the end of the latest line we actually
4215
     * never really reach. This saves us of a lot of special checks and cases
4216
     * in this function. */
4217
0
    mark = ctx->marks;
4218
0
    while(!(mark->flags & MD_MARK_RESOLVED))
4219
0
        mark++;
4220
4221
0
    text_type = MD_TEXT_NORMAL;
4222
4223
0
    while(1) {
4224
        /* Process the text up to the next mark or end-of-line. */
4225
0
        tmp = (line->end < mark->beg ? line->end : mark->beg);
4226
0
        if(tmp > off) {
4227
0
            MD_TEXT(text_type, STR(off), tmp - off);
4228
0
            off = tmp;
4229
0
        }
4230
4231
        /* If reached the mark, process it and move to next one. */
4232
0
        if(off >= mark->beg) {
4233
0
            switch(mark->ch) {
4234
0
                case '\\':      /* Backslash escape. */
4235
0
                    if(ISNEWLINE(mark->beg+1))
4236
0
                        enforce_hardbreak = 1;
4237
0
                    else
4238
0
                        MD_TEXT(text_type, STR(mark->beg+1), 1);
4239
0
                    break;
4240
4241
0
                case ' ':       /* Non-trivial space. */
4242
0
                    MD_TEXT(text_type, _T(" "), 1);
4243
0
                    break;
4244
4245
0
                case '`':       /* Code span. */
4246
0
                    if(mark->flags & MD_MARK_OPENER) {
4247
0
                        MD_ENTER_SPAN(MD_SPAN_CODE, NULL);
4248
0
                        text_type = MD_TEXT_CODE;
4249
0
                    } else {
4250
0
                        MD_LEAVE_SPAN(MD_SPAN_CODE, NULL);
4251
0
                        text_type = MD_TEXT_NORMAL;
4252
0
                    }
4253
0
                    break;
4254
4255
0
                case '_':       /* Underline (or emphasis if we fall through). */
4256
0
                    if(ctx->parser.flags & MD_FLAG_UNDERLINE) {
4257
0
                        if(mark->flags & MD_MARK_OPENER) {
4258
0
                            while(off < mark->end) {
4259
0
                                MD_ENTER_SPAN(MD_SPAN_U, NULL);
4260
0
                                off++;
4261
0
                            }
4262
0
                        } else {
4263
0
                            while(off < mark->end) {
4264
0
                                MD_LEAVE_SPAN(MD_SPAN_U, NULL);
4265
0
                                off++;
4266
0
                            }
4267
0
                        }
4268
0
                        break;
4269
0
                    }
4270
0
                    MD_FALLTHROUGH();
4271
4272
0
                case '*':       /* Emphasis, strong emphasis. */
4273
0
                    if(mark->flags & MD_MARK_OPENER) {
4274
0
                        if((mark->end - off) % 2) {
4275
0
                            MD_ENTER_SPAN(MD_SPAN_EM, NULL);
4276
0
                            off++;
4277
0
                        }
4278
0
                        while(off + 1 < mark->end) {
4279
0
                            MD_ENTER_SPAN(MD_SPAN_STRONG, NULL);
4280
0
                            off += 2;
4281
0
                        }
4282
0
                    } else {
4283
0
                        while(off + 1 < mark->end) {
4284
0
                            MD_LEAVE_SPAN(MD_SPAN_STRONG, NULL);
4285
0
                            off += 2;
4286
0
                        }
4287
0
                        if((mark->end - off) % 2) {
4288
0
                            MD_LEAVE_SPAN(MD_SPAN_EM, NULL);
4289
0
                            off++;
4290
0
                        }
4291
0
                    }
4292
0
                    break;
4293
4294
0
                case '~':
4295
0
                    if(mark->flags & MD_MARK_OPENER)
4296
0
                        MD_ENTER_SPAN(MD_SPAN_DEL, NULL);
4297
0
                    else
4298
0
                        MD_LEAVE_SPAN(MD_SPAN_DEL, NULL);
4299
0
                    break;
4300
4301
0
                case '$':
4302
0
                    if(mark->flags & MD_MARK_OPENER) {
4303
0
                        MD_ENTER_SPAN((mark->end - off) % 2 ? MD_SPAN_LATEXMATH : MD_SPAN_LATEXMATH_DISPLAY, NULL);
4304
0
                        text_type = MD_TEXT_LATEXMATH;
4305
0
                    } else {
4306
0
                        MD_LEAVE_SPAN((mark->end - off) % 2 ? MD_SPAN_LATEXMATH : MD_SPAN_LATEXMATH_DISPLAY, NULL);
4307
0
                        text_type = MD_TEXT_NORMAL;
4308
0
                    }
4309
0
                    break;
4310
4311
0
                case '[':       /* Link, wiki link, image. */
4312
0
                case '!':
4313
0
                case ']':
4314
0
                {
4315
0
                    const MD_MARK* opener = (mark->ch != ']' ? mark : &ctx->marks[mark->prev]);
4316
0
                    const MD_MARK* closer = &ctx->marks[opener->next];
4317
0
                    const MD_MARK* dest_mark;
4318
0
                    const MD_MARK* title_mark;
4319
4320
0
                    if ((opener->ch == '[' && closer->ch == ']') &&
4321
0
                        opener->end - opener->beg >= 2 &&
4322
0
                        closer->end - closer->beg >= 2)
4323
0
                    {
4324
0
                        int has_label = (opener->end - opener->beg > 2);
4325
0
                        SZ target_sz;
4326
4327
0
                        if(has_label)
4328
0
                            target_sz = opener->end - (opener->beg+2);
4329
0
                        else
4330
0
                            target_sz = closer->beg - opener->end;
4331
4332
0
                        MD_CHECK(md_enter_leave_span_wikilink(ctx, (mark->ch != ']'),
4333
0
                                 has_label ? STR(opener->beg+2) : STR(opener->end),
4334
0
                                 target_sz));
4335
4336
0
                        break;
4337
0
                    }
4338
4339
0
                    dest_mark = opener+1;
4340
0
                    MD_ASSERT(dest_mark->ch == 'D');
4341
0
                    title_mark = opener+2;
4342
0
                    MD_ASSERT(title_mark->ch == 'D');
4343
4344
0
                    MD_CHECK(md_enter_leave_span_a(ctx, (mark->ch != ']'),
4345
0
                                (opener->ch == '!' ? MD_SPAN_IMG : MD_SPAN_A),
4346
0
                                STR(dest_mark->beg), dest_mark->end - dest_mark->beg, FALSE,
4347
0
                                md_mark_get_ptr(ctx, (int)(title_mark - ctx->marks)),
4348
0
                title_mark->prev));
4349
4350
                    /* link/image closer may span multiple lines. */
4351
0
                    if(mark->ch == ']') {
4352
0
                        while(mark->end > line->end)
4353
0
                            line++;
4354
0
                    }
4355
4356
0
                    break;
4357
0
                }
4358
4359
0
                case '<':
4360
0
                case '>':       /* Autolink or raw HTML. */
4361
0
                    if(!(mark->flags & MD_MARK_AUTOLINK)) {
4362
                        /* Raw HTML. */
4363
0
                        if(mark->flags & MD_MARK_OPENER)
4364
0
                            text_type = MD_TEXT_HTML;
4365
0
                        else
4366
0
                            text_type = MD_TEXT_NORMAL;
4367
0
                        break;
4368
0
                    }
4369
                    /* Pass through, if auto-link. */
4370
0
                    MD_FALLTHROUGH();
4371
4372
0
                case '@':       /* Permissive e-mail autolink. */
4373
0
                case ':':       /* Permissive URL autolink. */
4374
0
                case '.':       /* Permissive WWW autolink. */
4375
0
                {
4376
0
                    MD_MARK* opener = ((mark->flags & MD_MARK_OPENER) ? mark : &ctx->marks[mark->prev]);
4377
0
                    MD_MARK* closer = &ctx->marks[opener->next];
4378
0
                    const CHAR* dest = STR(opener->end);
4379
0
                    SZ dest_size = closer->beg - opener->end;
4380
4381
                    /* For permissive auto-links we do not know closer mark
4382
                     * position at the time of md_collect_marks(), therefore
4383
                     * it can be out-of-order in ctx->marks[].
4384
                     *
4385
                     * With this flag, we make sure that we output the closer
4386
                     * only if we processed the opener. */
4387
0
                    if(mark->flags & MD_MARK_OPENER)
4388
0
                        closer->flags |= MD_MARK_VALIDPERMISSIVEAUTOLINK;
4389
4390
0
                    if(opener->ch == '@' || opener->ch == '.' ||
4391
0
                        (opener->ch == '<' && (opener->flags & MD_MARK_AUTOLINK_MISSING_MAILTO)))
4392
0
                    {
4393
0
                        dest_size += 7;
4394
0
                        MD_TEMP_BUFFER(dest_size * sizeof(CHAR));
4395
0
                        memcpy(ctx->buffer,
4396
0
                                (opener->ch == '.' ? _T("http://") : _T("mailto:")),
4397
0
                                7 * sizeof(CHAR));
4398
0
                        memcpy(ctx->buffer + 7, dest, (dest_size-7) * sizeof(CHAR));
4399
0
                        dest = ctx->buffer;
4400
0
                    }
4401
4402
0
                    if(closer->flags & MD_MARK_VALIDPERMISSIVEAUTOLINK)
4403
0
                        MD_CHECK(md_enter_leave_span_a(ctx, (mark->flags & MD_MARK_OPENER),
4404
0
                                    MD_SPAN_A, dest, dest_size, TRUE, NULL, 0));
4405
0
                    break;
4406
0
                }
4407
4408
0
                case '&':       /* Entity. */
4409
0
                    MD_TEXT(MD_TEXT_ENTITY, STR(mark->beg), mark->end - mark->beg);
4410
0
                    break;
4411
4412
0
                case '\0':
4413
0
                    MD_TEXT(MD_TEXT_NULLCHAR, _T(""), 1);
4414
0
                    break;
4415
4416
0
                case 127:
4417
0
                    goto abort;
4418
0
            }
4419
4420
0
            off = mark->end;
4421
4422
            /* Move to next resolved mark. */
4423
0
            prev_mark = mark;
4424
0
            mark++;
4425
0
            while(!(mark->flags & MD_MARK_RESOLVED)  ||  mark->beg < off)
4426
0
                mark++;
4427
0
        }
4428
4429
        /* If reached end of line, move to next one. */
4430
0
        if(off >= line->end) {
4431
            /* If it is the last line, we are done. */
4432
0
            if(off >= end)
4433
0
                break;
4434
4435
0
            if(text_type == MD_TEXT_CODE || text_type == MD_TEXT_LATEXMATH) {
4436
0
                MD_ASSERT(prev_mark != NULL);
4437
0
                MD_ASSERT(ISANYOF2_(prev_mark->ch, '`', '$')  &&  (prev_mark->flags & MD_MARK_OPENER));
4438
0
                MD_ASSERT(ISANYOF2_(mark->ch, '`', '$')  &&  (mark->flags & MD_MARK_CLOSER));
4439
4440
                /* Inside a code span, trailing line whitespace has to be
4441
                 * outputted. */
4442
0
                tmp = off;
4443
0
                while(off < ctx->size  &&  ISBLANK(off))
4444
0
                    off++;
4445
0
                if(off > tmp)
4446
0
                    MD_TEXT(text_type, STR(tmp), off-tmp);
4447
4448
                /* and new lines are transformed into single spaces. */
4449
0
                if(off == line->end)
4450
0
                    MD_TEXT(text_type, _T(" "), 1);
4451
0
            } else if(text_type == MD_TEXT_HTML) {
4452
                /* Inside raw HTML, we output the new line verbatim, including
4453
                 * any trailing spaces. */
4454
0
                tmp = off;
4455
0
                while(tmp < end  &&  ISBLANK(tmp))
4456
0
                    tmp++;
4457
0
                if(tmp > off)
4458
0
                    MD_TEXT(MD_TEXT_HTML, STR(off), tmp - off);
4459
0
                MD_TEXT(MD_TEXT_HTML, _T("\n"), 1);
4460
0
            } else {
4461
                /* Output soft or hard line break. */
4462
0
                MD_TEXTTYPE break_type = MD_TEXT_SOFTBR;
4463
4464
0
                if(text_type == MD_TEXT_NORMAL) {
4465
0
                    if(enforce_hardbreak  ||  (ctx->parser.flags & MD_FLAG_HARD_SOFT_BREAKS)) {
4466
0
                        break_type = MD_TEXT_BR;
4467
0
                    } else {
4468
0
                        while(off < ctx->size  &&  ISBLANK(off))
4469
0
                            off++;
4470
0
                        if(off >= line->end + 2  &&  CH(off-2) == _T(' ')  &&  CH(off-1) == _T(' ')  &&  ISNEWLINE(off))
4471
0
                            break_type = MD_TEXT_BR;
4472
0
                    }
4473
0
                }
4474
4475
0
                MD_TEXT(break_type, _T("\n"), 1);
4476
0
            }
4477
4478
            /* Move to the next line. */
4479
0
            line++;
4480
0
            off = MAX(off, line->beg);
4481
4482
0
            enforce_hardbreak = 0;
4483
0
        }
4484
0
    }
4485
4486
0
abort:
4487
0
    return ret;
4488
0
}
4489
4490
4491
/***************************
4492
 ***  Processing Tables  ***
4493
 ***************************/
4494
4495
static void
4496
md_analyze_table_alignment(MD_CTX* ctx, OFF beg, OFF end, MD_ALIGN* align, int n_align)
4497
0
{
4498
0
    static const MD_ALIGN align_map[] = { MD_ALIGN_DEFAULT, MD_ALIGN_LEFT, MD_ALIGN_RIGHT, MD_ALIGN_CENTER };
4499
0
    OFF off = beg;
4500
4501
0
    while(n_align > 0) {
4502
0
        int index = 0;  /* index into align_map[] */
4503
4504
0
        while(CH(off) != _T('-'))
4505
0
            off++;
4506
0
        if(off > beg  &&  CH(off-1) == _T(':'))
4507
0
            index |= 1;
4508
0
        while(off < end  &&  CH(off) == _T('-'))
4509
0
            off++;
4510
0
        if(off < end  &&  CH(off) == _T(':'))
4511
0
            index |= 2;
4512
4513
0
        *align = align_map[index];
4514
0
        align++;
4515
0
        n_align--;
4516
0
    }
4517
4518
0
}
4519
4520
/* Forward declaration. */
4521
static int md_process_normal_block_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines);
4522
4523
static int
4524
md_process_table_cell(MD_CTX* ctx, MD_BLOCKTYPE cell_type, MD_ALIGN align, OFF beg, OFF end)
4525
0
{
4526
0
    MD_LINE line;
4527
0
    MD_BLOCK_TD_DETAIL det;
4528
0
    int ret = 0;
4529
4530
0
    while(beg < end  &&  ISWHITESPACE(beg))
4531
0
        beg++;
4532
0
    while(end > beg  &&  ISWHITESPACE(end-1))
4533
0
        end--;
4534
4535
0
    det.align = align;
4536
0
    line.beg = beg;
4537
0
    line.end = end;
4538
4539
0
    MD_ENTER_BLOCK(cell_type, &det);
4540
0
    MD_CHECK(md_process_normal_block_contents(ctx, &line, 1));
4541
0
    MD_LEAVE_BLOCK(cell_type, &det);
4542
4543
0
abort:
4544
0
    return ret;
4545
0
}
4546
4547
static int
4548
md_process_table_row(MD_CTX* ctx, MD_BLOCKTYPE cell_type, OFF beg, OFF end,
4549
                     const MD_ALIGN* align, int col_count)
4550
0
{
4551
0
    MD_LINE line;
4552
0
    OFF* pipe_offs = NULL;
4553
0
    int i, j, k, n;
4554
0
    int ret = 0;
4555
4556
0
    line.beg = beg;
4557
0
    line.end = end;
4558
4559
    /* Break the line into table cells by identifying pipe characters who
4560
     * form the cell boundary. */
4561
0
    MD_CHECK(md_analyze_inlines(ctx, &line, 1, TRUE));
4562
4563
    /* We have to remember the cell boundaries in local buffer because
4564
     * ctx->marks[] shall be reused during cell contents processing. */
4565
0
    n = ctx->n_table_cell_boundaries + 2;
4566
0
    pipe_offs = (OFF*) malloc(n * sizeof(OFF));
4567
0
    if(pipe_offs == NULL) {
4568
0
        MD_LOG("malloc() failed.");
4569
0
        ret = -1;
4570
0
        goto abort;
4571
0
    }
4572
0
    j = 0;
4573
0
    pipe_offs[j++] = beg;
4574
0
    for(i = ctx->table_cell_boundaries_head; i >= 0; i = ctx->marks[i].next) {
4575
0
        MD_MARK* mark = &ctx->marks[i];
4576
0
        pipe_offs[j++] = mark->end;
4577
0
    }
4578
0
    pipe_offs[j++] = end+1;
4579
4580
    /* Process cells. */
4581
0
    MD_ENTER_BLOCK(MD_BLOCK_TR, NULL);
4582
0
    k = 0;
4583
0
    for(i = 0; i < j-1  &&  k < col_count; i++) {
4584
0
        if(pipe_offs[i] < pipe_offs[i+1]-1)
4585
0
            MD_CHECK(md_process_table_cell(ctx, cell_type, align[k++], pipe_offs[i], pipe_offs[i+1]-1));
4586
0
    }
4587
    /* Make sure we call enough table cells even if the current table contains
4588
     * too few of them. */
4589
0
    while(k < col_count)
4590
0
        MD_CHECK(md_process_table_cell(ctx, cell_type, align[k++], 0, 0));
4591
0
    MD_LEAVE_BLOCK(MD_BLOCK_TR, NULL);
4592
4593
0
abort:
4594
0
    free(pipe_offs);
4595
4596
0
    ctx->table_cell_boundaries_head = -1;
4597
0
    ctx->table_cell_boundaries_tail = -1;
4598
4599
0
    return ret;
4600
0
}
4601
4602
static int
4603
md_process_table_block_contents(MD_CTX* ctx, int col_count, const MD_LINE* lines, MD_SIZE n_lines)
4604
0
{
4605
0
    MD_ALIGN* align;
4606
0
    MD_SIZE line_index;
4607
0
    int ret = 0;
4608
4609
    /* At least two lines have to be present: The column headers and the line
4610
     * with the underlines. */
4611
0
    MD_ASSERT(n_lines >= 2);
4612
4613
0
    align = malloc(col_count * sizeof(MD_ALIGN));
4614
0
    if(align == NULL) {
4615
0
        MD_LOG("malloc() failed.");
4616
0
        ret = -1;
4617
0
        goto abort;
4618
0
    }
4619
4620
0
    md_analyze_table_alignment(ctx, lines[1].beg, lines[1].end, align, col_count);
4621
4622
0
    MD_ENTER_BLOCK(MD_BLOCK_THEAD, NULL);
4623
0
    MD_CHECK(md_process_table_row(ctx, MD_BLOCK_TH,
4624
0
                        lines[0].beg, lines[0].end, align, col_count));
4625
0
    MD_LEAVE_BLOCK(MD_BLOCK_THEAD, NULL);
4626
4627
0
    if(n_lines > 2) {
4628
0
        MD_ENTER_BLOCK(MD_BLOCK_TBODY, NULL);
4629
0
        for(line_index = 2; line_index < n_lines; line_index++) {
4630
0
            MD_CHECK(md_process_table_row(ctx, MD_BLOCK_TD,
4631
0
                     lines[line_index].beg, lines[line_index].end, align, col_count));
4632
0
        }
4633
0
        MD_LEAVE_BLOCK(MD_BLOCK_TBODY, NULL);
4634
0
    }
4635
4636
0
abort:
4637
0
    free(align);
4638
0
    return ret;
4639
0
}
4640
4641
4642
/**************************
4643
 ***  Processing Block  ***
4644
 **************************/
4645
4646
0
#define MD_BLOCK_CONTAINER_OPENER   0x01
4647
0
#define MD_BLOCK_CONTAINER_CLOSER   0x02
4648
0
#define MD_BLOCK_CONTAINER          (MD_BLOCK_CONTAINER_OPENER | MD_BLOCK_CONTAINER_CLOSER)
4649
0
#define MD_BLOCK_LOOSE_LIST         0x04
4650
0
#define MD_BLOCK_SETEXT_HEADER      0x08
4651
4652
struct MD_BLOCK_tag {
4653
    MD_BLOCKTYPE type  :  8;
4654
    unsigned flags     :  8;
4655
4656
    /* MD_BLOCK_H:      Header level (1 - 6)
4657
     * MD_BLOCK_CODE:   Non-zero if fenced, zero if indented.
4658
     * MD_BLOCK_LI:     Task mark character (0 if not task list item, 'x', 'X' or ' ').
4659
     * MD_BLOCK_TABLE:  Column count (as determined by the table underline).
4660
     */
4661
    unsigned data      : 16;
4662
4663
    /* Leaf blocks:     Count of lines (MD_LINE or MD_VERBATIMLINE) on the block.
4664
     * MD_BLOCK_LI:     Task mark offset in the input doc.
4665
     * MD_BLOCK_OL:     Start item number.
4666
     */
4667
    MD_SIZE n_lines;
4668
};
4669
4670
struct MD_CONTAINER_tag {
4671
    CHAR ch;
4672
    unsigned is_loose    : 8;
4673
    unsigned is_task     : 8;
4674
    unsigned start;
4675
    unsigned mark_indent;
4676
    unsigned contents_indent;
4677
    OFF block_byte_off;
4678
    OFF task_mark_off;
4679
};
4680
4681
4682
static int
4683
md_process_normal_block_contents(MD_CTX* ctx, const MD_LINE* lines, MD_SIZE n_lines)
4684
0
{
4685
0
    int i;
4686
0
    int ret;
4687
4688
0
    MD_CHECK(md_analyze_inlines(ctx, lines, n_lines, FALSE));
4689
0
    MD_CHECK(md_process_inlines(ctx, lines, n_lines));
4690
4691
0
abort:
4692
    /* Free any temporary memory blocks stored within some dummy marks. */
4693
0
    for(i = ctx->ptr_stack.top; i >= 0; i = ctx->marks[i].next)
4694
0
        free(md_mark_get_ptr(ctx, i));
4695
0
    ctx->ptr_stack.top = -1;
4696
4697
0
    return ret;
4698
0
}
4699
4700
static int
4701
md_process_verbatim_block_contents(MD_CTX* ctx, MD_TEXTTYPE text_type, const MD_VERBATIMLINE* lines, MD_SIZE n_lines)
4702
0
{
4703
0
    static const CHAR indent_chunk_str[] = _T("                ");
4704
0
    static const SZ indent_chunk_size = SIZEOF_ARRAY(indent_chunk_str) - 1;
4705
4706
0
    MD_SIZE line_index;
4707
0
    int ret = 0;
4708
4709
0
    for(line_index = 0; line_index < n_lines; line_index++) {
4710
0
        const MD_VERBATIMLINE* line = &lines[line_index];
4711
0
        int indent = line->indent;
4712
4713
0
        MD_ASSERT(indent >= 0);
4714
4715
        /* Output code indentation. */
4716
0
        while(indent > (int) indent_chunk_size) {
4717
0
            MD_TEXT(text_type, indent_chunk_str, indent_chunk_size);
4718
0
            indent -= indent_chunk_size;
4719
0
        }
4720
0
        if(indent > 0)
4721
0
            MD_TEXT(text_type, indent_chunk_str, indent);
4722
4723
        /* Output the code line itself. */
4724
0
        MD_TEXT_INSECURE(text_type, STR(line->beg), line->end - line->beg);
4725
4726
        /* Enforce end-of-line. */
4727
0
        MD_TEXT(text_type, _T("\n"), 1);
4728
0
    }
4729
4730
0
abort:
4731
0
    return ret;
4732
0
}
4733
4734
static int
4735
md_process_code_block_contents(MD_CTX* ctx, int is_fenced, const MD_VERBATIMLINE* lines, MD_SIZE n_lines)
4736
0
{
4737
0
    if(is_fenced) {
4738
        /* Skip the first line in case of fenced code: It is the fence.
4739
         * (Only the starting fence is present due to logic in md_analyze_line().) */
4740
0
        lines++;
4741
0
        n_lines--;
4742
0
    } else {
4743
        /* Ignore blank lines at start/end of indented code block. */
4744
0
        while(n_lines > 0  &&  lines[0].beg == lines[0].end) {
4745
0
            lines++;
4746
0
            n_lines--;
4747
0
        }
4748
0
        while(n_lines > 0  &&  lines[n_lines-1].beg == lines[n_lines-1].end) {
4749
0
            n_lines--;
4750
0
        }
4751
0
    }
4752
4753
0
    if(n_lines == 0)
4754
0
        return 0;
4755
4756
0
    return md_process_verbatim_block_contents(ctx, MD_TEXT_CODE, lines, n_lines);
4757
0
}
4758
4759
static int
4760
md_setup_fenced_code_detail(MD_CTX* ctx, const MD_BLOCK* block, MD_BLOCK_CODE_DETAIL* det,
4761
                            MD_ATTRIBUTE_BUILD* info_build, MD_ATTRIBUTE_BUILD* lang_build)
4762
0
{
4763
0
    const MD_VERBATIMLINE* fence_line = (const MD_VERBATIMLINE*)(block + 1);
4764
0
    OFF beg = fence_line->beg;
4765
0
    OFF end = fence_line->end;
4766
0
    OFF lang_end;
4767
0
    CHAR fence_ch = CH(fence_line->beg);
4768
0
    int ret = 0;
4769
4770
    /* Skip the fence itself. */
4771
0
    while(beg < ctx->size  &&  CH(beg) == fence_ch)
4772
0
        beg++;
4773
    /* Trim initial spaces. */
4774
0
    while(beg < ctx->size  &&  CH(beg) == _T(' '))
4775
0
        beg++;
4776
4777
    /* Trim trailing spaces. */
4778
0
    while(end > beg  &&  CH(end-1) == _T(' '))
4779
0
        end--;
4780
4781
    /* Build info string attribute. */
4782
0
    MD_CHECK(md_build_attribute(ctx, STR(beg), end - beg, 0, &det->info, info_build));
4783
4784
    /* Build info string attribute. */
4785
0
    lang_end = beg;
4786
0
    while(lang_end < end  &&  !ISWHITESPACE(lang_end))
4787
0
        lang_end++;
4788
0
    MD_CHECK(md_build_attribute(ctx, STR(beg), lang_end - beg, 0, &det->lang, lang_build));
4789
4790
0
    det->fence_char = fence_ch;
4791
4792
0
abort:
4793
0
    return ret;
4794
0
}
4795
4796
static int
4797
md_process_leaf_block(MD_CTX* ctx, const MD_BLOCK* block)
4798
0
{
4799
0
    union {
4800
0
        MD_BLOCK_H_DETAIL header;
4801
0
        MD_BLOCK_CODE_DETAIL code;
4802
0
        MD_BLOCK_TABLE_DETAIL table;
4803
0
    } det;
4804
0
    MD_ATTRIBUTE_BUILD info_build = { 0 };
4805
0
    MD_ATTRIBUTE_BUILD lang_build = { 0 };
4806
0
    int is_in_tight_list;
4807
0
    int clean_fence_code_detail = FALSE;
4808
0
    int ret = 0;
4809
4810
0
    memset(&det, 0, sizeof(det));
4811
4812
0
    if(ctx->n_containers == 0)
4813
0
        is_in_tight_list = FALSE;
4814
0
    else
4815
0
        is_in_tight_list = !ctx->containers[ctx->n_containers-1].is_loose;
4816
4817
0
    switch(block->type) {
4818
0
        case MD_BLOCK_H:
4819
0
            det.header.level = block->data;
4820
0
            break;
4821
4822
0
        case MD_BLOCK_CODE:
4823
            /* For fenced code block, we may need to set the info string. */
4824
0
            if(block->data != 0) {
4825
0
                memset(&det.code, 0, sizeof(MD_BLOCK_CODE_DETAIL));
4826
0
                clean_fence_code_detail = TRUE;
4827
0
                MD_CHECK(md_setup_fenced_code_detail(ctx, block, &det.code, &info_build, &lang_build));
4828
0
            }
4829
0
            break;
4830
4831
0
        case MD_BLOCK_TABLE:
4832
0
            det.table.col_count = block->data;
4833
0
            det.table.head_row_count = 1;
4834
0
            det.table.body_row_count = block->n_lines - 2;
4835
0
            break;
4836
4837
0
        default:
4838
            /* Noop. */
4839
0
            break;
4840
0
    }
4841
4842
0
    if(!is_in_tight_list  ||  block->type != MD_BLOCK_P)
4843
0
        MD_ENTER_BLOCK(block->type, (void*) &det);
4844
4845
    /* Process the block contents accordingly to is type. */
4846
0
    switch(block->type) {
4847
0
        case MD_BLOCK_HR:
4848
            /* noop */
4849
0
            break;
4850
4851
0
        case MD_BLOCK_CODE:
4852
0
            MD_CHECK(md_process_code_block_contents(ctx, (block->data != 0),
4853
0
                            (const MD_VERBATIMLINE*)(block + 1), block->n_lines));
4854
0
            break;
4855
4856
0
        case MD_BLOCK_HTML:
4857
0
            MD_CHECK(md_process_verbatim_block_contents(ctx, MD_TEXT_HTML,
4858
0
                            (const MD_VERBATIMLINE*)(block + 1), block->n_lines));
4859
0
            break;
4860
4861
0
        case MD_BLOCK_TABLE:
4862
0
            MD_CHECK(md_process_table_block_contents(ctx, block->data,
4863
0
                            (const MD_LINE*)(block + 1), block->n_lines));
4864
0
            break;
4865
4866
0
        default:
4867
0
            MD_CHECK(md_process_normal_block_contents(ctx,
4868
0
                            (const MD_LINE*)(block + 1), block->n_lines));
4869
0
            break;
4870
0
    }
4871
4872
0
    if(!is_in_tight_list  ||  block->type != MD_BLOCK_P)
4873
0
        MD_LEAVE_BLOCK(block->type, (void*) &det);
4874
4875
0
abort:
4876
0
    if(clean_fence_code_detail) {
4877
0
        md_free_attribute(ctx, &info_build);
4878
0
        md_free_attribute(ctx, &lang_build);
4879
0
    }
4880
0
    return ret;
4881
0
}
4882
4883
static int
4884
md_process_all_blocks(MD_CTX* ctx)
4885
0
{
4886
0
    int byte_off = 0;
4887
0
    int ret = 0;
4888
4889
    /* ctx->containers now is not needed for detection of lists and list items
4890
     * so we reuse it for tracking what lists are loose or tight. We rely
4891
     * on the fact the vector is large enough to hold the deepest nesting
4892
     * level of lists. */
4893
0
    ctx->n_containers = 0;
4894
4895
0
    while(byte_off < ctx->n_block_bytes) {
4896
0
        MD_BLOCK* block = (MD_BLOCK*)((char*)ctx->block_bytes + byte_off);
4897
0
        union {
4898
0
            MD_BLOCK_UL_DETAIL ul;
4899
0
            MD_BLOCK_OL_DETAIL ol;
4900
0
            MD_BLOCK_LI_DETAIL li;
4901
0
        } det;
4902
4903
0
        switch(block->type) {
4904
0
            case MD_BLOCK_UL:
4905
0
                det.ul.is_tight = (block->flags & MD_BLOCK_LOOSE_LIST) ? FALSE : TRUE;
4906
0
                det.ul.mark = (CHAR) block->data;
4907
0
                break;
4908
4909
0
            case MD_BLOCK_OL:
4910
0
                det.ol.start = block->n_lines;
4911
0
                det.ol.is_tight =  (block->flags & MD_BLOCK_LOOSE_LIST) ? FALSE : TRUE;
4912
0
                det.ol.mark_delimiter = (CHAR) block->data;
4913
0
                break;
4914
4915
0
            case MD_BLOCK_LI:
4916
0
                det.li.is_task = (block->data != 0);
4917
0
                det.li.task_mark = (CHAR) block->data;
4918
0
                det.li.task_mark_offset = (OFF) block->n_lines;
4919
0
                break;
4920
4921
0
            default:
4922
                /* noop */
4923
0
                break;
4924
0
        }
4925
4926
0
        if(block->flags & MD_BLOCK_CONTAINER) {
4927
0
            if(block->flags & MD_BLOCK_CONTAINER_CLOSER) {
4928
0
                MD_LEAVE_BLOCK(block->type, &det);
4929
4930
0
                if(block->type == MD_BLOCK_UL || block->type == MD_BLOCK_OL || block->type == MD_BLOCK_QUOTE)
4931
0
                    ctx->n_containers--;
4932
0
            }
4933
4934
0
            if(block->flags & MD_BLOCK_CONTAINER_OPENER) {
4935
0
                MD_ENTER_BLOCK(block->type, &det);
4936
4937
0
                if(block->type == MD_BLOCK_UL || block->type == MD_BLOCK_OL) {
4938
0
                    ctx->containers[ctx->n_containers].is_loose = (block->flags & MD_BLOCK_LOOSE_LIST);
4939
0
                    ctx->n_containers++;
4940
0
                } else if(block->type == MD_BLOCK_QUOTE) {
4941
                    /* This causes that any text in a block quote, even if
4942
                     * nested inside a tight list item, is wrapped with
4943
                     * <p>...</p>. */
4944
0
                    ctx->containers[ctx->n_containers].is_loose = TRUE;
4945
0
                    ctx->n_containers++;
4946
0
                }
4947
0
            }
4948
0
        } else {
4949
0
            MD_CHECK(md_process_leaf_block(ctx, block));
4950
4951
0
            if(block->type == MD_BLOCK_CODE || block->type == MD_BLOCK_HTML)
4952
0
                byte_off += block->n_lines * sizeof(MD_VERBATIMLINE);
4953
0
            else
4954
0
                byte_off += block->n_lines * sizeof(MD_LINE);
4955
0
        }
4956
4957
0
        byte_off += sizeof(MD_BLOCK);
4958
0
    }
4959
4960
0
    ctx->n_block_bytes = 0;
4961
4962
0
abort:
4963
0
    return ret;
4964
0
}
4965
4966
4967
/************************************
4968
 ***  Grouping Lines into Blocks  ***
4969
 ************************************/
4970
4971
static void*
4972
md_push_block_bytes(MD_CTX* ctx, int n_bytes)
4973
0
{
4974
0
    void* ptr;
4975
4976
0
    if(ctx->n_block_bytes + n_bytes > ctx->alloc_block_bytes) {
4977
0
        void* new_block_bytes;
4978
4979
0
        ctx->alloc_block_bytes = (ctx->alloc_block_bytes > 0
4980
0
                ? ctx->alloc_block_bytes + ctx->alloc_block_bytes / 2
4981
0
                : 512);
4982
0
        new_block_bytes = realloc(ctx->block_bytes, ctx->alloc_block_bytes);
4983
0
        if(new_block_bytes == NULL) {
4984
0
            MD_LOG("realloc() failed.");
4985
0
            return NULL;
4986
0
        }
4987
4988
        /* Fix the ->current_block after the reallocation. */
4989
0
        if(ctx->current_block != NULL) {
4990
0
            OFF off_current_block = (OFF) ((char*) ctx->current_block - (char*) ctx->block_bytes);
4991
0
            ctx->current_block = (MD_BLOCK*) ((char*) new_block_bytes + off_current_block);
4992
0
        }
4993
4994
0
        ctx->block_bytes = new_block_bytes;
4995
0
    }
4996
4997
0
    ptr = (char*)ctx->block_bytes + ctx->n_block_bytes;
4998
0
    ctx->n_block_bytes += n_bytes;
4999
0
    return ptr;
5000
0
}
5001
5002
static int
5003
md_start_new_block(MD_CTX* ctx, const MD_LINE_ANALYSIS* line)
5004
0
{
5005
0
    MD_BLOCK* block;
5006
5007
0
    MD_ASSERT(ctx->current_block == NULL);
5008
5009
0
    block = (MD_BLOCK*) md_push_block_bytes(ctx, sizeof(MD_BLOCK));
5010
0
    if(block == NULL)
5011
0
        return -1;
5012
5013
0
    switch(line->type) {
5014
0
        case MD_LINE_HR:
5015
0
            block->type = MD_BLOCK_HR;
5016
0
            break;
5017
5018
0
        case MD_LINE_ATXHEADER:
5019
0
        case MD_LINE_SETEXTHEADER:
5020
0
            block->type = MD_BLOCK_H;
5021
0
            break;
5022
5023
0
        case MD_LINE_FENCEDCODE:
5024
0
        case MD_LINE_INDENTEDCODE:
5025
0
            block->type = MD_BLOCK_CODE;
5026
0
            break;
5027
5028
0
        case MD_LINE_TEXT:
5029
0
            block->type = MD_BLOCK_P;
5030
0
            break;
5031
5032
0
        case MD_LINE_HTML:
5033
0
            block->type = MD_BLOCK_HTML;
5034
0
            break;
5035
5036
0
        case MD_LINE_BLANK:
5037
0
        case MD_LINE_SETEXTUNDERLINE:
5038
0
        case MD_LINE_TABLEUNDERLINE:
5039
0
        default:
5040
0
            MD_UNREACHABLE();
5041
0
            break;
5042
0
    }
5043
5044
0
    block->flags = 0;
5045
0
    block->data = line->data;
5046
0
    block->n_lines = 0;
5047
5048
0
    ctx->current_block = block;
5049
0
    return 0;
5050
0
}
5051
5052
/* Eat from start of current (textual) block any reference definitions and
5053
 * remember them so we can resolve any links referring to them.
5054
 *
5055
 * (Reference definitions can only be at start of it as they cannot break
5056
 * a paragraph.)
5057
 */
5058
static int
5059
md_consume_link_reference_definitions(MD_CTX* ctx)
5060
0
{
5061
0
    MD_LINE* lines = (MD_LINE*) (ctx->current_block + 1);
5062
0
    MD_SIZE n_lines = ctx->current_block->n_lines;
5063
0
    MD_SIZE n = 0;
5064
5065
    /* Compute how many lines at the start of the block form one or more
5066
     * reference definitions. */
5067
0
    while(n < n_lines) {
5068
0
        int n_link_ref_lines;
5069
5070
0
        n_link_ref_lines = md_is_link_reference_definition(ctx,
5071
0
                                    lines + n, n_lines - n);
5072
        /* Not a reference definition? */
5073
0
        if(n_link_ref_lines == 0)
5074
0
            break;
5075
5076
        /* We fail if it is the ref. def. but it could not be stored due
5077
         * a memory allocation error. */
5078
0
        if(n_link_ref_lines < 0)
5079
0
            return -1;
5080
5081
0
        n += n_link_ref_lines;
5082
0
    }
5083
5084
    /* If there was at least one reference definition, we need to remove
5085
     * its lines from the block, or perhaps even the whole block. */
5086
0
    if(n > 0) {
5087
0
        if(n == n_lines) {
5088
            /* Remove complete block. */
5089
0
            ctx->n_block_bytes -= n * sizeof(MD_LINE);
5090
0
            ctx->n_block_bytes -= sizeof(MD_BLOCK);
5091
0
            ctx->current_block = NULL;
5092
0
        } else {
5093
            /* Remove just some initial lines from the block. */
5094
0
            memmove(lines, lines + n, (n_lines - n) * sizeof(MD_LINE));
5095
0
            ctx->current_block->n_lines -= n;
5096
0
            ctx->n_block_bytes -= n * sizeof(MD_LINE);
5097
0
        }
5098
0
    }
5099
5100
0
    return 0;
5101
0
}
5102
5103
static int
5104
md_end_current_block(MD_CTX* ctx)
5105
0
{
5106
0
    int ret = 0;
5107
5108
0
    if(ctx->current_block == NULL)
5109
0
        return ret;
5110
5111
    /* Check whether there is a reference definition. (We do this here instead
5112
     * of in md_analyze_line() because reference definition can take multiple
5113
     * lines.) */
5114
0
    if(ctx->current_block->type == MD_BLOCK_P  ||
5115
0
       (ctx->current_block->type == MD_BLOCK_H  &&  (ctx->current_block->flags & MD_BLOCK_SETEXT_HEADER)))
5116
0
    {
5117
0
        MD_LINE* lines = (MD_LINE*) (ctx->current_block + 1);
5118
0
        if(lines[0].beg < ctx->size  &&  CH(lines[0].beg) == _T('[')) {
5119
0
            MD_CHECK(md_consume_link_reference_definitions(ctx));
5120
0
            if(ctx->current_block == NULL)
5121
0
                return ret;
5122
0
        }
5123
0
    }
5124
5125
0
    if(ctx->current_block->type == MD_BLOCK_H  &&  (ctx->current_block->flags & MD_BLOCK_SETEXT_HEADER)) {
5126
0
        MD_SIZE n_lines = ctx->current_block->n_lines;
5127
5128
0
        if(n_lines > 1) {
5129
            /* Get rid of the underline. */
5130
0
            ctx->current_block->n_lines--;
5131
0
            ctx->n_block_bytes -= sizeof(MD_LINE);
5132
0
        } else {
5133
            /* Only the underline has left after eating the ref. defs.
5134
             * Keep the line as beginning of a new ordinary paragraph. */
5135
0
            ctx->current_block->type = MD_BLOCK_P;
5136
0
            return 0;
5137
0
        }
5138
0
    }
5139
5140
    /* Mark we are not building any block anymore. */
5141
0
    ctx->current_block = NULL;
5142
5143
0
abort:
5144
0
    return ret;
5145
0
}
5146
5147
static int
5148
md_add_line_into_current_block(MD_CTX* ctx, const MD_LINE_ANALYSIS* analysis)
5149
0
{
5150
0
    MD_ASSERT(ctx->current_block != NULL);
5151
5152
0
    if(ctx->current_block->type == MD_BLOCK_CODE || ctx->current_block->type == MD_BLOCK_HTML) {
5153
0
        MD_VERBATIMLINE* line;
5154
5155
0
        line = (MD_VERBATIMLINE*) md_push_block_bytes(ctx, sizeof(MD_VERBATIMLINE));
5156
0
        if(line == NULL)
5157
0
            return -1;
5158
5159
0
        line->indent = analysis->indent;
5160
0
        line->beg = analysis->beg;
5161
0
        line->end = analysis->end;
5162
0
    } else {
5163
0
        MD_LINE* line;
5164
5165
0
        line = (MD_LINE*) md_push_block_bytes(ctx, sizeof(MD_LINE));
5166
0
        if(line == NULL)
5167
0
            return -1;
5168
5169
0
        line->beg = analysis->beg;
5170
0
        line->end = analysis->end;
5171
0
    }
5172
0
    ctx->current_block->n_lines++;
5173
5174
0
    return 0;
5175
0
}
5176
5177
static int
5178
md_push_container_bytes(MD_CTX* ctx, MD_BLOCKTYPE type, unsigned start,
5179
                        unsigned data, unsigned flags)
5180
0
{
5181
0
    MD_BLOCK* block;
5182
0
    int ret = 0;
5183
5184
0
    MD_CHECK(md_end_current_block(ctx));
5185
5186
0
    block = (MD_BLOCK*) md_push_block_bytes(ctx, sizeof(MD_BLOCK));
5187
0
    if(block == NULL)
5188
0
        return -1;
5189
5190
0
    block->type = type;
5191
0
    block->flags = flags;
5192
0
    block->data = data;
5193
0
    block->n_lines = start;
5194
5195
0
abort:
5196
0
    return ret;
5197
0
}
5198
5199
5200
5201
/***********************
5202
 ***  Line Analysis  ***
5203
 ***********************/
5204
5205
static int
5206
md_is_hr_line(MD_CTX* ctx, OFF beg, OFF* p_end, OFF* p_killer)
5207
0
{
5208
0
    OFF off = beg + 1;
5209
0
    int n = 1;
5210
5211
0
    while(off < ctx->size  &&  (CH(off) == CH(beg) || CH(off) == _T(' ') || CH(off) == _T('\t'))) {
5212
0
        if(CH(off) == CH(beg))
5213
0
            n++;
5214
0
        off++;
5215
0
    }
5216
5217
0
    if(n < 3) {
5218
0
        *p_killer = off;
5219
0
        return FALSE;
5220
0
    }
5221
5222
    /* Nothing else can be present on the line. */
5223
0
    if(off < ctx->size  &&  !ISNEWLINE(off)) {
5224
0
        *p_killer = off;
5225
0
        return FALSE;
5226
0
    }
5227
5228
0
    *p_end = off;
5229
0
    return TRUE;
5230
0
}
5231
5232
static int
5233
md_is_atxheader_line(MD_CTX* ctx, OFF beg, OFF* p_beg, OFF* p_end, unsigned* p_level)
5234
0
{
5235
0
    int n;
5236
0
    OFF off = beg + 1;
5237
5238
0
    while(off < ctx->size  &&  CH(off) == _T('#')  &&  off - beg < 7)
5239
0
        off++;
5240
0
    n = off - beg;
5241
5242
0
    if(n > 6)
5243
0
        return FALSE;
5244
0
    *p_level = n;
5245
5246
0
    if(!(ctx->parser.flags & MD_FLAG_PERMISSIVEATXHEADERS)  &&  off < ctx->size  &&
5247
0
       !ISBLANK(off)  &&  !ISNEWLINE(off))
5248
0
        return FALSE;
5249
5250
0
    while(off < ctx->size  &&  ISBLANK(off))
5251
0
        off++;
5252
0
    *p_beg = off;
5253
0
    *p_end = off;
5254
0
    return TRUE;
5255
0
}
5256
5257
static int
5258
md_is_setext_underline(MD_CTX* ctx, OFF beg, OFF* p_end, unsigned* p_level)
5259
0
{
5260
0
    OFF off = beg + 1;
5261
5262
0
    while(off < ctx->size  &&  CH(off) == CH(beg))
5263
0
        off++;
5264
5265
    /* Optionally, space(s) or tabs can follow. */
5266
0
    while(off < ctx->size  &&  ISBLANK(off))
5267
0
        off++;
5268
5269
    /* But nothing more is allowed on the line. */
5270
0
    if(off < ctx->size  &&  !ISNEWLINE(off))
5271
0
        return FALSE;
5272
5273
0
    *p_level = (CH(beg) == _T('=') ? 1 : 2);
5274
0
    *p_end = off;
5275
0
    return TRUE;
5276
0
}
5277
5278
static int
5279
md_is_table_underline(MD_CTX* ctx, OFF beg, OFF* p_end, unsigned* p_col_count)
5280
0
{
5281
0
    OFF off = beg;
5282
0
    int found_pipe = FALSE;
5283
0
    unsigned col_count = 0;
5284
5285
0
    if(off < ctx->size  &&  CH(off) == _T('|')) {
5286
0
        found_pipe = TRUE;
5287
0
        off++;
5288
0
        while(off < ctx->size  &&  ISWHITESPACE(off))
5289
0
            off++;
5290
0
    }
5291
5292
0
    while(1) {
5293
0
        int delimited = FALSE;
5294
5295
        /* Cell underline ("-----", ":----", "----:" or ":----:") */
5296
0
        if(off < ctx->size  &&  CH(off) == _T(':'))
5297
0
            off++;
5298
0
        if(off >= ctx->size  ||  CH(off) != _T('-'))
5299
0
            return FALSE;
5300
0
        while(off < ctx->size  &&  CH(off) == _T('-'))
5301
0
            off++;
5302
0
        if(off < ctx->size  &&  CH(off) == _T(':'))
5303
0
            off++;
5304
5305
0
        col_count++;
5306
0
        if(col_count > TABLE_MAXCOLCOUNT) {
5307
0
            MD_LOG("Suppressing table (column_count >" STRINGIZE(TABLE_MAXCOLCOUNT) ")");
5308
0
            return FALSE;
5309
0
        }
5310
5311
        /* Pipe delimiter (optional at the end of line). */
5312
0
        while(off < ctx->size  &&  ISWHITESPACE(off))
5313
0
            off++;
5314
0
        if(off < ctx->size  &&  CH(off) == _T('|')) {
5315
0
            delimited = TRUE;
5316
0
            found_pipe =  TRUE;
5317
0
            off++;
5318
0
            while(off < ctx->size  &&  ISWHITESPACE(off))
5319
0
                off++;
5320
0
        }
5321
5322
        /* Success, if we reach end of line. */
5323
0
        if(off >= ctx->size  ||  ISNEWLINE(off))
5324
0
            break;
5325
5326
0
        if(!delimited)
5327
0
            return FALSE;
5328
0
    }
5329
5330
0
    if(!found_pipe)
5331
0
        return FALSE;
5332
5333
0
    *p_end = off;
5334
0
    *p_col_count = col_count;
5335
0
    return TRUE;
5336
0
}
5337
5338
static int
5339
md_is_opening_code_fence(MD_CTX* ctx, OFF beg, OFF* p_end)
5340
0
{
5341
0
    OFF off = beg;
5342
5343
0
    while(off < ctx->size && CH(off) == CH(beg))
5344
0
        off++;
5345
5346
    /* Fence must have at least three characters. */
5347
0
    if(off - beg < 3)
5348
0
        return FALSE;
5349
5350
0
    ctx->code_fence_length = off - beg;
5351
5352
    /* Optionally, space(s) can follow. */
5353
0
    while(off < ctx->size  &&  CH(off) == _T(' '))
5354
0
        off++;
5355
5356
    /* Optionally, an info string can follow. */
5357
0
    while(off < ctx->size  &&  !ISNEWLINE(off)) {
5358
        /* Backtick-based fence must not contain '`' in the info string. */
5359
0
        if(CH(beg) == _T('`')  &&  CH(off) == _T('`'))
5360
0
            return FALSE;
5361
0
        off++;
5362
0
    }
5363
5364
0
    *p_end = off;
5365
0
    return TRUE;
5366
0
}
5367
5368
static int
5369
md_is_closing_code_fence(MD_CTX* ctx, CHAR ch, OFF beg, OFF* p_end)
5370
0
{
5371
0
    OFF off = beg;
5372
0
    int ret = FALSE;
5373
5374
    /* Closing fence must have at least the same length and use same char as
5375
     * opening one. */
5376
0
    while(off < ctx->size  &&  CH(off) == ch)
5377
0
        off++;
5378
0
    if(off - beg < ctx->code_fence_length)
5379
0
        goto out;
5380
5381
    /* Optionally, space(s) can follow */
5382
0
    while(off < ctx->size  &&  ISANYOF2(off, _T(' '), _T('\t')))
5383
0
        off++;
5384
5385
    /* But nothing more is allowed on the line. */
5386
0
    if(off < ctx->size  &&  !ISNEWLINE(off))
5387
0
        goto out;
5388
5389
0
    ret = TRUE;
5390
5391
0
out:
5392
    /* Note we set *p_end even on failure: If we are not closing fence, caller
5393
     * would eat the line anyway without any parsing. */
5394
0
    *p_end = off;
5395
0
    return ret;
5396
0
}
5397
5398
5399
/* Helper data for md_is_html_block_start_condition() and
5400
 * md_is_html_block_end_condition() */
5401
typedef struct TAG_tag TAG;
5402
struct TAG_tag {
5403
    const CHAR* name;
5404
    unsigned len    : 8;
5405
};
5406
5407
#ifdef X
5408
    #undef X
5409
#endif
5410
#define X(name)     { _T(name), (sizeof(name)-1) / sizeof(CHAR) }
5411
#define Xend        { NULL, 0 }
5412
5413
static const TAG t1[] = { X("pre"), X("script"), X("style"), X("textarea"), Xend };
5414
5415
static const TAG a6[] = { X("address"), X("article"), X("aside"), Xend };
5416
static const TAG b6[] = { X("base"), X("basefont"), X("blockquote"), X("body"), Xend };
5417
static const TAG c6[] = { X("caption"), X("center"), X("col"), X("colgroup"), Xend };
5418
static const TAG d6[] = { X("dd"), X("details"), X("dialog"), X("dir"),
5419
                          X("div"), X("dl"), X("dt"), Xend };
5420
static const TAG f6[] = { X("fieldset"), X("figcaption"), X("figure"), X("footer"),
5421
                          X("form"), X("frame"), X("frameset"), Xend };
5422
static const TAG h6[] = { X("h1"), X("h2"), X("h3"), X("h4"), X("h5"), X("h6"),
5423
                          X("head"), X("header"), X("hr"), X("html"), Xend };
5424
static const TAG i6[] = { X("iframe"), Xend };
5425
static const TAG l6[] = { X("legend"), X("li"), X("link"), Xend };
5426
static const TAG m6[] = { X("main"), X("menu"), X("menuitem"), Xend };
5427
static const TAG n6[] = { X("nav"), X("noframes"), Xend };
5428
static const TAG o6[] = { X("ol"), X("optgroup"), X("option"), Xend };
5429
static const TAG p6[] = { X("p"), X("param"), Xend };
5430
static const TAG s6[] = { X("search"), X("section"), X("summary"), Xend };
5431
static const TAG t6[] = { X("table"), X("tbody"), X("td"), X("tfoot"), X("th"),
5432
                          X("thead"), X("title"), X("tr"), X("track"), Xend };
5433
static const TAG u6[] = { X("ul"), Xend };
5434
static const TAG xx[] = { Xend };
5435
5436
#undef X
5437
#undef Xend
5438
5439
/* Returns type of the raw HTML block, or FALSE if it is not HTML block.
5440
 * (Refer to CommonMark specification for details about the types.)
5441
 */
5442
static int
5443
md_is_html_block_start_condition(MD_CTX* ctx, OFF beg)
5444
0
{
5445
    /* Type 6 is started by a long list of allowed tags. We use two-level
5446
     * tree to speed-up the search. */
5447
0
    static const TAG* map6[26] = {
5448
0
        a6, b6, c6, d6, xx, f6, xx, h6, i6, xx, xx, l6, m6,
5449
0
        n6, o6, p6, xx, xx, s6, t6, u6, xx, xx, xx, xx, xx
5450
0
    };
5451
0
    OFF off = beg + 1;
5452
0
    int i;
5453
5454
    /* Check for type 1: <script, <pre, or <style */
5455
0
    for(i = 0; t1[i].name != NULL; i++) {
5456
0
        if(off + t1[i].len <= ctx->size) {
5457
0
            if(md_ascii_case_eq(STR(off), t1[i].name, t1[i].len))
5458
0
                return 1;
5459
0
        }
5460
0
    }
5461
5462
    /* Check for type 2: <!-- */
5463
0
    if(off + 3 < ctx->size  &&  CH(off) == _T('!')  &&  CH(off+1) == _T('-')  &&  CH(off+2) == _T('-'))
5464
0
        return 2;
5465
5466
    /* Check for type 3: <? */
5467
0
    if(off < ctx->size  &&  CH(off) == _T('?'))
5468
0
        return 3;
5469
5470
    /* Check for type 4 or 5: <! */
5471
0
    if(off < ctx->size  &&  CH(off) == _T('!')) {
5472
        /* Check for type 4: <! followed by uppercase letter. */
5473
0
        if(off + 1 < ctx->size  &&  ISASCII(off+1))
5474
0
            return 4;
5475
5476
        /* Check for type 5: <![CDATA[ */
5477
0
        if(off + 8 < ctx->size) {
5478
0
            if(md_ascii_eq(STR(off), _T("![CDATA["), 8))
5479
0
                return 5;
5480
0
        }
5481
0
    }
5482
5483
    /* Check for type 6: Many possible starting tags listed above. */
5484
0
    if(off + 1 < ctx->size  &&  (ISALPHA(off) || (CH(off) == _T('/') && ISALPHA(off+1)))) {
5485
0
        int slot;
5486
0
        const TAG* tags;
5487
5488
0
        if(CH(off) == _T('/'))
5489
0
            off++;
5490
5491
0
        slot = (ISUPPER(off) ? CH(off) - 'A' : CH(off) - 'a');
5492
0
        tags = map6[slot];
5493
5494
0
        for(i = 0; tags[i].name != NULL; i++) {
5495
0
            if(off + tags[i].len <= ctx->size) {
5496
0
                if(md_ascii_case_eq(STR(off), tags[i].name, tags[i].len)) {
5497
0
                    OFF tmp = off + tags[i].len;
5498
0
                    if(tmp >= ctx->size)
5499
0
                        return 6;
5500
0
                    if(ISBLANK(tmp) || ISNEWLINE(tmp) || CH(tmp) == _T('>'))
5501
0
                        return 6;
5502
0
                    if(tmp+1 < ctx->size && CH(tmp) == _T('/') && CH(tmp+1) == _T('>'))
5503
0
                        return 6;
5504
0
                    break;
5505
0
                }
5506
0
            }
5507
0
        }
5508
0
    }
5509
5510
    /* Check for type 7: any COMPLETE other opening or closing tag. */
5511
0
    if(off + 1 < ctx->size) {
5512
0
        OFF end;
5513
5514
0
        if(md_is_html_tag(ctx, NULL, 0, beg, ctx->size, &end)) {
5515
            /* Only optional whitespace and new line may follow. */
5516
0
            while(end < ctx->size  &&  ISWHITESPACE(end))
5517
0
                end++;
5518
0
            if(end >= ctx->size  ||  ISNEWLINE(end))
5519
0
                return 7;
5520
0
        }
5521
0
    }
5522
5523
0
    return FALSE;
5524
0
}
5525
5526
/* Case sensitive check whether there is a substring 'what' between 'beg'
5527
 * and end of line. */
5528
static int
5529
md_line_contains(MD_CTX* ctx, OFF beg, const CHAR* what, SZ what_len, OFF* p_end)
5530
0
{
5531
0
    OFF i;
5532
0
    for(i = beg; i + what_len < ctx->size; i++) {
5533
0
        if(ISNEWLINE(i))
5534
0
            break;
5535
0
        if(memcmp(STR(i), what, what_len * sizeof(CHAR)) == 0) {
5536
0
            *p_end = i + what_len;
5537
0
            return TRUE;
5538
0
        }
5539
0
    }
5540
5541
0
    *p_end = i;
5542
0
    return FALSE;
5543
0
}
5544
5545
/* Returns type of HTML block end condition or FALSE if not an end condition.
5546
 *
5547
 * Note it fills p_end even when it is not end condition as the caller
5548
 * does not need to analyze contents of a raw HTML block.
5549
 */
5550
static int
5551
md_is_html_block_end_condition(MD_CTX* ctx, OFF beg, OFF* p_end)
5552
0
{
5553
0
    switch(ctx->html_block_type) {
5554
0
        case 1:
5555
0
        {
5556
0
            OFF off = beg;
5557
0
            int i;
5558
5559
0
            while(off+1 < ctx->size  &&  !ISNEWLINE(off)) {
5560
0
                if(CH(off) == _T('<')  &&  CH(off+1) == _T('/')) {
5561
0
                    for(i = 0; t1[i].name != NULL; i++) {
5562
0
                        if(off + 2 + t1[i].len < ctx->size) {
5563
0
                            if(md_ascii_case_eq(STR(off+2), t1[i].name, t1[i].len)  &&
5564
0
                               CH(off+2+t1[i].len) == _T('>'))
5565
0
                            {
5566
0
                                *p_end = off+2+t1[i].len+1;
5567
0
                                return TRUE;
5568
0
                            }
5569
0
                        }
5570
0
                    }
5571
0
                }
5572
0
                off++;
5573
0
            }
5574
0
            *p_end = off;
5575
0
            return FALSE;
5576
0
        }
5577
5578
0
        case 2:
5579
0
            return (md_line_contains(ctx, beg, _T("-->"), 3, p_end) ? 2 : FALSE);
5580
5581
0
        case 3:
5582
0
            return (md_line_contains(ctx, beg, _T("?>"), 2, p_end) ? 3 : FALSE);
5583
5584
0
        case 4:
5585
0
            return (md_line_contains(ctx, beg, _T(">"), 1, p_end) ? 4 : FALSE);
5586
5587
0
        case 5:
5588
0
            return (md_line_contains(ctx, beg, _T("]]>"), 3, p_end) ? 5 : FALSE);
5589
5590
0
        case 6:     /* Pass through */
5591
0
        case 7:
5592
0
            if(beg >= ctx->size  ||  ISNEWLINE(beg)) {
5593
                /* Blank line ends types 6 and 7. */
5594
0
                *p_end = beg;
5595
0
                return ctx->html_block_type;
5596
0
            }
5597
0
            return FALSE;
5598
5599
0
        default:
5600
0
            MD_UNREACHABLE();
5601
0
    }
5602
0
    return FALSE;
5603
0
}
5604
5605
5606
static int
5607
md_is_container_compatible(const MD_CONTAINER* pivot, const MD_CONTAINER* container)
5608
0
{
5609
    /* Block quote has no "items" like lists. */
5610
0
    if(container->ch == _T('>'))
5611
0
        return FALSE;
5612
5613
0
    if(container->ch != pivot->ch)
5614
0
        return FALSE;
5615
0
    if(container->mark_indent > pivot->contents_indent)
5616
0
        return FALSE;
5617
5618
0
    return TRUE;
5619
0
}
5620
5621
static int
5622
md_push_container(MD_CTX* ctx, const MD_CONTAINER* container)
5623
0
{
5624
0
    if(ctx->n_containers >= ctx->alloc_containers) {
5625
0
        MD_CONTAINER* new_containers;
5626
5627
0
        ctx->alloc_containers = (ctx->alloc_containers > 0
5628
0
                ? ctx->alloc_containers + ctx->alloc_containers / 2
5629
0
                : 16);
5630
0
        new_containers = realloc(ctx->containers, ctx->alloc_containers * sizeof(MD_CONTAINER));
5631
0
        if(new_containers == NULL) {
5632
0
            MD_LOG("realloc() failed.");
5633
0
            return -1;
5634
0
        }
5635
5636
0
        ctx->containers = new_containers;
5637
0
    }
5638
5639
0
    memcpy(&ctx->containers[ctx->n_containers++], container, sizeof(MD_CONTAINER));
5640
0
    return 0;
5641
0
}
5642
5643
static int
5644
md_enter_child_containers(MD_CTX* ctx, int n_children)
5645
0
{
5646
0
    int i;
5647
0
    int ret = 0;
5648
5649
0
    for(i = ctx->n_containers - n_children; i < ctx->n_containers; i++) {
5650
0
        MD_CONTAINER* c = &ctx->containers[i];
5651
0
        int is_ordered_list = FALSE;
5652
5653
0
        switch(c->ch) {
5654
0
            case _T(')'):
5655
0
            case _T('.'):
5656
0
                is_ordered_list = TRUE;
5657
0
                MD_FALLTHROUGH();
5658
5659
0
            case _T('-'):
5660
0
            case _T('+'):
5661
0
            case _T('*'):
5662
                /* Remember offset in ctx->block_bytes so we can revisit the
5663
                 * block if we detect it is a loose list. */
5664
0
                md_end_current_block(ctx);
5665
0
                c->block_byte_off = ctx->n_block_bytes;
5666
5667
0
                MD_CHECK(md_push_container_bytes(ctx,
5668
0
                                (is_ordered_list ? MD_BLOCK_OL : MD_BLOCK_UL),
5669
0
                                c->start, c->ch, MD_BLOCK_CONTAINER_OPENER));
5670
0
                MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI,
5671
0
                                c->task_mark_off,
5672
0
                                (c->is_task ? CH(c->task_mark_off) : 0),
5673
0
                                MD_BLOCK_CONTAINER_OPENER));
5674
0
                break;
5675
5676
0
            case _T('>'):
5677
0
                MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_QUOTE, 0, 0, MD_BLOCK_CONTAINER_OPENER));
5678
0
                break;
5679
5680
0
            default:
5681
0
                MD_UNREACHABLE();
5682
0
                break;
5683
0
        }
5684
0
    }
5685
5686
0
abort:
5687
0
    return ret;
5688
0
}
5689
5690
static int
5691
md_leave_child_containers(MD_CTX* ctx, int n_keep)
5692
0
{
5693
0
    int ret = 0;
5694
5695
0
    while(ctx->n_containers > n_keep) {
5696
0
        MD_CONTAINER* c = &ctx->containers[ctx->n_containers-1];
5697
0
        int is_ordered_list = FALSE;
5698
5699
0
        switch(c->ch) {
5700
0
            case _T(')'):
5701
0
            case _T('.'):
5702
0
                is_ordered_list = TRUE;
5703
0
                MD_FALLTHROUGH();
5704
5705
0
            case _T('-'):
5706
0
            case _T('+'):
5707
0
            case _T('*'):
5708
0
                MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI,
5709
0
                                c->task_mark_off, (c->is_task ? CH(c->task_mark_off) : 0),
5710
0
                                MD_BLOCK_CONTAINER_CLOSER));
5711
0
                MD_CHECK(md_push_container_bytes(ctx,
5712
0
                                (is_ordered_list ? MD_BLOCK_OL : MD_BLOCK_UL), 0,
5713
0
                                c->ch, MD_BLOCK_CONTAINER_CLOSER));
5714
0
                break;
5715
5716
0
            case _T('>'):
5717
0
                MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_QUOTE, 0,
5718
0
                                0, MD_BLOCK_CONTAINER_CLOSER));
5719
0
                break;
5720
5721
0
            default:
5722
0
                MD_UNREACHABLE();
5723
0
                break;
5724
0
        }
5725
5726
0
        ctx->n_containers--;
5727
0
    }
5728
5729
0
abort:
5730
0
    return ret;
5731
0
}
5732
5733
static int
5734
md_is_container_mark(MD_CTX* ctx, unsigned indent, OFF beg, OFF* p_end, MD_CONTAINER* p_container)
5735
0
{
5736
0
    OFF off = beg;
5737
0
    OFF max_end;
5738
5739
0
    if(off >= ctx->size  ||  indent >= ctx->code_indent_offset)
5740
0
        return FALSE;
5741
5742
    /* Check for block quote mark. */
5743
0
    if(CH(off) == _T('>')) {
5744
0
        off++;
5745
0
        p_container->ch = _T('>');
5746
0
        p_container->is_loose = FALSE;
5747
0
        p_container->is_task = FALSE;
5748
0
        p_container->mark_indent = indent;
5749
0
        p_container->contents_indent = indent + 1;
5750
0
        *p_end = off;
5751
0
        return TRUE;
5752
0
    }
5753
5754
    /* Check for list item bullet mark. */
5755
0
    if(ISANYOF(off, _T("-+*"))  &&  (off+1 >= ctx->size || ISBLANK(off+1) || ISNEWLINE(off+1))) {
5756
0
        p_container->ch = CH(off);
5757
0
        p_container->is_loose = FALSE;
5758
0
        p_container->is_task = FALSE;
5759
0
        p_container->mark_indent = indent;
5760
0
        p_container->contents_indent = indent + 1;
5761
0
        *p_end = off+1;
5762
0
        return TRUE;
5763
0
    }
5764
5765
    /* Check for ordered list item marks. */
5766
0
    max_end = off + 9;
5767
0
    if(max_end > ctx->size)
5768
0
        max_end = ctx->size;
5769
0
    p_container->start = 0;
5770
0
    while(off < max_end  &&  ISDIGIT(off)) {
5771
0
        p_container->start = p_container->start * 10 + CH(off) - _T('0');
5772
0
        off++;
5773
0
    }
5774
0
    if(off > beg  &&
5775
0
       off < ctx->size  &&
5776
0
       (CH(off) == _T('.') || CH(off) == _T(')'))  &&
5777
0
       (off+1 >= ctx->size || ISBLANK(off+1) || ISNEWLINE(off+1)))
5778
0
    {
5779
0
        p_container->ch = CH(off);
5780
0
        p_container->is_loose = FALSE;
5781
0
        p_container->is_task = FALSE;
5782
0
        p_container->mark_indent = indent;
5783
0
        p_container->contents_indent = indent + off - beg + 1;
5784
0
        *p_end = off+1;
5785
0
        return TRUE;
5786
0
    }
5787
5788
0
    return FALSE;
5789
0
}
5790
5791
static unsigned
5792
md_line_indentation(MD_CTX* ctx, unsigned total_indent, OFF beg, OFF* p_end)
5793
0
{
5794
0
    OFF off = beg;
5795
0
    unsigned indent = total_indent;
5796
5797
0
    while(off < ctx->size  &&  ISBLANK(off)) {
5798
0
        if(CH(off) == _T('\t'))
5799
0
            indent = (indent + 4) & ~3;
5800
0
        else
5801
0
            indent++;
5802
0
        off++;
5803
0
    }
5804
5805
0
    *p_end = off;
5806
0
    return indent - total_indent;
5807
0
}
5808
5809
static const MD_LINE_ANALYSIS md_dummy_blank_line = { MD_LINE_BLANK, 0, 0, 0, 0, 0 };
5810
5811
/* Analyze type of the line and find some its properties. This serves as a
5812
 * main input for determining type and boundaries of a block. */
5813
static int
5814
md_analyze_line(MD_CTX* ctx, OFF beg, OFF* p_end,
5815
                const MD_LINE_ANALYSIS* pivot_line, MD_LINE_ANALYSIS* line)
5816
0
{
5817
0
    unsigned total_indent = 0;
5818
0
    int n_parents = 0;
5819
0
    int n_brothers = 0;
5820
0
    int n_children = 0;
5821
0
    MD_CONTAINER container = { 0 };
5822
0
    int prev_line_has_list_loosening_effect = ctx->last_line_has_list_loosening_effect;
5823
0
    OFF off = beg;
5824
0
    OFF hr_killer = 0;
5825
0
    int ret = 0;
5826
5827
0
    line->indent = md_line_indentation(ctx, total_indent, off, &off);
5828
0
    total_indent += line->indent;
5829
0
    line->beg = off;
5830
0
    line->enforce_new_block = FALSE;
5831
5832
    /* Given the indentation and block quote marks '>', determine how many of
5833
     * the current containers are our parents. */
5834
0
    while(n_parents < ctx->n_containers) {
5835
0
        MD_CONTAINER* c = &ctx->containers[n_parents];
5836
5837
0
        if(c->ch == _T('>')  &&  line->indent < ctx->code_indent_offset  &&
5838
0
            off < ctx->size  &&  CH(off) == _T('>'))
5839
0
        {
5840
            /* Block quote mark. */
5841
0
            off++;
5842
0
            total_indent++;
5843
0
            line->indent = md_line_indentation(ctx, total_indent, off, &off);
5844
0
            total_indent += line->indent;
5845
5846
            /* The optional 1st space after '>' is part of the block quote mark. */
5847
0
            if(line->indent > 0)
5848
0
                line->indent--;
5849
5850
0
            line->beg = off;
5851
5852
0
        } else if(c->ch != _T('>')  &&  line->indent >= c->contents_indent) {
5853
            /* List. */
5854
0
            line->indent -= c->contents_indent;
5855
0
        } else {
5856
0
            break;
5857
0
        }
5858
5859
0
        n_parents++;
5860
0
    }
5861
5862
0
    if(off >= ctx->size  ||  ISNEWLINE(off)) {
5863
        /* Blank line does not need any real indentation to be nested inside
5864
         * a list. */
5865
0
        if(n_brothers + n_children == 0) {
5866
0
            while(n_parents < ctx->n_containers  &&  ctx->containers[n_parents].ch != _T('>'))
5867
0
                n_parents++;
5868
0
        }
5869
0
    }
5870
5871
0
    while(TRUE) {
5872
        /* Check whether we are fenced code continuation. */
5873
0
        if(pivot_line->type == MD_LINE_FENCEDCODE) {
5874
0
            line->beg = off;
5875
5876
            /* We are another MD_LINE_FENCEDCODE unless we are closing fence
5877
             * which we transform into MD_LINE_BLANK. */
5878
0
            if(line->indent < ctx->code_indent_offset) {
5879
0
                if(md_is_closing_code_fence(ctx, CH(pivot_line->beg), off, &off)) {
5880
0
                    line->type = MD_LINE_BLANK;
5881
0
                    ctx->last_line_has_list_loosening_effect = FALSE;
5882
0
                    break;
5883
0
                }
5884
0
            }
5885
5886
            /* Change indentation accordingly to the initial code fence. */
5887
0
            if(n_parents == ctx->n_containers) {
5888
0
                if(line->indent > pivot_line->indent)
5889
0
                    line->indent -= pivot_line->indent;
5890
0
                else
5891
0
                    line->indent = 0;
5892
5893
0
                line->type = MD_LINE_FENCEDCODE;
5894
0
                break;
5895
0
            }
5896
0
        }
5897
5898
        /* Check whether we are HTML block continuation. */
5899
0
        if(pivot_line->type == MD_LINE_HTML  &&  ctx->html_block_type > 0) {
5900
0
            if(n_parents < ctx->n_containers) {
5901
                /* HTML block is implicitly ended if the enclosing container
5902
                 * block ends. */
5903
0
                ctx->html_block_type = 0;
5904
0
            } else {
5905
0
                int html_block_type;
5906
5907
0
                html_block_type = md_is_html_block_end_condition(ctx, off, &off);
5908
0
                if(html_block_type > 0) {
5909
0
                    MD_ASSERT(html_block_type == ctx->html_block_type);
5910
5911
                    /* Make sure this is the last line of the block. */
5912
0
                    ctx->html_block_type = 0;
5913
5914
                    /* Some end conditions serve as blank lines at the same time. */
5915
0
                    if(html_block_type == 6 || html_block_type == 7) {
5916
0
                        line->type = MD_LINE_BLANK;
5917
0
                        line->indent = 0;
5918
0
                        break;
5919
0
                    }
5920
0
                }
5921
5922
0
                line->type = MD_LINE_HTML;
5923
0
                n_parents = ctx->n_containers;
5924
0
                break;
5925
0
            }
5926
0
        }
5927
5928
        /* Check for blank line. */
5929
0
        if(off >= ctx->size  ||  ISNEWLINE(off)) {
5930
0
            if(pivot_line->type == MD_LINE_INDENTEDCODE  &&  n_parents == ctx->n_containers) {
5931
0
                line->type = MD_LINE_INDENTEDCODE;
5932
0
                if(line->indent > ctx->code_indent_offset)
5933
0
                    line->indent -= ctx->code_indent_offset;
5934
0
                else
5935
0
                    line->indent = 0;
5936
0
                ctx->last_line_has_list_loosening_effect = FALSE;
5937
0
            } else {
5938
0
                line->type = MD_LINE_BLANK;
5939
0
                ctx->last_line_has_list_loosening_effect = (n_parents > 0  &&
5940
0
                        n_brothers + n_children == 0  &&
5941
0
                        ctx->containers[n_parents-1].ch != _T('>'));
5942
5943
0
    #if 1
5944
                /* See https://github.com/mity/md4c/issues/6
5945
                 *
5946
                 * This ugly checking tests we are in (yet empty) list item but
5947
                 * not its very first line (i.e. not the line with the list
5948
                 * item mark).
5949
                 *
5950
                 * If we are such a blank line, then any following non-blank
5951
                 * line which would be part of the list item actually has to
5952
                 * end the list because according to the specification, "a list
5953
                 * item can begin with at most one blank line."
5954
                 */
5955
0
                if(n_parents > 0  &&  ctx->containers[n_parents-1].ch != _T('>')  &&
5956
0
                   n_brothers + n_children == 0  &&  ctx->current_block == NULL  &&
5957
0
                   ctx->n_block_bytes > (int) sizeof(MD_BLOCK))
5958
0
                {
5959
0
                    MD_BLOCK* top_block = (MD_BLOCK*) ((char*)ctx->block_bytes + ctx->n_block_bytes - sizeof(MD_BLOCK));
5960
0
                    if(top_block->type == MD_BLOCK_LI)
5961
0
                        ctx->last_list_item_starts_with_two_blank_lines = TRUE;
5962
0
                }
5963
0
    #endif
5964
0
            }
5965
0
            break;
5966
0
        } else {
5967
0
    #if 1
5968
            /* This is the 2nd half of the hack. If the flag is set (i.e. there
5969
             * was a 2nd blank line at the beginning of the list item) and if
5970
             * we would otherwise still belong to the list item, we enforce
5971
             * the end of the list. */
5972
0
            if(ctx->last_list_item_starts_with_two_blank_lines) {
5973
0
                if(n_parents > 0  &&  n_parents == ctx->n_containers  &&
5974
0
                   ctx->containers[n_parents-1].ch != _T('>')  &&
5975
0
                   n_brothers + n_children == 0  &&  ctx->current_block == NULL  &&
5976
0
                   ctx->n_block_bytes > (int) sizeof(MD_BLOCK))
5977
0
                {
5978
0
                    MD_BLOCK* top_block = (MD_BLOCK*) ((char*)ctx->block_bytes + ctx->n_block_bytes - sizeof(MD_BLOCK));
5979
0
                    if(top_block->type == MD_BLOCK_LI) {
5980
0
                        n_parents--;
5981
5982
0
                        line->indent = total_indent;
5983
0
                        if(n_parents > 0)
5984
0
                            line->indent -= MIN(line->indent, ctx->containers[n_parents-1].contents_indent);
5985
0
                    }
5986
0
                }
5987
5988
0
                ctx->last_list_item_starts_with_two_blank_lines = FALSE;
5989
0
            }
5990
0
    #endif
5991
0
            ctx->last_line_has_list_loosening_effect = FALSE;
5992
0
        }
5993
5994
        /* Check whether we are Setext underline. */
5995
0
        if(line->indent < ctx->code_indent_offset  &&  pivot_line->type == MD_LINE_TEXT
5996
0
            &&  off < ctx->size  &&  ISANYOF2(off, _T('='), _T('-'))
5997
0
            &&  (n_parents == ctx->n_containers))
5998
0
        {
5999
0
            unsigned level;
6000
6001
0
            if(md_is_setext_underline(ctx, off, &off, &level)) {
6002
0
                line->type = MD_LINE_SETEXTUNDERLINE;
6003
0
                line->data = level;
6004
0
                break;
6005
0
            }
6006
0
        }
6007
6008
        /* Check for thematic break line. */
6009
0
        if(line->indent < ctx->code_indent_offset
6010
0
            &&  off < ctx->size  &&  off >= hr_killer
6011
0
            &&  ISANYOF(off, _T("-_*")))
6012
0
        {
6013
0
            if(md_is_hr_line(ctx, off, &off, &hr_killer)) {
6014
0
                line->type = MD_LINE_HR;
6015
0
                break;
6016
0
            }
6017
0
        }
6018
6019
        /* Check for "brother" container. I.e. whether we are another list item
6020
         * in already started list. */
6021
0
        if(n_parents < ctx->n_containers  &&  n_brothers + n_children == 0) {
6022
0
            OFF tmp;
6023
6024
0
            if(md_is_container_mark(ctx, line->indent, off, &tmp, &container)  &&
6025
0
               md_is_container_compatible(&ctx->containers[n_parents], &container))
6026
0
            {
6027
0
                pivot_line = &md_dummy_blank_line;
6028
6029
0
                off = tmp;
6030
6031
0
                total_indent += container.contents_indent - container.mark_indent;
6032
0
                line->indent = md_line_indentation(ctx, total_indent, off, &off);
6033
0
                total_indent += line->indent;
6034
0
                line->beg = off;
6035
6036
                /* Some of the following whitespace actually still belongs to the mark. */
6037
0
                if(off >= ctx->size || ISNEWLINE(off)) {
6038
0
                    container.contents_indent++;
6039
0
                } else if(line->indent <= ctx->code_indent_offset) {
6040
0
                    container.contents_indent += line->indent;
6041
0
                    line->indent = 0;
6042
0
                } else {
6043
0
                    container.contents_indent += 1;
6044
0
                    line->indent--;
6045
0
                }
6046
6047
0
                ctx->containers[n_parents].mark_indent = container.mark_indent;
6048
0
                ctx->containers[n_parents].contents_indent = container.contents_indent;
6049
6050
0
                n_brothers++;
6051
0
                continue;
6052
0
            }
6053
0
        }
6054
6055
        /* Check for indented code.
6056
         * Note indented code block cannot interrupt a paragraph. */
6057
0
        if(line->indent >= ctx->code_indent_offset  &&  (pivot_line->type != MD_LINE_TEXT)) {
6058
0
            line->type = MD_LINE_INDENTEDCODE;
6059
0
            line->indent -= ctx->code_indent_offset;
6060
0
            line->data = 0;
6061
0
            break;
6062
0
        }
6063
6064
        /* Check for start of a new container block. */
6065
0
        if(line->indent < ctx->code_indent_offset  &&
6066
0
           md_is_container_mark(ctx, line->indent, off, &off, &container))
6067
0
        {
6068
0
            if(pivot_line->type == MD_LINE_TEXT  &&  n_parents == ctx->n_containers  &&
6069
0
                        (off >= ctx->size || ISNEWLINE(off))  &&  container.ch != _T('>'))
6070
0
            {
6071
                /* Noop. List mark followed by a blank line cannot interrupt a paragraph. */
6072
0
            } else if(pivot_line->type == MD_LINE_TEXT  &&  n_parents == ctx->n_containers  &&
6073
0
                        ISANYOF2_(container.ch, _T('.'), _T(')'))  &&  container.start != 1)
6074
0
            {
6075
                /* Noop. Ordered list cannot interrupt a paragraph unless the start index is 1. */
6076
0
            } else {
6077
0
                total_indent += container.contents_indent - container.mark_indent;
6078
0
                line->indent = md_line_indentation(ctx, total_indent, off, &off);
6079
0
                total_indent += line->indent;
6080
6081
0
                line->beg = off;
6082
0
                line->data = container.ch;
6083
6084
                /* Some of the following whitespace actually still belongs to the mark. */
6085
0
                if(off >= ctx->size || ISNEWLINE(off)) {
6086
0
                    container.contents_indent++;
6087
0
                } else if(line->indent <= ctx->code_indent_offset) {
6088
0
                    container.contents_indent += line->indent;
6089
0
                    line->indent = 0;
6090
0
                } else {
6091
0
                    container.contents_indent += 1;
6092
0
                    line->indent--;
6093
0
                }
6094
6095
0
                if(n_brothers + n_children == 0)
6096
0
                    pivot_line = &md_dummy_blank_line;
6097
6098
0
                if(n_children == 0)
6099
0
                    MD_CHECK(md_leave_child_containers(ctx, n_parents + n_brothers));
6100
6101
0
                n_children++;
6102
0
                MD_CHECK(md_push_container(ctx, &container));
6103
0
                continue;
6104
0
            }
6105
0
        }
6106
6107
        /* Check whether we are table continuation. */
6108
0
        if(pivot_line->type == MD_LINE_TABLE  &&  n_parents == ctx->n_containers) {
6109
0
            line->type = MD_LINE_TABLE;
6110
0
            break;
6111
0
        }
6112
6113
        /* Check for ATX header. */
6114
0
        if(line->indent < ctx->code_indent_offset  &&
6115
0
                off < ctx->size  &&  CH(off) == _T('#'))
6116
0
        {
6117
0
            unsigned level;
6118
6119
0
            if(md_is_atxheader_line(ctx, off, &line->beg, &off, &level)) {
6120
0
                line->type = MD_LINE_ATXHEADER;
6121
0
                line->data = level;
6122
0
                break;
6123
0
            }
6124
0
        }
6125
6126
        /* Check whether we are starting code fence. */
6127
0
        if(line->indent < ctx->code_indent_offset  &&
6128
0
                off < ctx->size  &&  ISANYOF2(off, _T('`'), _T('~')))
6129
0
        {
6130
0
            if(md_is_opening_code_fence(ctx, off, &off)) {
6131
0
                line->type = MD_LINE_FENCEDCODE;
6132
0
                line->data = 1;
6133
0
                line->enforce_new_block = TRUE;
6134
0
                break;
6135
0
            }
6136
0
        }
6137
6138
        /* Check for start of raw HTML block. */
6139
0
        if(off < ctx->size  &&  CH(off) == _T('<')
6140
0
            &&  !(ctx->parser.flags & MD_FLAG_NOHTMLBLOCKS))
6141
0
        {
6142
0
            ctx->html_block_type = md_is_html_block_start_condition(ctx, off);
6143
6144
            /* HTML block type 7 cannot interrupt paragraph. */
6145
0
            if(ctx->html_block_type == 7  &&  pivot_line->type == MD_LINE_TEXT)
6146
0
                ctx->html_block_type = 0;
6147
6148
0
            if(ctx->html_block_type > 0) {
6149
                /* The line itself also may immediately close the block. */
6150
0
                if(md_is_html_block_end_condition(ctx, off, &off) == ctx->html_block_type) {
6151
                    /* Make sure this is the last line of the block. */
6152
0
                    ctx->html_block_type = 0;
6153
0
                }
6154
6155
0
                line->enforce_new_block = TRUE;
6156
0
                line->type = MD_LINE_HTML;
6157
0
                break;
6158
0
            }
6159
0
        }
6160
6161
        /* Check for table underline. */
6162
0
        if((ctx->parser.flags & MD_FLAG_TABLES)  &&  pivot_line->type == MD_LINE_TEXT
6163
0
            &&  off < ctx->size  &&  ISANYOF3(off, _T('|'), _T('-'), _T(':'))
6164
0
            &&  n_parents == ctx->n_containers)
6165
0
        {
6166
0
            unsigned col_count;
6167
6168
0
            if(ctx->current_block != NULL  &&  ctx->current_block->n_lines == 1  &&
6169
0
                md_is_table_underline(ctx, off, &off, &col_count))
6170
0
            {
6171
0
                line->data = col_count;
6172
0
                line->type = MD_LINE_TABLEUNDERLINE;
6173
0
                break;
6174
0
            }
6175
0
        }
6176
6177
        /* By default, we are normal text line. */
6178
0
        line->type = MD_LINE_TEXT;
6179
0
        if(pivot_line->type == MD_LINE_TEXT  &&  n_brothers + n_children == 0) {
6180
            /* Lazy continuation. */
6181
0
            n_parents = ctx->n_containers;
6182
0
        }
6183
6184
        /* Check for task mark. */
6185
0
        if((ctx->parser.flags & MD_FLAG_TASKLISTS)  &&  n_brothers + n_children > 0  &&
6186
0
           ISANYOF_(ctx->containers[ctx->n_containers-1].ch, _T("-+*.)")))
6187
0
        {
6188
0
            OFF tmp = off;
6189
6190
0
            while(tmp < ctx->size  &&  tmp < off + 3  &&  ISBLANK(tmp))
6191
0
                tmp++;
6192
0
            if(tmp + 2 < ctx->size  &&  CH(tmp) == _T('[')  &&
6193
0
               ISANYOF(tmp+1, _T("xX "))  &&  CH(tmp+2) == _T(']')  &&
6194
0
               (tmp + 3 == ctx->size  ||  ISBLANK(tmp+3)  ||  ISNEWLINE(tmp+3)))
6195
0
            {
6196
0
                MD_CONTAINER* task_container = (n_children > 0 ? &ctx->containers[ctx->n_containers-1] : &container);
6197
0
                task_container->is_task = TRUE;
6198
0
                task_container->task_mark_off = tmp + 1;
6199
0
                off = tmp + 3;
6200
0
                while(off < ctx->size  &&  ISWHITESPACE(off))
6201
0
                    off++;
6202
0
                line->beg = off;
6203
0
            }
6204
0
        }
6205
6206
0
        break;
6207
0
    }
6208
6209
    /* Scan for end of the line. */
6210
    /* Optimization: Use some loop unrolling. */
6211
0
    while(off + 3 < ctx->size  &&  !ISNEWLINE(off+0)  &&  !ISNEWLINE(off+1)
6212
0
                               &&  !ISNEWLINE(off+2)  &&  !ISNEWLINE(off+3))
6213
0
        off += 4;
6214
0
    while(off < ctx->size  &&  !ISNEWLINE(off))
6215
0
        off++;
6216
6217
    /* Set end of the line. */
6218
0
    line->end = off;
6219
6220
    /* But for ATX header, we should exclude the optional trailing mark. */
6221
0
    if(line->type == MD_LINE_ATXHEADER) {
6222
0
        OFF tmp = line->end;
6223
0
        while(tmp > line->beg && ISBLANK(tmp-1))
6224
0
            tmp--;
6225
0
        while(tmp > line->beg && CH(tmp-1) == _T('#'))
6226
0
            tmp--;
6227
0
        if(tmp == line->beg || ISBLANK(tmp-1) || (ctx->parser.flags & MD_FLAG_PERMISSIVEATXHEADERS))
6228
0
            line->end = tmp;
6229
0
    }
6230
6231
    /* Trim trailing spaces. */
6232
0
    if(line->type != MD_LINE_INDENTEDCODE  &&  line->type != MD_LINE_FENCEDCODE  && line->type != MD_LINE_HTML) {
6233
0
        while(line->end > line->beg && ISBLANK(line->end-1))
6234
0
            line->end--;
6235
0
    }
6236
6237
    /* Eat also the new line. */
6238
0
    if(off < ctx->size && CH(off) == _T('\r'))
6239
0
        off++;
6240
0
    if(off < ctx->size && CH(off) == _T('\n'))
6241
0
        off++;
6242
6243
0
    *p_end = off;
6244
6245
    /* If we belong to a list after seeing a blank line, the list is loose. */
6246
0
    if(prev_line_has_list_loosening_effect  &&  line->type != MD_LINE_BLANK  &&  n_parents + n_brothers > 0) {
6247
0
        MD_CONTAINER* c = &ctx->containers[n_parents + n_brothers - 1];
6248
0
        if(c->ch != _T('>')) {
6249
0
            MD_BLOCK* block = (MD_BLOCK*) (((char*)ctx->block_bytes) + c->block_byte_off);
6250
0
            block->flags |= MD_BLOCK_LOOSE_LIST;
6251
0
        }
6252
0
    }
6253
6254
    /* Leave any containers we are not part of anymore. */
6255
0
    if(n_children == 0  &&  n_parents + n_brothers < ctx->n_containers)
6256
0
        MD_CHECK(md_leave_child_containers(ctx, n_parents + n_brothers));
6257
6258
    /* Enter any container we found a mark for. */
6259
0
    if(n_brothers > 0) {
6260
0
        MD_ASSERT(n_brothers == 1);
6261
0
        MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI,
6262
0
                    ctx->containers[n_parents].task_mark_off,
6263
0
                    (ctx->containers[n_parents].is_task ? CH(ctx->containers[n_parents].task_mark_off) : 0),
6264
0
                    MD_BLOCK_CONTAINER_CLOSER));
6265
0
        MD_CHECK(md_push_container_bytes(ctx, MD_BLOCK_LI,
6266
0
                    container.task_mark_off,
6267
0
                    (container.is_task ? CH(container.task_mark_off) : 0),
6268
0
                    MD_BLOCK_CONTAINER_OPENER));
6269
0
        ctx->containers[n_parents].is_task = container.is_task;
6270
0
        ctx->containers[n_parents].task_mark_off = container.task_mark_off;
6271
0
    }
6272
6273
0
    if(n_children > 0)
6274
0
        MD_CHECK(md_enter_child_containers(ctx, n_children));
6275
6276
0
abort:
6277
0
    return ret;
6278
0
}
6279
6280
static int
6281
md_process_line(MD_CTX* ctx, const MD_LINE_ANALYSIS** p_pivot_line, MD_LINE_ANALYSIS* line)
6282
0
{
6283
0
    const MD_LINE_ANALYSIS* pivot_line = *p_pivot_line;
6284
0
    int ret = 0;
6285
6286
    /* Blank line ends current leaf block. */
6287
0
    if(line->type == MD_LINE_BLANK) {
6288
0
        MD_CHECK(md_end_current_block(ctx));
6289
0
        *p_pivot_line = &md_dummy_blank_line;
6290
0
        return 0;
6291
0
    }
6292
6293
0
    if(line->enforce_new_block)
6294
0
        MD_CHECK(md_end_current_block(ctx));
6295
6296
    /* Some line types form block on their own. */
6297
0
    if(line->type == MD_LINE_HR || line->type == MD_LINE_ATXHEADER) {
6298
0
        MD_CHECK(md_end_current_block(ctx));
6299
6300
        /* Add our single-line block. */
6301
0
        MD_CHECK(md_start_new_block(ctx, line));
6302
0
        MD_CHECK(md_add_line_into_current_block(ctx, line));
6303
0
        MD_CHECK(md_end_current_block(ctx));
6304
0
        *p_pivot_line = &md_dummy_blank_line;
6305
0
        return 0;
6306
0
    }
6307
6308
    /* MD_LINE_SETEXTUNDERLINE changes meaning of the current block and ends it. */
6309
0
    if(line->type == MD_LINE_SETEXTUNDERLINE) {
6310
0
        MD_ASSERT(ctx->current_block != NULL);
6311
0
        ctx->current_block->type = MD_BLOCK_H;
6312
0
        ctx->current_block->data = line->data;
6313
0
        ctx->current_block->flags |= MD_BLOCK_SETEXT_HEADER;
6314
0
        MD_CHECK(md_add_line_into_current_block(ctx, line));
6315
0
        MD_CHECK(md_end_current_block(ctx));
6316
0
        if(ctx->current_block == NULL) {
6317
0
            *p_pivot_line = &md_dummy_blank_line;
6318
0
        } else {
6319
            /* This happens if we have consumed all the body as link ref. defs.
6320
             * and downgraded the underline into start of a new paragraph block. */
6321
0
            line->type = MD_LINE_TEXT;
6322
0
            *p_pivot_line = line;
6323
0
        }
6324
0
        return 0;
6325
0
    }
6326
6327
    /* MD_LINE_TABLEUNDERLINE changes meaning of the current block. */
6328
0
    if(line->type == MD_LINE_TABLEUNDERLINE) {
6329
0
        MD_ASSERT(ctx->current_block != NULL);
6330
0
        MD_ASSERT(ctx->current_block->n_lines == 1);
6331
0
        ctx->current_block->type = MD_BLOCK_TABLE;
6332
0
        ctx->current_block->data = line->data;
6333
0
        MD_ASSERT(pivot_line != &md_dummy_blank_line);
6334
0
        ((MD_LINE_ANALYSIS*)pivot_line)->type = MD_LINE_TABLE;
6335
0
        MD_CHECK(md_add_line_into_current_block(ctx, line));
6336
0
        return 0;
6337
0
    }
6338
6339
    /* The current block also ends if the line has different type. */
6340
0
    if(line->type != pivot_line->type)
6341
0
        MD_CHECK(md_end_current_block(ctx));
6342
6343
    /* The current line may start a new block. */
6344
0
    if(ctx->current_block == NULL) {
6345
0
        MD_CHECK(md_start_new_block(ctx, line));
6346
0
        *p_pivot_line = line;
6347
0
    }
6348
6349
    /* In all other cases the line is just a continuation of the current block. */
6350
0
    MD_CHECK(md_add_line_into_current_block(ctx, line));
6351
6352
0
abort:
6353
0
    return ret;
6354
0
}
6355
6356
static int
6357
md_process_doc(MD_CTX *ctx)
6358
0
{
6359
0
    const MD_LINE_ANALYSIS* pivot_line = &md_dummy_blank_line;
6360
0
    MD_LINE_ANALYSIS line_buf[2];
6361
0
    MD_LINE_ANALYSIS* line = &line_buf[0];
6362
0
    OFF off = 0;
6363
0
    int ret = 0;
6364
6365
0
    MD_ENTER_BLOCK(MD_BLOCK_DOC, NULL);
6366
6367
0
    while(off < ctx->size) {
6368
0
        if(line == pivot_line)
6369
0
            line = (line == &line_buf[0] ? &line_buf[1] : &line_buf[0]);
6370
6371
0
        MD_CHECK(md_analyze_line(ctx, off, &off, pivot_line, line));
6372
0
        MD_CHECK(md_process_line(ctx, &pivot_line, line));
6373
0
    }
6374
6375
0
    md_end_current_block(ctx);
6376
6377
0
    MD_CHECK(md_build_ref_def_hashtable(ctx));
6378
6379
    /* Process all blocks. */
6380
0
    MD_CHECK(md_leave_child_containers(ctx, 0));
6381
0
    MD_CHECK(md_process_all_blocks(ctx));
6382
6383
0
    MD_LEAVE_BLOCK(MD_BLOCK_DOC, NULL);
6384
6385
0
abort:
6386
6387
#if 0
6388
    /* Output some memory consumption statistics. */
6389
    {
6390
        char buffer[256];
6391
        sprintf(buffer, "Alloced %u bytes for block buffer.",
6392
                    (unsigned)(ctx->alloc_block_bytes));
6393
        MD_LOG(buffer);
6394
6395
        sprintf(buffer, "Alloced %u bytes for containers buffer.",
6396
                    (unsigned)(ctx->alloc_containers * sizeof(MD_CONTAINER)));
6397
        MD_LOG(buffer);
6398
6399
        sprintf(buffer, "Alloced %u bytes for marks buffer.",
6400
                    (unsigned)(ctx->alloc_marks * sizeof(MD_MARK)));
6401
        MD_LOG(buffer);
6402
6403
        sprintf(buffer, "Alloced %u bytes for aux. buffer.",
6404
                    (unsigned)(ctx->alloc_buffer * sizeof(MD_CHAR)));
6405
        MD_LOG(buffer);
6406
    }
6407
#endif
6408
6409
0
    return ret;
6410
0
}
6411
6412
6413
/********************
6414
 ***  Public API  ***
6415
 ********************/
6416
6417
int
6418
md_parse(const MD_CHAR* text, MD_SIZE size, const MD_PARSER* parser, void* userdata)
6419
0
{
6420
0
    MD_CTX ctx;
6421
0
    int i;
6422
0
    int ret;
6423
6424
0
    if(parser->abi_version != 0) {
6425
0
        if(parser->debug_log != NULL)
6426
0
            parser->debug_log("Unsupported abi_version.", userdata);
6427
0
        return -1;
6428
0
    }
6429
6430
    /* Setup context structure. */
6431
0
    memset(&ctx, 0, sizeof(MD_CTX));
6432
0
    ctx.text = text;
6433
0
    ctx.size = size;
6434
0
    memcpy(&ctx.parser, parser, sizeof(MD_PARSER));
6435
0
    ctx.userdata = userdata;
6436
0
    ctx.code_indent_offset = (ctx.parser.flags & MD_FLAG_NOINDENTEDCODEBLOCKS) ? (OFF)(-1) : 4;
6437
0
    md_build_mark_char_map(&ctx);
6438
0
    ctx.doc_ends_with_newline = (size > 0  &&  ISNEWLINE_(text[size-1]));
6439
0
    ctx.max_ref_def_output = 16 * MIN(size, (MD_SIZE)(1024 * 1024 / 16));
6440
6441
    /* Reset all mark stacks and lists. */
6442
0
    for(i = 0; i < (int) SIZEOF_ARRAY(ctx.opener_stacks); i++)
6443
0
        ctx.opener_stacks[i].top = -1;
6444
0
    ctx.ptr_stack.top = -1;
6445
0
    ctx.unresolved_link_head = -1;
6446
0
    ctx.unresolved_link_tail = -1;
6447
0
    ctx.table_cell_boundaries_head = -1;
6448
0
    ctx.table_cell_boundaries_tail = -1;
6449
6450
    /* All the work. */
6451
0
    ret = md_process_doc(&ctx);
6452
6453
    /* Clean-up. */
6454
0
    md_free_ref_defs(&ctx);
6455
0
    md_free_ref_def_hashtable(&ctx);
6456
0
    free(ctx.buffer);
6457
0
    free(ctx.marks);
6458
0
    free(ctx.block_bytes);
6459
0
    free(ctx.containers);
6460
6461
0
    return ret;
6462
0
}