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