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