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