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