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