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