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