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