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