]> git.wincent.com - wikitext.git/blob - ext/parser.c
69c0ff7faec8abfa2352a262e17d5e42407ee17a
[wikitext.git] / ext / parser.c
1 // Copyright 2007-2009 Wincent Colaiuta. All rights reserved.
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are met:
5 //
6 // 1. Redistributions of source code must retain the above copyright notice,
7 //    this list of conditions and the following disclaimer.
8 // 2. Redistributions in binary form must reproduce the above copyright notice,
9 //    this list of conditions and the following disclaimer in the documentation
10 //    and/or other materials provided with the distribution.
11 //
12 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
13 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
16 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
17 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
18 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
19 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
20 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
21 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
22 // POSSIBILITY OF SUCH DAMAGE.
23
24 #include <stdbool.h>
25
26 #include "parser.h"
27 #include "ary.h"
28 #include "str.h"
29 #include "wikitext.h"
30 #include "wikitext_ragel.h"
31
32 #define IN(type) ary_includes(parser->scope, type)
33
34 // poor man's object orientation in C:
35 // instead of parsing around multiple parameters between functions in the parser
36 // we pack everything into a struct and pass around only a pointer to that
37 typedef struct
38 {
39     str_t   *capture;               // capturing to link_target, link_text, or NULL (direct to output, not capturing)
40     str_t   *output;                // for accumulating output to be returned
41     str_t   *link_target;           // short term "memory" for parsing links
42     str_t   *link_text;             // short term "memory" for parsing links
43     str_t   *line_ending;
44     str_t   *tabulation;            // caching buffer for emitting indentation
45     ary_t   *scope;                 // stack for tracking scope
46     ary_t   *line;                  // stack for tracking scope as implied by current line
47     ary_t   *line_buffer;           // stack for tracking raw tokens (not scope) on current line
48     VALUE   external_link_class;    // CSS class applied to external links
49     VALUE   mailto_class;           // CSS class applied to email (mailto) links
50     VALUE   img_prefix;             // path prepended when emitting img tags
51     int     base_indent;            // controlled by the :indent option to Wikitext::Parser#parse
52     int     current_indent;         // fluctuates according to currently nested structures
53     int     base_heading_level;
54     bool    pending_crlf;
55     bool    autolink;
56     bool    space_to_underscore;
57 } parser_t;
58
59 const char escaped_no_wiki_start[]      = "&lt;nowiki&gt;";
60 const char escaped_no_wiki_end[]        = "&lt;/nowiki&gt;";
61 const char literal_strong_em[]          = "'''''";
62 const char literal_strong[]             = "'''";
63 const char literal_em[]                 = "''";
64 const char escaped_em_start[]           = "&lt;em&gt;";
65 const char escaped_em_end[]             = "&lt;/em&gt;";
66 const char escaped_strong_start[]       = "&lt;strong&gt;";
67 const char escaped_strong_end[]         = "&lt;/strong&gt;";
68 const char escaped_tt_start[]           = "&lt;tt&gt;";
69 const char escaped_tt_end[]             = "&lt;/tt&gt;";
70 const char literal_h6[]                 = "======";
71 const char literal_h5[]                 = "=====";
72 const char literal_h4[]                 = "====";
73 const char literal_h3[]                 = "===";
74 const char literal_h2[]                 = "==";
75 const char literal_h1[]                 = "=";
76 const char pre_start[]                  = "<pre>";
77 const char pre_end[]                    = "</pre>";
78 const char escaped_pre_start[]          = "&lt;pre&gt;";
79 const char escaped_pre_end[]            = "&lt;/pre&gt;";
80 const char blockquote_start[]           = "<blockquote>";
81 const char blockquote_end[]             = "</blockquote>";
82 const char escaped_blockquote_start[]   = "&lt;blockquote&gt;";
83 const char escaped_blockquote_end[]     = "&lt;/blockquote&gt;";
84 const char strong_em_start[]            = "<strong><em>";
85 const char strong_start[]               = "<strong>";
86 const char strong_end[]                 = "</strong>";
87 const char em_start[]                   = "<em>";
88 const char em_end[]                     = "</em>";
89 const char tt_start[]                   = "<tt>";
90 const char tt_end[]                     = "</tt>";
91 const char ol_start[]                   = "<ol>";
92 const char ol_end[]                     = "</ol>";
93 const char ul_start[]                   = "<ul>";
94 const char ul_end[]                     = "</ul>";
95 const char li_start[]                   = "<li>";
96 const char li_end[]                     = "</li>";
97 const char h6_start[]                   = "<h6>";
98 const char h6_end[]                     = "</h6>";
99 const char h5_start[]                   = "<h5>";
100 const char h5_end[]                     = "</h5>";
101 const char h4_start[]                   = "<h4>";
102 const char h4_end[]                     = "</h4>";
103 const char h3_start[]                   = "<h3>";
104 const char h3_end[]                     = "</h3>";
105 const char h2_start[]                   = "<h2>";
106 const char h2_end[]                     = "</h2>";
107 const char h1_start[]                   = "<h1>";
108 const char h1_end[]                     = "</h1>";
109 const char p_start[]                    = "<p>";
110 const char p_end[]                      = "</p>";
111 const char space[]                      = " ";
112 const char a_start[]                    = "<a href=\"";
113 const char a_class[]                    = "\" class=\"";
114 const char a_start_close[]              = "\">";
115 const char a_end[]                      = "</a>";
116 const char link_start[]                 = "[[";
117 const char link_end[]                   = "]]";
118 const char separator[]                  = "|";
119 const char ext_link_start[]             = "[";
120 const char backtick[]                   = "`";
121 const char quote[]                      = "\"";
122 const char ampersand[]                  = "&";
123 const char quot_entity[]                = "&quot;";
124 const char amp_entity[]                 = "&amp;";
125 const char lt_entity[]                  = "&lt;";
126 const char gt_entity[]                  = "&gt;";
127 const char escaped_blockquote[]         = "&gt; ";
128 const char ext_link_end[]               = "]";
129 const char literal_img_start[]          = "{{";
130 const char img_start[]                  = "<img src=\"";
131 const char img_end[]                    = "\" />";
132 const char img_alt[]                    = "\" alt=\"";
133
134 // Mark the parser struct designated by ptr as a participant in Ruby's
135 // mark-and-sweep garbage collection scheme. A variable named name is placed on
136 // the C stack to prevent the structure from being prematurely collected.
137 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
138
139 parser_t *parser_new(void)
140 {
141     parser_t *parser                = ALLOC_N(parser_t, 1);
142     parser->capture                 = NULL; // not a real instance, pointer to other member's instance
143     parser->output                  = str_new();
144     parser->link_target             = str_new();
145     parser->link_text               = str_new();
146     parser->line_ending             = NULL; // caller should set up
147     parser->tabulation              = str_new();
148     parser->scope                   = ary_new();
149     parser->line                    = ary_new();
150     parser->line_buffer             = ary_new();
151     parser->external_link_class     = Qnil; // caller should set up
152     parser->mailto_class            = Qnil; // caller should set up
153     parser->img_prefix              = Qnil; // caller should set up
154     parser->base_indent             = 0;
155     parser->current_indent          = 0;
156     parser->base_heading_level      = 0;
157     parser->pending_crlf            = false;
158     parser->autolink                = true;
159     parser->space_to_underscore     = true;
160     return parser;
161 }
162
163 void parser_free(parser_t *parser)
164 {
165     // we don't free parser->capture; it's just a redundant pointer
166     if (parser->output)         str_free(parser->output);
167     if (parser->link_target)    str_free(parser->link_target);
168     if (parser->link_text)      str_free(parser->link_text);
169     if (parser->line_ending)    str_free(parser->line_ending);
170     if (parser->tabulation)     str_free(parser->tabulation);
171     if (parser->scope)          ary_free(parser->scope);
172     if (parser->line)           ary_free(parser->line);
173     if (parser->line_buffer)    ary_free(parser->line_buffer);
174     free(parser);
175 }
176
177 // for testing and debugging only
178 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
179 {
180     if (NIL_P(string))
181         return Qnil;
182     string = StringValue(string);
183     VALUE tokens = rb_ary_new();
184     char *p = RSTRING_PTR(string);
185     long len = RSTRING_LEN(string);
186     char *pe = p + len;
187     token_t token;
188     next_token(&token, NULL, p, pe);
189     rb_ary_push(tokens, _Wikitext_token(&token));
190     while (token.type != END_OF_FILE)
191     {
192         next_token(&token, &token, NULL, pe);
193         rb_ary_push(tokens, _Wikitext_token(&token));
194     }
195     return tokens;
196 }
197
198 // for benchmarking raw tokenization speed only
199 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
200 {
201     if (NIL_P(string))
202         return Qnil;
203     string = StringValue(string);
204     char *p = RSTRING_PTR(string);
205     long len = RSTRING_LEN(string);
206     char *pe = p + len;
207     token_t token;
208     next_token(&token, NULL, p, pe);
209     while (token.type != END_OF_FILE)
210         next_token(&token, &token, NULL, pe);
211     return Qnil;
212 }
213
214 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
215 {
216     // process arguments
217     VALUE string, options;
218     if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
219         options = Qnil;
220     if (NIL_P(string))
221         return Qnil;
222     string = StringValue(string);
223     VALUE tokens = rb_ary_new();
224
225     // check instance variables
226     VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
227
228     // process options hash (can override instance variables)
229     if (!NIL_P(options) && TYPE(options) == T_HASH)
230     {
231         if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
232             min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
233     }
234     int min_len = NIL_P(min) ? 3 : NUM2INT(min);
235     if (min_len < 0)
236         min_len = 0;
237
238     // set up scanner
239     char *p = RSTRING_PTR(string);
240     long len = RSTRING_LEN(string);
241     char *pe = p + len;
242     token_t token;
243     token_t *_token = &token;
244     next_token(&token, NULL, p, pe);
245     while (token.type != END_OF_FILE)
246     {
247         switch (token.type)
248         {
249             case URI:
250             case MAIL:
251             case ALNUM:
252                 if (TOKEN_LEN(_token) >= min_len)
253                     rb_ary_push(tokens, TOKEN_TEXT(_token));
254                 break;
255             default:
256                 // ignore everything else
257                 break;
258         }
259         next_token(&token, &token, NULL, pe);
260     }
261     return tokens;
262 }
263
264 // we downcase "in place", overwriting the original contents of the buffer
265 void _Wikitext_downcase_bang(char *ptr, long len)
266 {
267     for (long i = 0; i < len; i++)
268     {
269         if (ptr[i] >= 'A' && ptr[i] <= 'Z')
270             ptr[i] += 32;
271     }
272 }
273
274 // prepare hyperlink and append it to parser->output
275 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
276 // or merely the literal link target
277 // if link_text is Qnil, the link_target is re-used for the link text
278 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class, bool check_autolink)
279 {
280     if (check_autolink && !parser->autolink)
281         str_append_string(parser->output, link_target);
282     else
283     {
284         str_append(parser->output, a_start, sizeof(a_start) - 1);               // <a href="
285         if (!NIL_P(link_prefix))
286             str_append_string(parser->output, link_prefix);
287         str_append_string(parser->output, link_target);
288
289         // special handling for mailto URIs
290         const char *mailto = "mailto:";
291         if (NIL_P(link_prefix) &&
292             RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
293             strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
294             link_class = parser->mailto_class; // use mailto_class from parser
295         if (link_class != Qnil)
296         {
297             str_append(parser->output, a_class, sizeof(a_class) - 1);           // " class="
298             str_append_string(parser->output, link_class);
299         }
300         str_append(parser->output, a_start_close, sizeof(a_start_close) - 1);   // ">
301         if (NIL_P(link_text)) // re-use link_target
302             str_append_string(parser->output, link_target);
303         else
304             str_append_string(parser->output, link_text);
305         str_append(parser->output, a_end, sizeof(a_end) - 1);                   // </a>
306     }
307 }
308
309 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
310 {
311     str_append(parser->output, img_start, sizeof(img_start) - 1);   // <img src="
312     if (!NIL_P(parser->img_prefix) && *token_ptr != '/')            // len always > 0
313         str_append_string(parser->output, parser->img_prefix);
314     str_append(parser->output, token_ptr, token_len);
315     str_append(parser->output, img_alt, sizeof(img_alt) - 1);       // " alt="
316     str_append(parser->output, token_ptr, token_len);
317     str_append(parser->output, img_end, sizeof(img_end) - 1);       // " />
318 }
319
320 // will emit indentation only if we are about to emit any of:
321 //      <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
322 // each time we enter one of those spans must ++ the indentation level
323 void _Wikitext_indent(parser_t *parser)
324 {
325     if (parser->base_indent == -1) // indentation disabled
326         return;
327     int space_count = parser->current_indent + parser->base_indent;
328     if (space_count > 0)
329     {
330         char *old_end, *new_end;
331         if (parser->tabulation->len < space_count)
332             str_grow(parser->tabulation, space_count); // reallocates if necessary
333         old_end = parser->tabulation->ptr + parser->tabulation->len;
334         new_end = parser->tabulation->ptr + space_count;
335         while (old_end < new_end)
336             *old_end++ = ' ';
337         if (space_count > parser->tabulation->len)
338             parser->tabulation->len = space_count;
339         str_append(parser->output, parser->tabulation->ptr, space_count);
340     }
341     parser->current_indent += 2;
342 }
343
344 void _Wikitext_dedent(parser_t *parser, VALUE emit)
345 {
346     if (parser->base_indent == -1) // indentation disabled
347         return;
348     parser->current_indent -= 2;
349     if (emit != Qtrue)
350         return;
351     int space_count = parser->current_indent + parser->base_indent;
352     if (space_count > 0)
353         str_append(parser->output, parser->tabulation->ptr, space_count);
354 }
355
356 // Pops a single item off the parser's scope stack.
357 // A corresponding closing tag is written to the target string.
358 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
359 void _Wikitext_pop_from_stack(parser_t *parser, str_t *target)
360 {
361     int top = ary_entry(parser->scope, -1);
362     if (NO_ITEM(top))
363         return;
364     if (!target)
365         target = parser->output;
366
367     // for headings, take base_heading_level into account
368     if (top >= H1_START && top <= H6_START)
369     {
370         top += parser->base_heading_level;
371         // no need to check for underflow (base_heading_level is never negative)
372         if (top > H6_START)
373             top = H6_START;
374     }
375
376     switch (top)
377     {
378         case PRE:
379         case PRE_START:
380             str_append(target, pre_end, sizeof(pre_end) - 1);
381             str_append_str(target, parser->line_ending);
382             _Wikitext_dedent(parser, Qfalse);
383             break;
384
385         case BLOCKQUOTE:
386         case BLOCKQUOTE_START:
387             _Wikitext_dedent(parser, Qtrue);
388             str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
389             str_append_str(target, parser->line_ending);
390             break;
391
392         case NO_WIKI_START:
393             // not a real HTML tag; so nothing to pop
394             break;
395
396         case STRONG:
397         case STRONG_START:
398             str_append(target, strong_end, sizeof(strong_end) - 1);
399             break;
400
401         case EM:
402         case EM_START:
403             str_append(target, em_end, sizeof(em_end) - 1);
404             break;
405
406         case TT:
407         case TT_START:
408             str_append(target, tt_end, sizeof(tt_end) - 1);
409             break;
410
411         case OL:
412             _Wikitext_dedent(parser, Qtrue);
413             str_append(target, ol_end, sizeof(ol_end) - 1);
414             str_append_str(target, parser->line_ending);
415             break;
416
417         case UL:
418             _Wikitext_dedent(parser, Qtrue);
419             str_append(target, ul_end, sizeof(ul_end) - 1);
420             str_append_str(target, parser->line_ending);
421             break;
422
423         case NESTED_LIST:
424             // next token to pop will be a LI
425             // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
426             // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
427             // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
428             // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
429             _Wikitext_dedent(parser, Qtrue);    // we really only want to emit the spaces
430             parser->current_indent += 2;        // we don't want to decrement the actual indent level, so put it back
431             break;
432
433         case LI:
434             str_append(target, li_end, sizeof(li_end) - 1);
435             str_append_str(target, parser->line_ending);
436             _Wikitext_dedent(parser, Qfalse);
437             break;
438
439         case H6_START:
440             str_append(target, h6_end, sizeof(h6_end) - 1);
441             str_append_str(target, parser->line_ending);
442             _Wikitext_dedent(parser, Qfalse);
443             break;
444
445         case H5_START:
446             str_append(target, h5_end, sizeof(h5_end) - 1);
447             str_append_str(target, parser->line_ending);
448             _Wikitext_dedent(parser, Qfalse);
449             break;
450
451         case H4_START:
452             str_append(target, h4_end, sizeof(h4_end) - 1);
453             str_append_str(target, parser->line_ending);
454             _Wikitext_dedent(parser, Qfalse);
455             break;
456
457         case H3_START:
458             str_append(target, h3_end, sizeof(h3_end) - 1);
459             str_append_str(target, parser->line_ending);
460             _Wikitext_dedent(parser, Qfalse);
461             break;
462
463         case H2_START:
464             str_append(target, h2_end, sizeof(h2_end) - 1);
465             str_append_str(target, parser->line_ending);
466             _Wikitext_dedent(parser, Qfalse);
467             break;
468
469         case H1_START:
470             str_append(target, h1_end, sizeof(h1_end) - 1);
471             str_append_str(target, parser->line_ending);
472             _Wikitext_dedent(parser, Qfalse);
473             break;
474
475         case LINK_START:
476             // not an HTML tag; so nothing to emit
477             break;
478
479         case EXT_LINK_START:
480             // not an HTML tag; so nothing to emit
481             break;
482
483         case PATH:
484             // not an HTML tag; so nothing to emit
485             break;
486
487         case SPACE:
488             // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
489             break;
490
491         case SEPARATOR:
492             // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
493             break;
494
495         case P:
496             str_append(target, p_end, sizeof(p_end) - 1);
497             str_append_str(target, parser->line_ending);
498             _Wikitext_dedent(parser, Qfalse);
499             break;
500
501         case END_OF_FILE:
502             // nothing to do
503             break;
504
505         default:
506             // should probably raise an exception here
507             break;
508     }
509     ary_pop(parser->scope);
510 }
511
512 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
513 // If including is true then the item itself is also popped.
514 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
515 void _Wikitext_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
516 {
517     int continue_looping = 1;
518     do
519     {
520         int top = ary_entry(parser->scope, -1);
521         if (NO_ITEM(top))
522             return;
523         if (top == item)
524         {
525             if (!including)
526                 return;
527             continue_looping = 0;
528         }
529         _Wikitext_pop_from_stack(parser, target);
530     } while (continue_looping);
531 }
532
533 void _Wikitext_pop_all_from_stack(parser_t *parser)
534 {
535     for (int i = 0, max = parser->scope->count; i < max; i++)
536         _Wikitext_pop_from_stack(parser, NULL);
537 }
538
539 void _Wikitext_start_para_if_necessary(parser_t *parser)
540 {
541     if (parser->capture)
542         return;
543
544     // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
545     if (parser->scope->count == 0 ||
546         ary_entry(parser->scope, -1) == BLOCKQUOTE ||
547         ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
548     {
549         _Wikitext_indent(parser);
550         str_append(parser->output, p_start, sizeof(p_start) - 1);
551         ary_push(parser->scope, P);
552         ary_push(parser->line, P);
553     }
554     else if (parser->pending_crlf)
555     {
556         if (IN(P))
557             // already in a paragraph block; convert pending CRLF into a space
558             str_append(parser->output, space, sizeof(space) - 1);
559         else if (IN(PRE))
560             // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
561             str_append_str(parser->output, parser->line_ending);
562     }
563     parser->pending_crlf = false;
564 }
565
566 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
567 {
568     if (parser->pending_crlf)
569     {
570         str_append_str(parser->output, parser->line_ending);
571         parser->pending_crlf = false;
572     }
573 }
574
575 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
576 // For example, given input like:
577 //
578 //      > > foo
579 //      bar
580 //
581 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
582 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
583 //
584 //      foo
585 //      > > bar
586 //
587 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
588 // but not on the line scope:
589 //
590 //      <blockquote>foo
591 //      bar</blockquote>
592 //
593 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
594 // on the line scope.
595 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
596 // entering the for loop.
597 void _Wikitext_pop_excess_elements(parser_t *parser)
598 {
599     if (parser->capture)
600         return;
601     for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
602     {
603         // special case for last item on scope
604         if (i - j == 1)
605         {
606             // don't auto-pop P if it is only item on scope
607             if (ary_entry(parser->scope, -1) == P)
608             {
609                 // add P to the line scope to prevent us entering the loop at all next time around
610                 ary_push(parser->line, P);
611                 continue;
612             }
613         }
614         _Wikitext_pop_from_stack(parser, NULL);
615     }
616 }
617
618 #define INVALID_ENCODING(msg)  do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
619
620 // convert a single UTF-8 codepoint to UTF-32
621 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
622 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
623 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
624 // raises a RangeError if the supplied character is invalid UTF-8
625 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
626 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
627 {
628     uint32_t dest;
629     if ((unsigned char)src[0] <= 0x7f)                      // ASCII
630     {
631         dest = src[0];
632         *width_out = 1;
633     }
634     else if ((src[0] & 0xe0) == 0xc0)                       // byte starts with 110..... : this should be a two-byte sequence
635     {
636         if (src + 1 >= end)
637             INVALID_ENCODING("truncated byte sequence");    // no second byte
638         else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
639             INVALID_ENCODING("overlong encoding");          // overlong encoding: lead byte of 110..... but code point <= 127
640         else if ((src[1] & 0xc0) != 0x80 )
641             INVALID_ENCODING("malformed byte sequence");    // should have second byte starting with 10......
642         dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
643         *width_out = 2;
644     }
645     else if ((src[0] & 0xf0) == 0xe0)                       // byte starts with 1110.... : this should be a three-byte sequence
646     {
647         if (src + 2 >= end)
648             INVALID_ENCODING("truncated byte sequence");    // missing second or third byte
649         else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
650             INVALID_ENCODING("malformed byte sequence");    // should have second and third bytes starting with 10......
651         dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
652         *width_out = 3;
653     }
654     else if ((src[0] & 0xf8) == 0xf0)                       // bytes starts with 11110... : this should be a four-byte sequence
655     {
656         if (src + 3 >= end)
657             INVALID_ENCODING("truncated byte sequence");    // missing second, third, or fourth byte
658         else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
659             INVALID_ENCODING("overlong encoding");          // disallowed by RFC 3629 (codepoints above 0x10ffff)
660         else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
661             INVALID_ENCODING("malformed byte sequence");    // should have second and third bytes starting with 10......
662         dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
663         *width_out = 4;
664     }
665     else                                                    // invalid input
666         INVALID_ENCODING("unexpected byte");
667     return dest;
668 }
669
670 void _Wikitext_append_entity_from_utf32_char(char *output, uint32_t character)
671 {
672     // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
673     char hex_string[8]  = { '&', '#', 'x', 0, 0, 0, 0, ';' };
674     char scratch        = (character & 0xf000) >> 12;
675     hex_string[3]       = (scratch <= 9 ? scratch + 48 : scratch + 87);
676     scratch             = (character & 0x0f00) >> 8;
677     hex_string[4]       = (scratch <= 9 ? scratch + 48 : scratch + 87);
678     scratch             = (character & 0x00f0) >> 4;
679     hex_string[5]       = (scratch <= 9 ? scratch + 48 : scratch + 87);
680     scratch             = character & 0x000f;
681     hex_string[6]       = (scratch <= 9 ? scratch + 48 : scratch + 87);
682     memcpy(output, hex_string, sizeof(hex_string));
683 }
684
685 // trim parser->link_text in place
686 void _Wikitext_parser_trim_link_text(parser_t *parser)
687 {
688     char    *src        = parser->link_text->ptr;
689     char    *start      = src;                  // remember this so we can check if we're at the start
690     char    *left       = src;
691     char    *non_space  = src;                  // remember last non-space character output
692     long    len         = parser->link_text->len;
693     char    *end        = src + len;
694     while (src < end)
695     {
696         if (*src == ' ')
697         {
698             if (src == left)
699                 left++;
700         }
701         else
702             non_space = src;
703         src++;
704     }
705     if (left != start || non_space + 1 != end)
706     {
707         // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
708         parser->link_text->len = (non_space + 1) - left;
709         memmove(parser->link_text->ptr, left, parser->link_text->len);
710     }
711 }
712
713 // - non-printable (non-ASCII) characters converted to numeric entities
714 // - QUOT and AMP characters converted to named entities
715 // - if rollback is true, there is no special treatment of spaces
716 // - if rollback is false, leading and trailing whitespace trimmed
717 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, bool rollback)
718 {
719     char    *src    = parser->link_target->ptr;
720     char    *start  = src;                  // remember this so we can check if we're at the start
721     long    len     = parser->link_target->len;
722     char    *end    = src + len;
723
724     // start with a destination buffer twice the size of the source, will realloc if necessary
725     // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
726     // this efficiently handles the most common case (where the size of the buffer doesn't change much)
727     char    *dest       = ALLOC_N(char, len * 2);
728     char    *dest_ptr   = dest; // hang on to this so we can pass it to free() later
729     char    *non_space  = dest; // remember last non-space character output
730     while (src < end)
731     {
732         // need at most 8 characters (8 bytes) to display each character
733         if (dest + 8 > dest_ptr + len)                      // outgrowing buffer, must reallocate
734         {
735             char *old_dest      = dest;
736             char *old_dest_ptr  = dest_ptr;
737             len                 = len + (end - src) * 8;    // allocate enough for worst case
738             dest                = realloc(dest_ptr, len);   // will never have to realloc more than once
739             if (dest == NULL)
740             {
741                 // would have used reallocf, but this has to run on Linux too, not just Darwin
742                 free(dest_ptr);
743                 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
744             }
745             dest_ptr    = dest;
746             dest        = dest_ptr + (old_dest - old_dest_ptr);
747             non_space   = dest_ptr + (non_space - old_dest_ptr);
748         }
749
750         if (*src == '"')
751         {
752             char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' };  // no trailing NUL
753             memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
754             dest += sizeof(quot_entity_literal);
755         }
756         else if (*src == '&')
757         {
758             char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' };    // no trailing NUL
759             memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
760             dest += sizeof(amp_entity_literal);
761         }
762         else if (*src == '<' || *src == '>')
763         {
764             free(dest_ptr);
765             rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
766         }
767         else if (*src == ' ' && src == start && !rollback)
768             start++;                            // we eat leading space
769         else if (*src >= 0x20 && *src <= 0x7e)  // printable ASCII
770         {
771             *dest = *src;
772             dest++;
773         }
774         else    // all others: must convert to entities
775         {
776             long        width;
777             _Wikitext_append_entity_from_utf32_char(dest, _Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
778             dest        += 8; // always  8 characters (&#x0000;)
779             src         += width;
780             non_space   = dest;
781             continue;
782         }
783         if (*src != ' ')
784             non_space = dest;
785         src++;
786     }
787
788     // trim trailing space if necessary
789     if (!rollback && non_space > dest_ptr && dest != non_space)
790         len = non_space - dest_ptr;
791     else
792         len = dest - dest_ptr;
793     VALUE out = rb_str_new(dest_ptr, len);
794     free(dest_ptr);
795     return out;
796 }
797
798 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
799 {
800     parser_t parser;
801     parser.link_target = str_new_from_string(string);
802     GC_WRAP_STR(parser.link_target, link_target_gc);
803     return _Wikitext_parser_sanitize_link_target(&parser, false);
804 }
805
806 // encodes the input string according to RFCs 2396 and 2718
807 // leading and trailing whitespace trimmed
808 // note that the first character of the target link is not case-sensitive
809 // (this is a recommended application-level constraint; it is not imposed at this level)
810 // this is to allow links like:
811 //         ...the [[foo]] is...
812 // to be equivalent to:
813 //         thing. [[Foo]] was...
814 static void _Wikitext_parser_encode_link_target(parser_t *parser)
815 {
816     VALUE in                = string_from_str(parser->link_target);
817     char        *input      = RSTRING_PTR(in);
818     char        *start      = input;            // remember this so we can check if we're at the start
819     long        len         = RSTRING_LEN(in);
820     if (!(len > 0))
821         return;
822     char        *end        = input + len;
823     static char hex[]       = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
824
825     // to avoid most reallocations start with a destination buffer twice the size of the source
826     // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
827     // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
828     // the worst case is where _every_ byte must be written out using 3 bytes
829     long        dest_len    = len * 2;
830     char        *dest       = ALLOC_N(char, dest_len);
831     char        *dest_ptr   = dest; // hang on to this so we can pass it to free() later
832     char        *non_space  = dest; // remember last non-space character output
833     for (; input < end; input++)
834     {
835         if ((dest + 3) > (dest_ptr + dest_len))     // worst case: a single character may grow to 3 characters once encoded
836         {
837             // outgrowing buffer, must reallocate
838             char *old_dest      = dest;
839             char *old_dest_ptr  = dest_ptr;
840             dest_len            += len;
841             dest                = realloc(dest_ptr, dest_len);
842             if (dest == NULL)
843             {
844                 // would have used reallocf, but this has to run on Linux too, not just Darwin
845                 free(dest_ptr);
846                 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
847             }
848             dest_ptr    = dest;
849             dest        = dest_ptr + (old_dest - old_dest_ptr);
850             non_space   = dest_ptr + (non_space - old_dest_ptr);
851         }
852
853         // pass through unreserved characters
854         if (((*input >= 'a') && (*input <= 'z')) ||
855             ((*input >= 'A') && (*input <= 'Z')) ||
856             ((*input >= '0') && (*input <= '9')) ||
857             (*input == '-') ||
858             (*input == '_') ||
859             (*input == '.') ||
860             (*input == '~'))
861         {
862             *dest++     = *input;
863             non_space   = dest;
864         }
865         else if (*input == ' ' && input == start)
866             start++;                    // we eat leading space
867         else if (*input == ' ' && parser->space_to_underscore)
868             *dest++     = '_';
869         else    // everything else gets URL-encoded
870         {
871             *dest++     = '%';
872             *dest++     = hex[(unsigned char)(*input) / 16];   // left
873             *dest++     = hex[(unsigned char)(*input) % 16];   // right
874             if (*input != ' ')
875                 non_space = dest;
876         }
877     }
878
879     // trim trailing space if necessary
880     if (non_space > dest_ptr && dest != non_space)
881         dest_len = non_space - dest_ptr;
882     else
883         dest_len = dest - dest_ptr;
884
885     // TOOD: try to avoid this copy by working directly inside link_target buffer
886     str_clear(parser->link_target);
887     str_append(parser->link_target, dest_ptr, dest_len);
888     free(dest_ptr);
889 }
890
891 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
892 {
893     parser_t parser;
894     parser.space_to_underscore      = false;
895     parser.link_target              = str_new_from_string(in);
896     GC_WRAP_STR(parser.link_target, link_target_gc);
897     _Wikitext_parser_encode_link_target(&parser);
898     return string_from_str(parser.link_target);
899 }
900
901 // this method exposed for testing only
902 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
903 {
904     parser_t parser;
905     parser.space_to_underscore      = false;
906     parser.link_target              = str_new_from_string(in);
907     GC_WRAP_STR(parser.link_target, link_target_gc);
908     _Wikitext_parser_encode_link_target(&parser);
909     return string_from_str(parser.link_target);
910 }
911
912 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
913 // returns 0 (false) otherwise
914 bool _Wikitext_blank(str_t *str)
915 {
916     if (str->len == 0)
917         return true;
918     for (char *ptr = str->ptr,
919         *end = str->ptr + str->len;
920         ptr < end; ptr++)
921     {
922         if (*ptr != ' ')
923             return false;
924     }
925     return true;
926 }
927
928 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
929 {
930     if (!IN(LINK_START))
931         return; // nothing to do!
932     int scope_includes_separator = IN(SEPARATOR);
933     _Wikitext_pop_from_stack_up_to(parser, NULL, LINK_START, true);
934     str_append(parser->output, link_start, sizeof(link_start) - 1);
935     if (parser->link_target->len > 0)
936     {
937         // TODO: make _Wikitext_parser_sanitize_link_target return something else? or append directly to buffer would be much better
938         VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, true);
939         str_append_string(parser->output, sanitized);
940         if (scope_includes_separator)
941         {
942             str_append(parser->output, separator, sizeof(separator) - 1);
943             if (parser->link_text->len > 0)
944                 str_append_str(parser->output, parser->link_text);
945         }
946     }
947     parser->capture = NULL;
948     str_clear(parser->link_target);
949     str_clear(parser->link_text);
950 }
951
952 void _Wikitext_rollback_failed_external_link(parser_t *parser)
953 {
954     if (!IN(EXT_LINK_START))
955         return; // nothing to do!
956
957     // store a couple of values before popping
958     int scope_includes_space = IN(SPACE);
959     VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
960     _Wikitext_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
961
962     str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
963     if (parser->link_target->len > 0)
964     {
965         _Wikitext_append_hyperlink(parser, Qnil, string_from_str(parser->link_target), Qnil, link_class, true);
966         if (scope_includes_space)
967         {
968             str_append(parser->output, space, sizeof(space) - 1);
969             if (parser->link_text->len > 0)
970                 str_append_str(parser->output, parser->link_text);
971         }
972     }
973     parser->capture = NULL;
974     str_clear(parser->link_target);
975     str_clear(parser->link_text);
976 }
977
978 void _Wikitext_rollback_failed_link(parser_t *parser)
979 {
980     _Wikitext_rollback_failed_internal_link(parser);
981     _Wikitext_rollback_failed_external_link(parser);
982 }
983
984 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
985 {
986     // process arguments
987     VALUE options;
988     if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
989         options = Qnil;
990
991     // defaults
992     VALUE autolink                      = Qtrue;
993     VALUE line_ending                   = rb_str_new2("\n");
994     VALUE external_link_class           = rb_str_new2("external");
995     VALUE mailto_class                  = rb_str_new2("mailto");
996     VALUE internal_link_prefix          = rb_str_new2("/wiki/");
997     VALUE img_prefix                    = rb_str_new2("/images/");
998     VALUE space_to_underscore           = Qtrue;
999     VALUE minimum_fulltext_token_length = INT2NUM(3);
1000     VALUE base_heading_level            = INT2NUM(0);
1001
1002     // process options hash (override defaults)
1003     if (!NIL_P(options) && TYPE(options) == T_HASH)
1004     {
1005 #define OVERRIDE_IF_SET(name)   rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1006                                 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1007         autolink                        = OVERRIDE_IF_SET(autolink);
1008         line_ending                     = OVERRIDE_IF_SET(line_ending);
1009         external_link_class             = OVERRIDE_IF_SET(external_link_class);
1010         mailto_class                    = OVERRIDE_IF_SET(mailto_class);
1011         internal_link_prefix            = OVERRIDE_IF_SET(internal_link_prefix);
1012         img_prefix                      = OVERRIDE_IF_SET(img_prefix);
1013         space_to_underscore             = OVERRIDE_IF_SET(space_to_underscore);
1014         minimum_fulltext_token_length   = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1015         base_heading_level              = OVERRIDE_IF_SET(base_heading_level);
1016     }
1017
1018     // no need to call super here; rb_call_super()
1019     rb_iv_set(self, "@autolink",                        autolink);
1020     rb_iv_set(self, "@line_ending",                     line_ending);
1021     rb_iv_set(self, "@external_link_class",             external_link_class);
1022     rb_iv_set(self, "@mailto_class",                    mailto_class);
1023     rb_iv_set(self, "@internal_link_prefix",            internal_link_prefix);
1024     rb_iv_set(self, "@img_prefix",                      img_prefix);
1025     rb_iv_set(self, "@space_to_underscore",             space_to_underscore);
1026     rb_iv_set(self, "@minimum_fulltext_token_length",   minimum_fulltext_token_length);
1027     rb_iv_set(self, "@base_heading_level",              base_heading_level);
1028     return self;
1029 }
1030
1031 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1032 {
1033     for (int i = 0; i < 100000; i++)
1034         Wikitext_parser_parse(1, &string, self);
1035     return Qnil;
1036 }
1037
1038 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1039 {
1040     // process arguments
1041     VALUE string, options;
1042     if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1043         options = Qnil;
1044     if (NIL_P(string))
1045         return Qnil;
1046     string = StringValue(string);
1047
1048     // process options hash
1049     int base_indent = 0;
1050     int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1051     if (!NIL_P(options) && TYPE(options) == T_HASH)
1052     {
1053         // :indent => 0 (or more)
1054         if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1055         {
1056             VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1057             if (indent == Qfalse)
1058                 base_indent = -1; // indentation disabled
1059             else
1060             {
1061                 base_indent = NUM2INT(indent);
1062                 if (base_indent < 0)
1063                     base_indent = 0;
1064             }
1065         }
1066
1067         // :base_heading_level => 0/1/2/3/4/5/6
1068         if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1069             base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1070     }
1071
1072     // normalize, regardless of whether this came from instance variable or override
1073     if (base_heading_level < 0)
1074         base_heading_level = 0;
1075     if (base_heading_level > 6)
1076         base_heading_level = 6;
1077
1078     // set up scanner
1079     char *p = RSTRING_PTR(string);
1080     long len = RSTRING_LEN(string);
1081     char *pe = p + len;
1082
1083     // access these once per parse
1084     VALUE line_ending   = rb_iv_get(self, "@line_ending");
1085     line_ending         = StringValue(line_ending);
1086     VALUE link_class    = rb_iv_get(self, "@external_link_class");
1087     link_class          = NIL_P(link_class) ? Qnil : StringValue(link_class);
1088     VALUE mailto_class  = rb_iv_get(self, "@mailto_class");
1089     mailto_class        = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1090     VALUE prefix        = rb_iv_get(self, "@internal_link_prefix");
1091
1092     // set up parser struct to make passing parameters a little easier
1093     parser_t *parser                = parser_new();
1094     GC_WRAP_PARSER(parser, parser_gc);
1095     parser->external_link_class     = link_class;
1096     parser->mailto_class            = mailto_class;
1097     parser->img_prefix              = rb_iv_get(self, "@img_prefix");
1098     parser->autolink                = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1099     parser->space_to_underscore     = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1100     parser->line_ending             = str_new_from_string(line_ending);
1101     parser->base_indent             = base_indent;
1102     parser->base_heading_level      = base_heading_level;
1103
1104     // this simple looping design leads to a single enormous function,
1105     // but it's faster than doing actual recursive descent and also secure in the face of
1106     // malicious input that seeks to overflow the stack
1107     // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1108     // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1109     // than a straightforward looping translator like this one anyway
1110     token_t _token;
1111     _token.type = NO_TOKEN;
1112     token_t *token = NULL;
1113     do
1114     {
1115         // note that whenever we grab a token we push it into the line buffer
1116         // this provides us with context-sensitive "memory" of what's been seen so far on this line
1117 #define NEXT_TOKEN()    token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1118
1119         // check to see if we have a token hanging around from a previous iteration of this loop
1120         if (token == NULL)
1121         {
1122             if (_token.type == NO_TOKEN)
1123             {
1124                 // first time here (haven't started scanning yet)
1125                 token = &_token;
1126                 next_token(token, NULL, p, pe);
1127                 ary_push(parser->line_buffer, token->type);
1128             }
1129             else
1130                 // already scanning
1131                 NEXT_TOKEN();
1132         }
1133         int type = token->type;
1134
1135         // can't declare new variables inside a switch statement, so predeclare them here
1136         long remove_strong          = -1;
1137         long remove_em              = -1;
1138
1139         // general purpose counters, flags and pointers
1140         long i                      = 0;
1141         long j                      = 0;
1142         long k                      = 0;
1143         str_t *output               = NULL;
1144
1145         // The following giant switch statement contains cases for all the possible token types.
1146         // In the most basic sense we are emitting the HTML that corresponds to each token,
1147         // but some tokens require context information in order to decide what to output.
1148         // For example, does the STRONG token (''') translate to <strong> or </strong>?
1149         // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1150         //
1151         //  - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1152         //  - the line buffer (records tokens seen so far on the current line)
1153         //  - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1154         //
1155         // Although this is fairly complicated, there is one key simplifying factor:
1156         // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1157         // scope stack (up to the current token) is valid; our translator can take this as a given.
1158         // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1159         // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1160         switch (type)
1161         {
1162             case PRE:
1163                 if (IN(NO_WIKI_START) || IN(PRE_START))
1164                 {
1165                     str_append(parser->output, space, sizeof(space) - 1);
1166                     break;
1167                 }
1168                 else if (IN(BLOCKQUOTE_START))
1169                 {
1170                     // this kind of nesting not allowed (to avoid user confusion)
1171                     _Wikitext_pop_excess_elements(parser);
1172                     _Wikitext_start_para_if_necessary(parser);
1173                     output = parser->capture ? parser->capture : parser->output;
1174                     str_append(output, space, sizeof(space) - 1);
1175                     break;
1176                 }
1177
1178                 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1179                 ary_push(parser->line, PRE);
1180                 i = ary_count(parser->line, BLOCKQUOTE);
1181                 j = ary_count(parser->scope, BLOCKQUOTE);
1182                 if (i < j)
1183                 {
1184                     // must pop (reduce nesting level)
1185                     for (i = j - i; i > 0; i--)
1186                         _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1187                 }
1188
1189                 if (!IN(PRE))
1190                 {
1191                     parser->pending_crlf = false;
1192                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1193                     _Wikitext_indent(parser);
1194                     str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1195                     ary_push(parser->scope, PRE);
1196                 }
1197                 break;
1198
1199             case PRE_START:
1200                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1201                 {
1202                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1203                     str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1204                 }
1205                 else if (IN(BLOCKQUOTE_START))
1206                 {
1207                     _Wikitext_rollback_failed_link(parser); // if any
1208                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1209                     _Wikitext_indent(parser);
1210                     str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1211                     ary_push(parser->scope, PRE_START);
1212                     ary_push(parser->line, PRE_START);
1213                 }
1214                 else if (IN(BLOCKQUOTE))
1215                 {
1216                     if (token->column_start == 1) // only allowed in first column
1217                     {
1218                         _Wikitext_rollback_failed_link(parser); // if any
1219                         _Wikitext_pop_all_from_stack(parser);
1220                         _Wikitext_indent(parser);
1221                         str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1222                         ary_push(parser->scope, PRE_START);
1223                         ary_push(parser->line, PRE_START);
1224                     }
1225                     else // PRE_START illegal here
1226                     {
1227                         output = parser->capture ? parser->capture : parser->output;
1228                         _Wikitext_pop_excess_elements(parser);
1229                         _Wikitext_start_para_if_necessary(parser);
1230                         str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1231                     }
1232                 }
1233                 else
1234                 {
1235                     _Wikitext_rollback_failed_link(parser); // if any
1236                     _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1237                     _Wikitext_indent(parser);
1238                     str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1239                     ary_push(parser->scope, PRE_START);
1240                     ary_push(parser->line, PRE_START);
1241                 }
1242                 break;
1243
1244             case PRE_END:
1245                 if (IN(NO_WIKI_START) || IN(PRE))
1246                 {
1247                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1248                     str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1249                 }
1250                 else
1251                 {
1252                     if (IN(PRE_START))
1253                         _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1254                     else
1255                     {
1256                         output = parser->capture ? parser->capture : parser->output;
1257                         _Wikitext_pop_excess_elements(parser);
1258                         _Wikitext_start_para_if_necessary(parser);
1259                         str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1260                     }
1261                 }
1262                 break;
1263
1264             case BLOCKQUOTE:
1265                 if (IN(NO_WIKI_START) || IN(PRE_START))
1266                     // no need to check for <pre>; can never appear inside it
1267                     str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit "&gt;" or "&gt; "
1268                 else if (IN(BLOCKQUOTE_START))
1269                 {
1270                     // this kind of nesting not allowed (to avoid user confusion)
1271                     _Wikitext_pop_excess_elements(parser);
1272                     _Wikitext_start_para_if_necessary(parser);
1273                     output = parser->capture ? parser->capture : parser->output;
1274                     str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit "&gt;" or "&gt; "
1275                     break;
1276                 }
1277                 else
1278                 {
1279                     ary_push(parser->line, BLOCKQUOTE);
1280
1281                     // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1282                     i = ary_count(parser->line, BLOCKQUOTE);
1283                     j = ary_count(parser->scope, BLOCKQUOTE);
1284
1285                     // given that BLOCKQUOTE tokens can be nested, peek ahead and see if there are any more which might affect the decision to push or pop
1286                     while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1287                     {
1288                         ary_push(parser->line, BLOCKQUOTE);
1289                         i++;
1290                     }
1291
1292                     // now decide whether to push, pop or do nothing
1293                     if (i > j)
1294                     {
1295                         // must push (increase nesting level)
1296                         _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1297                         for (i = i - j; i > 0; i--)
1298                         {
1299                             _Wikitext_indent(parser);
1300                             str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1301                             str_append_str(parser->output, parser->line_ending);
1302                             ary_push(parser->scope, BLOCKQUOTE);
1303                         }
1304                     }
1305                     else if (i < j)
1306                     {
1307                         // must pop (reduce nesting level)
1308                         for (i = j - i; i > 0; i--)
1309                             _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1310                     }
1311
1312                     // jump to top of the loop to process token we scanned during lookahead
1313                     continue;
1314                 }
1315                 break;
1316
1317             case BLOCKQUOTE_START:
1318                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1319                 {
1320                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1321                     str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1322                 }
1323                 else if (IN(BLOCKQUOTE_START))
1324                 {
1325                     // nesting is fine here
1326                     _Wikitext_rollback_failed_link(parser); // if any
1327                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1328                     _Wikitext_indent(parser);
1329                     str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1330                     str_append_str(parser->output, parser->line_ending);
1331                     ary_push(parser->scope, BLOCKQUOTE_START);
1332                     ary_push(parser->line, BLOCKQUOTE_START);
1333                 }
1334                 else if (IN(BLOCKQUOTE))
1335                 {
1336                     if (token->column_start == 1) // only allowed in first column
1337                     {
1338                         _Wikitext_rollback_failed_link(parser); // if any
1339                         _Wikitext_pop_all_from_stack(parser);
1340                         _Wikitext_indent(parser);
1341                         str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1342                         str_append_str(parser->output, parser->line_ending);
1343                         ary_push(parser->scope, BLOCKQUOTE_START);
1344                         ary_push(parser->line, BLOCKQUOTE_START);
1345                     }
1346                     else // BLOCKQUOTE_START illegal here
1347                     {
1348                         output = parser->capture ? parser->capture : parser->output;
1349                         _Wikitext_pop_excess_elements(parser);
1350                         _Wikitext_start_para_if_necessary(parser);
1351                         str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1352                     }
1353                 }
1354                 else
1355                 {
1356                     // would be nice to eliminate the repetition here but it's probably the clearest way
1357                     _Wikitext_rollback_failed_link(parser); // if any
1358                     _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1359                     _Wikitext_indent(parser);
1360                     str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1361                     str_append_str(parser->output, parser->line_ending);
1362                     ary_push(parser->scope, BLOCKQUOTE_START);
1363                     ary_push(parser->line, BLOCKQUOTE_START);
1364                 }
1365                 break;
1366
1367             case BLOCKQUOTE_END:
1368                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1369                 {
1370                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1371                     str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1372                 }
1373                 else
1374                 {
1375                     if (IN(BLOCKQUOTE_START))
1376                         _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1377                     else
1378                     {
1379                         output = parser->capture ? parser->capture : parser->output;
1380                         _Wikitext_pop_excess_elements(parser);
1381                         _Wikitext_start_para_if_necessary(parser);
1382                         str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1383                     }
1384                 }
1385                 break;
1386
1387             case NO_WIKI_START:
1388                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1389                 {
1390                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1391                     str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1392                 }
1393                 else
1394                 {
1395                     _Wikitext_pop_excess_elements(parser);
1396                     _Wikitext_start_para_if_necessary(parser);
1397                     ary_push(parser->scope, NO_WIKI_START);
1398                     ary_push(parser->line, NO_WIKI_START);
1399                 }
1400                 break;
1401
1402             case NO_WIKI_END:
1403                 if (IN(NO_WIKI_START))
1404                     // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1405                     _Wikitext_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1406                 else
1407                 {
1408                     _Wikitext_pop_excess_elements(parser);
1409                     _Wikitext_start_para_if_necessary(parser);
1410                     str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1411                 }
1412                 break;
1413
1414             case STRONG_EM:
1415                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1416                 {
1417                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1418                     str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1419                     break;
1420                 }
1421
1422                 output = parser->capture ? parser->capture : parser->output;
1423                 _Wikitext_pop_excess_elements(parser);
1424
1425                 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1426                 // otherwise, must open them
1427                 remove_strong  = -1;
1428                 remove_em      = -1;
1429                 j              = parser->scope->count;
1430                 for (j = j - 1; j >= 0; j--)
1431                 {
1432                     int val = ary_entry(parser->scope, j);
1433                     if (val == STRONG || val == STRONG_START)
1434                     {
1435                         str_append(output, strong_end, sizeof(strong_end) - 1);
1436                         remove_strong = j;
1437                     }
1438                     else if (val == EM || val == EM_START)
1439                     {
1440                         str_append(output, em_end, sizeof(em_end) - 1);
1441                         remove_em = j;
1442                     }
1443                 }
1444
1445                 if (remove_strong > remove_em)      // must remove strong first
1446                 {
1447                     ary_pop(parser->scope);
1448                     if (remove_em > -1)
1449                         ary_pop(parser->scope);
1450                     else    // there was no em to remove!, so consider this an opening em tag
1451                     {
1452                         str_append(output, em_start, sizeof(em_start) - 1);
1453                         ary_push(parser->scope, EM);
1454                         ary_push(parser->line, EM);
1455                     }
1456                 }
1457                 else if (remove_em > remove_strong) // must remove em first
1458                 {
1459                     ary_pop(parser->scope);
1460                     if (remove_strong > -1)
1461                         ary_pop(parser->scope);
1462                     else    // there was no strong to remove!, so consider this an opening strong tag
1463                     {
1464                         str_append(output, strong_start, sizeof(strong_start) - 1);
1465                         ary_push(parser->scope, STRONG);
1466                         ary_push(parser->line, STRONG);
1467                     }
1468                 }
1469                 else    // no strong or em to remove, so this must be a new opening of both
1470                 {
1471                     _Wikitext_start_para_if_necessary(parser);
1472                     str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1473                     ary_push(parser->scope, STRONG);
1474                     ary_push(parser->line, STRONG);
1475                     ary_push(parser->scope, EM);
1476                     ary_push(parser->line, EM);
1477                 }
1478                 break;
1479
1480             case STRONG:
1481                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1482                 {
1483                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1484                     str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1485                 }
1486                 else
1487                 {
1488                     output = parser->capture ? parser->capture : parser->output;
1489                     if (IN(STRONG_START))
1490                         // already in span started with <strong>, no choice but to emit this literally
1491                         str_append(output, literal_strong, sizeof(literal_strong) - 1);
1492                     else if (IN(STRONG))
1493                         // STRONG already seen, this is a closing tag
1494                         _Wikitext_pop_from_stack_up_to(parser, output, STRONG, true);
1495                     else
1496                     {
1497                         // this is a new opening
1498                         _Wikitext_pop_excess_elements(parser);
1499                         _Wikitext_start_para_if_necessary(parser);
1500                         str_append(output, strong_start, sizeof(strong_start) - 1);
1501                         ary_push(parser->scope, STRONG);
1502                         ary_push(parser->line, STRONG);
1503                     }
1504                 }
1505                 break;
1506
1507             case STRONG_START:
1508                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1509                 {
1510                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1511                     str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1512                 }
1513                 else
1514                 {
1515                     output = parser->capture ? parser->capture : parser->output;
1516                     if (IN(STRONG_START) || IN(STRONG))
1517                         str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1518                     else
1519                     {
1520                         _Wikitext_pop_excess_elements(parser);
1521                         _Wikitext_start_para_if_necessary(parser);
1522                         str_append(output, strong_start, sizeof(strong_start) - 1);
1523                         ary_push(parser->scope, STRONG_START);
1524                         ary_push(parser->line, STRONG_START);
1525                     }
1526                 }
1527                 break;
1528
1529             case STRONG_END:
1530                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1531                 {
1532                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1533                     str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1534                 }
1535                 else
1536                 {
1537                     output = parser->capture ? parser->capture : parser->output;
1538                     if (IN(STRONG_START))
1539                         _Wikitext_pop_from_stack_up_to(parser, output, STRONG_START, true);
1540                     else
1541                     {
1542                         // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1543                         _Wikitext_pop_excess_elements(parser);
1544                         _Wikitext_start_para_if_necessary(parser);
1545                         str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1546                     }
1547                 }
1548                 break;
1549
1550             case EM:
1551                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1552                 {
1553                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1554                     str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1555                 }
1556                 else
1557                 {
1558                     output = parser->capture ? parser->capture : parser->output;
1559                     if (IN(EM_START))
1560                         // already in span started with <em>, no choice but to emit this literally
1561                         str_append(output, literal_em, sizeof(literal_em) - 1);
1562                     else if (IN(EM))
1563                         // EM already seen, this is a closing tag
1564                         _Wikitext_pop_from_stack_up_to(parser, output, EM, true);
1565                     else
1566                     {
1567                         // this is a new opening
1568                         _Wikitext_pop_excess_elements(parser);
1569                         _Wikitext_start_para_if_necessary(parser);
1570                         str_append(output, em_start, sizeof(em_start) - 1);
1571                         ary_push(parser->scope, EM);
1572                         ary_push(parser->line, EM);
1573                     }
1574                 }
1575                 break;
1576
1577             case EM_START:
1578                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1579                 {
1580                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1581                     str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1582                 }
1583                 else
1584                 {
1585                     output = parser->capture ? parser->capture : parser->output;
1586                     if (IN(EM_START) || IN(EM))
1587                         str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1588                     else
1589                     {
1590                         _Wikitext_pop_excess_elements(parser);
1591                         _Wikitext_start_para_if_necessary(parser);
1592                         str_append(output, em_start, sizeof(em_start) - 1);
1593                         ary_push(parser->scope, EM_START);
1594                         ary_push(parser->line, EM_START);
1595                     }
1596                 }
1597                 break;
1598
1599             case EM_END:
1600                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1601                 {
1602                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1603                     str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1604                 }
1605                 else
1606                 {
1607                     output = parser->capture ? parser->capture : parser->output;
1608                     if (IN(EM_START))
1609                         _Wikitext_pop_from_stack_up_to(parser, output, EM_START, true);
1610                     else
1611                     {
1612                         // no EM_START in scope, so must interpret the TT_END without any special meaning
1613                         _Wikitext_pop_excess_elements(parser);
1614                         _Wikitext_start_para_if_necessary(parser);
1615                         str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1616                     }
1617                 }
1618                 break;
1619
1620             case TT:
1621                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1622                 {
1623                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1624                     str_append(parser->output, backtick, sizeof(backtick) - 1);
1625                 }
1626                 else
1627                 {
1628                     output = parser->capture ? parser->capture : parser->output;
1629                     if (IN(TT_START))
1630                         // already in span started with <tt>, no choice but to emit this literally
1631                         str_append(output, backtick, sizeof(backtick) - 1);
1632                     else if (IN(TT))
1633                         // TT (`) already seen, this is a closing tag
1634                         _Wikitext_pop_from_stack_up_to(parser, output, TT, true);
1635                     else
1636                     {
1637                         // this is a new opening
1638                         _Wikitext_pop_excess_elements(parser);
1639                         _Wikitext_start_para_if_necessary(parser);
1640                         str_append(output, tt_start, sizeof(tt_start) - 1);
1641                         ary_push(parser->scope, TT);
1642                         ary_push(parser->line, TT);
1643                     }
1644                 }
1645                 break;
1646
1647             case TT_START:
1648                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1649                 {
1650                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1651                     str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1652                 }
1653                 else
1654                 {
1655                     output = parser->capture ? parser->capture : parser->output;
1656                     if (IN(TT_START) || IN(TT))
1657                         str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1658                     else
1659                     {
1660                         _Wikitext_pop_excess_elements(parser);
1661                         _Wikitext_start_para_if_necessary(parser);
1662                         str_append(output, tt_start, sizeof(tt_start) - 1);
1663                         ary_push(parser->scope, TT_START);
1664                         ary_push(parser->line, TT_START);
1665                     }
1666                 }
1667                 break;
1668
1669             case TT_END:
1670                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1671                 {
1672                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1673                     str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1674                 }
1675                 else
1676                 {
1677                     output = parser->capture ? parser->capture : parser->output;
1678                     if (IN(TT_START))
1679                         _Wikitext_pop_from_stack_up_to(parser, output, TT_START, true);
1680                     else
1681                     {
1682                         // no TT_START in scope, so must interpret the TT_END without any special meaning
1683                         _Wikitext_pop_excess_elements(parser);
1684                         _Wikitext_start_para_if_necessary(parser);
1685                         str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1686                     }
1687                 }
1688                 break;
1689
1690             case OL:
1691             case UL:
1692                 if (IN(NO_WIKI_START) || IN(PRE_START))
1693                 {
1694                     // no need to check for PRE; can never appear inside it
1695                     str_append(parser->output, token->start, TOKEN_LEN(token));
1696                     break;
1697                 }
1698
1699                 // count number of tokens in line and scope stacks
1700                 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1701                 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1702                 j = parser->scope->count - bq_count;
1703                 k = i;
1704
1705                 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1706                 for (;;)
1707                 {
1708                     type = token->type;
1709                     if (type == OL || type == UL)
1710                     {
1711                         token = NULL;
1712                         if (i - k >= 2)                             // already seen at least one OL or UL
1713                         {
1714                             ary_push(parser->line, NESTED_LIST);    // which means this is a nested list
1715                             i += 3;
1716                         }
1717                         else
1718                             i += 2;
1719                         ary_push(parser->line, type);
1720                         ary_push(parser->line, LI);
1721
1722                         // want to compare line with scope but can only do so if scope has enough items on it
1723                         if (j >= i)
1724                         {
1725                             if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1726                                 ary_entry(parser->scope, i + bq_count - 1) == LI)
1727                             {
1728                                 // line and scope match at this point: do nothing yet
1729                             }
1730                             else
1731                             {
1732                                 // item just pushed onto line does not match corresponding slot of scope!
1733                                 for (; j >= i - 2; j--)
1734                                     // must pop back before emitting
1735                                     _Wikitext_pop_from_stack(parser, NULL);
1736
1737                                 // will emit UL or OL, then LI
1738                                 break;
1739                             }
1740                         }
1741                         else        // line stack size now exceeds scope stack size: must increase nesting level
1742                             break;  // will emit UL or OL, then LI
1743                     }
1744                     else
1745                     {
1746                         // not a OL or UL token!
1747                         if (j == i)
1748                             // must close existing LI and re-open new one
1749                             _Wikitext_pop_from_stack(parser, NULL);
1750                         else if (j > i)
1751                         {
1752                             // item just pushed onto line does not match corresponding slot of scope!
1753                             for (; j >= i; j--)
1754                                 // must pop back before emitting
1755                                 _Wikitext_pop_from_stack(parser, NULL);
1756                         }
1757                         break;
1758                     }
1759                     NEXT_TOKEN();
1760                 }
1761
1762                 // will emit
1763                 if (type == OL || type == UL)
1764                 {
1765                     // if LI is at the top of a stack this is the start of a nested list
1766                     if (j > 0 && ary_entry(parser->scope, -1) == LI)
1767                     {
1768                         // so we should precede it with a CRLF, and indicate that it's a nested list
1769                         str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1770                         ary_push(parser->scope, NESTED_LIST);
1771                     }
1772                     else
1773                     {
1774                         // this is a new list
1775                         if (IN(BLOCKQUOTE_START))
1776                             _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1777                         else
1778                             _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1779                     }
1780
1781                     // emit
1782                     _Wikitext_indent(parser);
1783                     if (type == OL)
1784                         str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1785                     else if (type == UL)
1786                         str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1787                     ary_push(parser->scope, type);
1788                     str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1789                 }
1790                 else if (type == SPACE)
1791                     // silently throw away the optional SPACE token after final list marker
1792                     token = NULL;
1793
1794                 _Wikitext_indent(parser);
1795                 str_append(parser->output, li_start, sizeof(li_start) - 1);
1796                 ary_push(parser->scope, LI);
1797
1798                 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1799                 if (type == OL || type == UL)
1800                 {
1801                     k = 0;
1802                     while (k++, NEXT_TOKEN(), (type = token->type))
1803                     {
1804                         if (type == OL || type == UL)
1805                             str_append(parser->output, token->start, TOKEN_LEN(token));
1806                         else if (type == SPACE && k == 1)
1807                         {
1808                             // silently throw away the optional SPACE token after final list marker
1809                             token = NULL;
1810                             break;
1811                         }
1812                         else
1813                             break;
1814                     }
1815                 }
1816
1817                 // jump to top of the loop to process token we scanned during lookahead
1818                 continue;
1819
1820             case H6_START:
1821             case H5_START:
1822             case H4_START:
1823             case H3_START:
1824             case H2_START:
1825             case H1_START:
1826                 if (IN(NO_WIKI_START) || IN(PRE_START))
1827                 {
1828                     // no need to check for PRE; can never appear inside it
1829                     str_append(parser->output, token->start, TOKEN_LEN(token));
1830                     break;
1831                 }
1832
1833                 // pop up to but not including the last BLOCKQUOTE on the scope stack
1834                 if (IN(BLOCKQUOTE_START))
1835                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1836                 else
1837                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1838
1839                 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1840                 ary_push(parser->line, type);
1841                 i = ary_count(parser->line, BLOCKQUOTE);
1842                 j = ary_count(parser->scope, BLOCKQUOTE);
1843
1844                 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1845                 if (i < j)
1846                 {
1847                     // must pop (reduce nesting level)
1848                     for (i = j - i; i > 0; i--)
1849                         _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1850                 }
1851
1852                 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1853                 while (NEXT_TOKEN(), (token->type == SPACE))
1854                     ; // discard
1855
1856                 ary_push(parser->scope, type);
1857                 _Wikitext_indent(parser);
1858
1859                 // take base_heading_level into account
1860                 type += base_heading_level;
1861                 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1862                     type = H6_START;
1863
1864                 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1865                 if (type == H6_START)
1866                     str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1867                 else if (type == H5_START)
1868                     str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1869                 else if (type == H4_START)
1870                     str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1871                 else if (type == H3_START)
1872                     str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1873                 else if (type == H2_START)
1874                     str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1875                 else if (type == H1_START)
1876                     str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1877
1878                 // jump to top of the loop to process token we scanned during lookahead
1879                 continue;
1880
1881             case H6_END:
1882                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1883                 {
1884                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1885                     str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1886                 }
1887                 else
1888                 {
1889                     _Wikitext_rollback_failed_external_link(parser); // if any
1890                     if (!IN(H6_START))
1891                     {
1892                         // literal output only if not in h6 scope (we stay silent in that case)
1893                         _Wikitext_start_para_if_necessary(parser);
1894                         str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1895                     }
1896                 }
1897                 break;
1898
1899             case H5_END:
1900                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1901                 {
1902                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1903                     str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1904                 }
1905                 else
1906                 {
1907                     _Wikitext_rollback_failed_external_link(parser); // if any
1908                     if (!IN(H5_START))
1909                     {
1910                         // literal output only if not in h5 scope (we stay silent in that case)
1911                         _Wikitext_start_para_if_necessary(parser);
1912                         str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1913                     }
1914                 }
1915                 break;
1916
1917             case H4_END:
1918                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1919                 {
1920                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1921                     str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1922                 }
1923                 else
1924                 {
1925                     _Wikitext_rollback_failed_external_link(parser); // if any
1926                     if (!IN(H4_START))
1927                     {
1928                         // literal output only if not in h4 scope (we stay silent in that case)
1929                         _Wikitext_start_para_if_necessary(parser);
1930                         str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1931                     }
1932                 }
1933                 break;
1934
1935             case H3_END:
1936                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1937                 {
1938                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1939                     str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1940                 }
1941                 else
1942                 {
1943                     _Wikitext_rollback_failed_external_link(parser); // if any
1944                     if (!IN(H3_START))
1945                     {
1946                         // literal output only if not in h3 scope (we stay silent in that case)
1947                         _Wikitext_start_para_if_necessary(parser);
1948                         str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1949                     }
1950                 }
1951                 break;
1952
1953             case H2_END:
1954                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1955                 {
1956                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1957                     str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1958                 }
1959                 else
1960                 {
1961                     _Wikitext_rollback_failed_external_link(parser); // if any
1962                     if (!IN(H2_START))
1963                     {
1964                         // literal output only if not in h2 scope (we stay silent in that case)
1965                         _Wikitext_start_para_if_necessary(parser);
1966                         str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1967                     }
1968                 }
1969                 break;
1970
1971             case H1_END:
1972                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1973                 {
1974                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1975                     str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1976                 }
1977                 else
1978                 {
1979                     _Wikitext_rollback_failed_external_link(parser); // if any
1980                     if (!IN(H1_START))
1981                     {
1982                         // literal output only if not in h1 scope (we stay silent in that case)
1983                         _Wikitext_start_para_if_necessary(parser);
1984                         str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1985                     }
1986                 }
1987                 break;
1988
1989             case MAIL:
1990                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1991                 {
1992                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1993                     str_append(parser->output, token->start, TOKEN_LEN(token));
1994                 }
1995                 else
1996                 {
1997                     _Wikitext_pop_excess_elements(parser);
1998                     _Wikitext_start_para_if_necessary(parser);
1999                     _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), TOKEN_TEXT(token), Qnil, mailto_class, true);
2000                 }
2001                 break;
2002
2003             case URI:
2004                 if (IN(NO_WIKI_START))
2005                     // user can temporarily suppress autolinking by using <nowiki></nowiki>
2006                     // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
2007                     str_append(parser->output, token->start, TOKEN_LEN(token));
2008                 else if (IN(LINK_START))
2009                 {
2010                     // if the URI were allowed it would have been handled already in LINK_START
2011                     _Wikitext_rollback_failed_internal_link(parser);
2012                     _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, true);
2013                 }
2014                 else if (IN(EXT_LINK_START))
2015                 {
2016                     if (parser->link_target->len == 0)
2017                     {
2018                         // this must be our link target: look ahead to make sure we see the space we're expecting to see
2019                         i = TOKEN_TEXT(token);
2020                         NEXT_TOKEN();
2021                         if (token->type == SPACE)
2022                         {
2023                             ary_push(parser->scope, SPACE);
2024                             str_append_string(parser->link_target, i);
2025                             str_clear(parser->link_text);
2026                             parser->capture     = parser->link_text;
2027                             token               = NULL; // silently consume space
2028                         }
2029                         else
2030                         {
2031                             // didn't see the space! this must be an error
2032                             _Wikitext_pop_from_stack(parser, NULL);
2033                             _Wikitext_pop_excess_elements(parser);
2034                             _Wikitext_start_para_if_necessary(parser);
2035                             str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2036                             _Wikitext_append_hyperlink(parser, Qnil, i, Qnil, parser->external_link_class, true);
2037                         }
2038                     }
2039                     else
2040                         str_append(parser->link_text, token->start, TOKEN_LEN(token));
2041                 }
2042                 else
2043                 {
2044                     _Wikitext_pop_excess_elements(parser);
2045                     _Wikitext_start_para_if_necessary(parser);
2046                     _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, true);
2047                 }
2048                 break;
2049
2050             case PATH:
2051                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2052                     str_append(parser->output, token->start, TOKEN_LEN(token));
2053                 else if (IN(EXT_LINK_START))
2054                 {
2055                     if (parser->link_target->len == 0)
2056                     {
2057                         // this must be our link target: look ahead to make sure we see the space we're expecting to see
2058                         i = TOKEN_TEXT(token);
2059                         NEXT_TOKEN();
2060                         if (token->type == SPACE)
2061                         {
2062                             ary_push(parser->scope, PATH);
2063                             ary_push(parser->scope, SPACE);
2064                             str_append_string(parser->link_target, i);
2065                             str_clear(parser->link_text);
2066                             parser->capture     = parser->link_text;
2067                             token               = NULL; // silently consume space
2068                         }
2069                         else
2070                         {
2071                             // didn't see the space! this must be an error
2072                             _Wikitext_pop_from_stack(parser, NULL);
2073                             _Wikitext_pop_excess_elements(parser);
2074                             _Wikitext_start_para_if_necessary(parser);
2075                             str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2076                             str_append_string(parser->output, i);
2077                         }
2078                     }
2079                     else
2080                         str_append(parser->link_text, token->start, TOKEN_LEN(token));
2081                 }
2082                 else
2083                 {
2084                     output = parser->capture ? parser->capture : parser->output;
2085                     _Wikitext_pop_excess_elements(parser);
2086                     _Wikitext_start_para_if_necessary(parser);
2087                     str_append(output, token->start, TOKEN_LEN(token));
2088                 }
2089                 break;
2090
2091             // internal links (links to other wiki articles) look like this:
2092             //      [[another article]] (would point at, for example, "/wiki/another_article")
2093             //      [[the other article|the link text we'll use for it]]
2094             //      [[the other article | the link text we'll use for it]]
2095             // MediaWiki has strict requirements about what it will accept as a link target:
2096             //      all wikitext markup is disallowed:
2097             //          example [[foo ''bar'' baz]]
2098             //          renders [[foo <em>bar</em> baz]]        (ie. not a link)
2099             //          example [[foo <em>bar</em> baz]]
2100             //          renders [[foo <em>bar</em> baz]]        (ie. not a link)
2101             //          example [[foo <nowiki>''</nowiki> baz]]
2102             //          renders [[foo '' baz]]                  (ie. not a link)
2103             //          example [[foo <bar> baz]]
2104             //          renders [[foo &lt;bar&gt; baz]]         (ie. not a link)
2105             //      HTML entities and non-ASCII, however, make it through:
2106             //          example [[foo &euro;]]
2107             //          renders <a href="/wiki/Foo_%E2%82%AC">foo &euro;</a>
2108             //          example [[foo â‚¬]]
2109             //          renders <a href="/wiki/Foo_%E2%82%AC">foo â‚¬</a>
2110             // we'll impose similar restrictions here for the link target; allowed tokens will be:
2111             //      SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2112             // everything else will be rejected
2113             case LINK_START:
2114                 output = parser->capture ? parser->capture : parser->output;
2115                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2116                 {
2117                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2118                     str_append(output, link_start, sizeof(link_start) - 1);
2119                 }
2120                 else if (IN(EXT_LINK_START))
2121                     // already in external link scope! (and in fact, must be capturing link_text right now)
2122                     str_append(output, link_start, sizeof(link_start) - 1);
2123                 else if (IN(LINK_START))
2124                 {
2125                     // already in internal link scope! this is a syntax error
2126                     _Wikitext_rollback_failed_internal_link(parser);
2127                     str_append(parser->output, link_start, sizeof(link_start) - 1);
2128                 }
2129                 else if (IN(SEPARATOR))
2130                 {
2131                     // scanning internal link text
2132                 }
2133                 else // not in internal link scope yet
2134                 {
2135                     // will either emit a link, or the rollback of a failed link, so start the para now
2136                     _Wikitext_pop_excess_elements(parser);
2137                     _Wikitext_start_para_if_necessary(parser);
2138                     ary_push(parser->scope, LINK_START);
2139
2140                     // look ahead and try to gobble up link target
2141                     while (NEXT_TOKEN(), (type = token->type))
2142                     {
2143                         if (type == SPACE               ||
2144                             type == SPECIAL_URI_CHARS   ||
2145                             type == PATH                ||
2146                             type == PRINTABLE           ||
2147                             type == ALNUM               ||
2148                             type == DEFAULT             ||
2149                             type == QUOT                ||
2150                             type == QUOT_ENTITY         ||
2151                             type == AMP                 ||
2152                             type == AMP_ENTITY          ||
2153                             type == IMG_START           ||
2154                             type == IMG_END             ||
2155                             type == LEFT_CURLY          ||
2156                             type == RIGHT_CURLY)
2157                         {
2158                             // accumulate these tokens into link_target
2159                             if (parser->link_target->len == 0)
2160                             {
2161                                 str_clear(parser->link_target);
2162                                 parser->capture = parser->link_target;
2163                             }
2164                             if (type == QUOT_ENTITY)
2165                                 // don't insert the entity, insert the literal quote
2166                                 str_append(parser->link_target, quote, sizeof(quote) - 1);
2167                             else if (type == AMP_ENTITY)
2168                                 // don't insert the entity, insert the literal ampersand
2169                                 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2170                             else
2171                                 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2172                         }
2173                         else if (type == LINK_END)
2174                         {
2175                             if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2176                                 _Wikitext_rollback_failed_internal_link(parser);
2177                             break; // jump back to top of loop (will handle this in LINK_END case below)
2178                         }
2179                         else if (type == SEPARATOR)
2180                         {
2181                             if (parser->link_target->len == 0) // bail for inputs like "[[|"
2182                                 _Wikitext_rollback_failed_internal_link(parser);
2183                             else
2184                             {
2185                                 ary_push(parser->scope, SEPARATOR);
2186                                 str_clear(parser->link_text);
2187                                 parser->capture     = parser->link_text;
2188                                 token               = NULL;
2189                             }
2190                             break;
2191                         }
2192                         else // unexpected token (syntax error)
2193                         {
2194                             _Wikitext_rollback_failed_internal_link(parser);
2195                             break; // jump back to top of loop to handle unexpected token
2196                         }
2197                     }
2198
2199                     // jump to top of the loop to process token we scanned during lookahead (if any)
2200                     continue;
2201                 }
2202                 break;
2203
2204             case LINK_END:
2205                 output = parser->capture ? parser->capture : parser->output;
2206                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2207                 {
2208                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2209                     str_append(output, link_end, sizeof(link_end) - 1);
2210                 }
2211                 else if (IN(EXT_LINK_START))
2212                     // already in external link scope! (and in fact, must be capturing link_text right now)
2213                     str_append(output, link_end, sizeof(link_end) - 1);
2214                 else if (IN(LINK_START)) // in internal link scope!
2215                 {
2216                     if (_Wikitext_blank(parser->link_target))
2217                     {
2218                         // special case for inputs like "[[    ]]"
2219                         _Wikitext_rollback_failed_internal_link(parser);
2220                         str_append(parser->output, link_end, sizeof(link_end) - 1);
2221                         break;
2222                     }
2223                     if (parser->link_text->len == 0 ||
2224                         _Wikitext_blank(parser->link_text))
2225                     {
2226                         // use link target as link text
2227                         str_clear(parser->link_text);
2228                         str_append_string(parser->link_text, _Wikitext_parser_sanitize_link_target(parser, false));
2229                     }
2230                     else
2231                         _Wikitext_parser_trim_link_text(parser);
2232                     _Wikitext_parser_encode_link_target(parser);
2233                     _Wikitext_pop_from_stack_up_to(parser, output, LINK_START, true);
2234                     parser->capture = NULL;
2235                     _Wikitext_append_hyperlink(parser, prefix, string_from_str(parser->link_target), string_from_str(parser->link_text), Qnil, false);
2236                     str_clear(parser->link_target);
2237                     str_clear(parser->link_text);
2238                 }
2239                 else // wasn't in internal link scope
2240                 {
2241                     _Wikitext_pop_excess_elements(parser);
2242                     _Wikitext_start_para_if_necessary(parser);
2243                     str_append(output, link_end, sizeof(link_end) - 1);
2244                 }
2245                 break;
2246
2247             // external links look like this:
2248             //      [http://google.com/ the link text]
2249             //      [/other/page/on/site see this page]
2250             // strings in square brackets which don't match this syntax get passed through literally; eg:
2251             //      he was very angery [sic] about the turn of events
2252             case EXT_LINK_START:
2253                 output = parser->capture ? parser->capture : parser->output;
2254                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2255                 {
2256                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2257                     str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2258                 }
2259                 else if (IN(EXT_LINK_START))
2260                     // already in external link scope! (and in fact, must be capturing link_text right now)
2261                     str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2262                 else if (IN(LINK_START))
2263                 {
2264                     // already in internal link scope!
2265                     if (parser->link_target->len == 0)
2266                         // this must be the first character of our link target
2267                         str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2268                     else if (IN(SPACE))
2269                         // link target has already been scanned
2270                         str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2271                     else
2272                         // TODO: possibly roll this condition into the above
2273                         // add to existing link target
2274                         str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2275                 }
2276                 else // not in external link scope yet
2277                 {
2278                     // will either emit a link, or the rollback of a failed link, so start the para now
2279                     _Wikitext_pop_excess_elements(parser);
2280                     _Wikitext_start_para_if_necessary(parser);
2281
2282                     // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2283                     NEXT_TOKEN();
2284                     if (token->type == URI || token->type == PATH)
2285                         ary_push(parser->scope, EXT_LINK_START);    // so far so good, jump back to the top of the loop
2286                     else
2287                         // only get here if there was a syntax error (missing URI)
2288                         str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2289                     continue; // jump back to top of loop to handle token (either URI or whatever it is)
2290                 }
2291                 break;
2292
2293             case EXT_LINK_END:
2294                 output = parser->capture ? parser->capture : parser->output;
2295                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2296                 {
2297                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2298                     str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2299                 }
2300                 else if (IN(EXT_LINK_START))
2301                 {
2302                     if (parser->link_text->len == 0)
2303                         // syntax error: external link with no link text
2304                         _Wikitext_rollback_failed_external_link(parser);
2305                     else
2306                     {
2307                         // success!
2308                         j = IN(PATH) ? Qnil : parser->external_link_class;
2309                         _Wikitext_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2310                         parser->capture = NULL;
2311                         _Wikitext_append_hyperlink(parser, Qnil, string_from_str(parser->link_target), string_from_str(parser->link_text), j, false);
2312                     }
2313                     str_clear(parser->link_target);
2314                     str_clear(parser->link_text);
2315                 }
2316                 else
2317                 {
2318                     _Wikitext_pop_excess_elements(parser);
2319                     _Wikitext_start_para_if_necessary(parser);
2320                     str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2321                 }
2322                 break;
2323
2324             case SEPARATOR:
2325                 output = parser->capture ? parser->capture : parser->output;
2326                 _Wikitext_pop_excess_elements(parser);
2327                 _Wikitext_start_para_if_necessary(parser);
2328                 str_append(output, separator, sizeof(separator) - 1);
2329                 break;
2330
2331             case SPACE:
2332                 output = parser->capture ? parser->capture : parser->output;
2333                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2334                 {
2335                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2336                     str_append(output, token->start, TOKEN_LEN(token));
2337                 }
2338                 else
2339                 {
2340                     // peek ahead to see next token
2341                     char    *token_ptr  = token->start;
2342                     int     token_len   = TOKEN_LEN(token);
2343                     NEXT_TOKEN();
2344                     type = token->type;
2345                     if (((type == H6_END) && IN(H6_START)) ||
2346                         ((type == H5_END) && IN(H5_START)) ||
2347                         ((type == H4_END) && IN(H4_START)) ||
2348                         ((type == H3_END) && IN(H3_START)) ||
2349                         ((type == H2_END) && IN(H2_START)) ||
2350                         ((type == H1_END) && IN(H1_START)))
2351                     {
2352                         // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2353                     }
2354                     else
2355                     {
2356                         // emit the space
2357                         _Wikitext_pop_excess_elements(parser);
2358                         _Wikitext_start_para_if_necessary(parser);
2359                         str_append(output, token_ptr, token_len);
2360                     }
2361
2362                     // jump to top of the loop to process token we scanned during lookahead
2363                     continue;
2364                 }
2365                 break;
2366
2367             case QUOT_ENTITY:
2368             case AMP_ENTITY:
2369             case NAMED_ENTITY:
2370             case DECIMAL_ENTITY:
2371                 // pass these through unaltered as they are case sensitive
2372                 output = parser->capture ? parser->capture : parser->output;
2373                 _Wikitext_pop_excess_elements(parser);
2374                 _Wikitext_start_para_if_necessary(parser);
2375                 str_append(output, token->start, TOKEN_LEN(token));
2376                 break;
2377
2378             case HEX_ENTITY:
2379                 // normalize hex entities (downcase them)
2380                 output = parser->capture ? parser->capture : parser->output;
2381                 _Wikitext_pop_excess_elements(parser);
2382                 _Wikitext_start_para_if_necessary(parser);
2383                 str_append(output, token->start, TOKEN_LEN(token));
2384                 _Wikitext_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2385                 break;
2386
2387             case QUOT:
2388                 output = parser->capture ? parser->capture : parser->output;
2389                 _Wikitext_pop_excess_elements(parser);
2390                 _Wikitext_start_para_if_necessary(parser);
2391                 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2392                 break;
2393
2394             case AMP:
2395                 output = parser->capture ? parser->capture : parser->output;
2396                 _Wikitext_pop_excess_elements(parser);
2397                 _Wikitext_start_para_if_necessary(parser);
2398                 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2399                 break;
2400
2401             case LESS:
2402                 output = parser->capture ? parser->capture : parser->output;
2403                 _Wikitext_pop_excess_elements(parser);
2404                 _Wikitext_start_para_if_necessary(parser);
2405                 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2406                 break;
2407
2408             case GREATER:
2409                 output = parser->capture ? parser->capture : parser->output;
2410                 _Wikitext_pop_excess_elements(parser);
2411                 _Wikitext_start_para_if_necessary(parser);
2412                 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2413                 break;
2414
2415             case IMG_START:
2416                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2417                 {
2418                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2419                     str_append(parser->output, token->start, TOKEN_LEN(token));
2420                 }
2421                 else if (parser->capture)
2422                     str_append(parser->capture, token->start, TOKEN_LEN(token));
2423                 else
2424                 {
2425                     // not currently capturing: will be emitting something on success or failure, so get ready
2426                     _Wikitext_pop_excess_elements(parser);
2427                     _Wikitext_start_para_if_necessary(parser);
2428
2429                     // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2430                     // will cheat here and abuse the link_target capture buffer to accumulate text
2431                     while (NEXT_TOKEN(), (type = token->type))
2432                     {
2433                         if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2434                             str_append(parser->link_target, token->start, TOKEN_LEN(token));
2435                         else if (type == IMG_END && parser->link_target->len > 0)
2436                         {
2437                             // success
2438                             _Wikitext_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2439                             token = NULL;
2440                             break;
2441                         }
2442                         else // unexpected token or zero-length target (syntax error)
2443                         {
2444                             // rollback
2445                             str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2446                             if (parser->link_target->len > 0)
2447                                 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2448                             break;
2449                         }
2450                     }
2451
2452                     // jump to top of the loop to process token we scanned during lookahead
2453                     str_clear(parser->link_target);
2454                     continue;
2455                 }
2456                 break;
2457
2458             case CRLF:
2459                 i = parser->pending_crlf;
2460                 parser->pending_crlf = false;
2461                 _Wikitext_rollback_failed_link(parser); // if any
2462                 if (IN(NO_WIKI_START) || IN(PRE_START))
2463                 {
2464                     ary_clear(parser->line_buffer);
2465                     str_append_str(parser->output, parser->line_ending);
2466                     break;
2467                 }
2468                 else if (IN(PRE))
2469                 {
2470                     // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2471                     if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2472                         // don't emit in this case
2473                         _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2474                     else
2475                     {
2476                         if (ary_entry(parser->line_buffer, -2) == PRE)
2477                         {
2478                              // only thing on line is the PRE: emit pending line ending (if we had one)
2479                              if (i)
2480                                  str_append_str(parser->output, parser->line_ending);
2481                         }
2482
2483                         // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2484                         ary_clear(parser->line);
2485                         ary_clear(parser->line_buffer);
2486
2487                         // peek ahead to see if this is definitely the end of the PRE block
2488                         NEXT_TOKEN();
2489                         type = token->type;
2490                         if (type != BLOCKQUOTE && type != PRE)
2491                             // this is definitely the end of the block, so don't emit
2492                             _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2493                         else
2494                             // potentially will emit
2495                             parser->pending_crlf = true;
2496
2497                         continue; // jump back to top of loop to handle token grabbed via lookahead
2498                     }
2499                 }
2500                 else
2501                 {
2502                     parser->pending_crlf = true;
2503
2504                     // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2505                     // as a side effect, this handles any open span-level elements and unclosed blocks
2506                     // (with special handling for P blocks and LI elements)
2507                     i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2508                     for (j = parser->scope->count; j > i; j--)
2509                     {
2510                         if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2511                         {
2512                             parser->pending_crlf = false;
2513                             break;
2514                         }
2515
2516                         // special handling on last iteration through the loop if the top item on the scope is a P block
2517                         if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2518                         {
2519                             // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2520                             // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2521                             // because in those blocks BLOCKQUOTE tokens have no special meaning)
2522                             if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2523                                 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2524                                 // paragraph break
2525                                 parser->pending_crlf = false;
2526                             else
2527                                 // not a paragraph break!
2528                                 continue;
2529                         }
2530                         _Wikitext_pop_from_stack(parser, NULL);
2531                     }
2532                 }
2533
2534                 // delete the entire contents of the line scope stack and buffer
2535                 ary_clear(parser->line);
2536                 ary_clear(parser->line_buffer);
2537                 break;
2538
2539             case SPECIAL_URI_CHARS:
2540             case PRINTABLE:
2541             case ALNUM:
2542             case IMG_END:
2543             case LEFT_CURLY:
2544             case RIGHT_CURLY:
2545                 output = parser->capture ? parser->capture : parser->output;
2546                 _Wikitext_pop_excess_elements(parser);
2547                 _Wikitext_start_para_if_necessary(parser);
2548                 str_append(output, token->start, TOKEN_LEN(token));
2549                 break;
2550
2551             case DEFAULT:
2552                 output = parser->capture ? parser->capture : parser->output;
2553                 _Wikitext_pop_excess_elements(parser);
2554                 _Wikitext_start_para_if_necessary(parser);
2555                 //str_append_string(output, _Wikitext_utf32_char_to_entity(token->code_point));    // convert to entity
2556                 // TODO: replace this with a different append function
2557                 str_grow(output, output->len + 8);
2558                 _Wikitext_append_entity_from_utf32_char(output->ptr + output->len, token->code_point);
2559                 output->len = output->len + 8;
2560                 break;
2561
2562             case END_OF_FILE:
2563                 // special case for input like " foo\n " (see pre_spec.rb)
2564                 if (IN(PRE) &&
2565                     ary_entry(parser->line_buffer, -2) == PRE &&
2566                     parser->pending_crlf)
2567                     str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2568
2569                 // close any open scopes on hitting EOF
2570                 _Wikitext_rollback_failed_link(parser); // if any
2571                 _Wikitext_pop_all_from_stack(parser);
2572                 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2573
2574             default:
2575                 break;
2576         }
2577
2578         // reset current token; forcing lexer to return another token at the top of the loop
2579         token = NULL;
2580     } while (1);
2581 return_output:
2582     // TODO: make this fast
2583     return string_from_str(parser->output);
2584 }