]> git.wincent.com - wikitext.git/blob - ext/parser.c
d54c1c711c5396085e7e76434516c37bfd328fe2
[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     long    len         = parser->link_text->len;
724     char    *end        = src + len;
725     while (src < end)
726     {
727         if (*src == ' ')
728         {
729             if (src == left)
730                 left++;
731         }
732         else
733             non_space = src;
734         src++;
735     }
736     if (left != start || non_space + 1 != end)
737     {
738         // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
739         parser->link_text->len = (non_space + 1) - left;
740         memmove(parser->link_text->ptr, left, parser->link_text->len);
741     }
742 }
743
744 // - non-printable (non-ASCII) characters converted to numeric entities
745 // - QUOT and AMP characters converted to named entities
746 // - if trim is true, leading and trailing whitespace trimmed
747 // - if trim is false, there is no special treatment of spaces
748 void _Wikitext_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
749 {
750     char    *src        = parser->link_target->ptr;
751     char    *start      = src;  // remember this so we can check if we're at the start
752     long    len         = parser->link_target->len;
753     char    *end        = src + len;
754     char    *dest       = output->ptr + output->len;
755     char    *non_space  = dest; // remember last non-space character output
756     while (src < end)
757     {
758         // need at most 8 bytes to display each input character (&#x0000;)
759         if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
760         {
761             char *old_ptr       = output->ptr;
762             len                 = output->len + (end - src) * 8;    // allocate enough for worst case
763             str_grow(output, len);
764             if (old_ptr != output->ptr) // may have moved
765             {
766                 non_space       += output->ptr - old_ptr;
767                 dest            += output->ptr - old_ptr;
768             }
769         }
770
771         if (*src == '"')
772         {
773             char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' };  // no trailing NUL
774             str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
775         }
776         else if (*src == '&')
777         {
778             char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' };    // no trailing NUL
779             str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
780         }
781         else if (*src == '<' || *src == '>')
782             rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
783         else if (*src == ' ' && src == start && trim)
784             start++;                            // we eat leading space
785         else if (*src >= 0x20 && *src <= 0x7e)  // printable ASCII
786         {
787             *(output->ptr + output->len) = *src;
788             output->len++;
789         }
790         else    // all others: must convert to entities
791         {
792             long        width;
793             _Wikitext_append_entity_from_utf32_char(output->ptr + output->len, _Wikitext_utf8_to_utf32(src, end, &width));
794             output->len += 8;
795             src         += width;
796             non_space   = output->ptr + output->len;
797             continue;
798         }
799         if (*src != ' ')
800             non_space = output->ptr + output->len;
801         src++;
802     }
803
804     // trim trailing space if necessary
805     if (trim && non_space > dest && output->ptr + output->len != non_space)
806         output->len -= (output->ptr + output->len) - non_space;
807 }
808
809 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
810 {
811     parser_t parser;
812     parser.link_target = str_new_from_string(string);
813     GC_WRAP_STR(parser.link_target, link_target_gc);
814     str_t *output = str_new();
815     GC_WRAP_STR(output, output_gc);
816     _Wikitext_append_sanitized_link_target(&parser, output, true);
817     return string_from_str(output);
818 }
819
820 // encodes the input string according to RFCs 2396 and 2718
821 // leading and trailing whitespace trimmed
822 // note that the first character of the target link is not case-sensitive
823 // (this is a recommended application-level constraint; it is not imposed at this level)
824 // this is to allow links like:
825 //         ...the [[foo]] is...
826 // to be equivalent to:
827 //         thing. [[Foo]] was...
828 static void _Wikitext_encode_link_target(parser_t *parser)
829 {
830     char        *input      = parser->link_target->ptr;
831     char        *start      = input;            // remember this so we can check if we're at the start
832     long        len         = parser->link_target->len;
833     if (!(len > 0))
834         return;
835     char        *end        = input + len;
836     static char hex[]       = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
837
838     // to avoid most reallocations start with a destination buffer twice the size of the source
839     // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
840     // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
841     // the worst case is where _every_ byte must be written out using 3 bytes
842     long        dest_len    = len * 2;
843     char        *dest       = ALLOC_N(char, dest_len);
844     char        *dest_ptr   = dest; // hang on to this so we can pass it to free() later
845     char        *non_space  = dest; // remember last non-space character output
846     for (; input < end; input++)
847     {
848         if ((dest + 3) > (dest_ptr + dest_len))     // worst case: a single character may grow to 3 characters once encoded
849         {
850             // outgrowing buffer, must reallocate
851             char *old_dest      = dest;
852             char *old_dest_ptr  = dest_ptr;
853             dest_len            += len;
854             dest                = realloc(dest_ptr, dest_len);
855             if (dest == NULL)
856             {
857                 // would have used reallocf, but this has to run on Linux too, not just Darwin
858                 free(dest_ptr);
859                 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
860             }
861             dest_ptr    = dest;
862             dest        = dest_ptr + (old_dest - old_dest_ptr);
863             non_space   = dest_ptr + (non_space - old_dest_ptr);
864         }
865
866         // pass through unreserved characters
867         if (((*input >= 'a') && (*input <= 'z')) ||
868             ((*input >= 'A') && (*input <= 'Z')) ||
869             ((*input >= '0') && (*input <= '9')) ||
870             (*input == '-') ||
871             (*input == '_') ||
872             (*input == '.') ||
873             (*input == '~'))
874         {
875             *dest++     = *input;
876             non_space   = dest;
877         }
878         else if (*input == ' ' && input == start)
879             start++;                    // we eat leading space
880         else if (*input == ' ' && parser->space_to_underscore)
881             *dest++     = '_';
882         else    // everything else gets URL-encoded
883         {
884             *dest++     = '%';
885             *dest++     = hex[(unsigned char)(*input) / 16];   // left
886             *dest++     = hex[(unsigned char)(*input) % 16];   // right
887             if (*input != ' ')
888                 non_space = dest;
889         }
890     }
891
892     // trim trailing space if necessary
893     if (non_space > dest_ptr && dest != non_space)
894         dest_len = non_space - dest_ptr;
895     else
896         dest_len = dest - dest_ptr;
897
898     // TOOD: try to avoid this copy by working directly inside link_target buffer
899     str_clear(parser->link_target);
900     str_append(parser->link_target, dest_ptr, dest_len);
901     free(dest_ptr);
902 }
903
904 VALUE Wikitext_parser_encode_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 // this method exposed for testing only
915 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
916 {
917     parser_t parser;
918     parser.space_to_underscore      = false;
919     parser.link_target              = str_new_from_string(in);
920     GC_WRAP_STR(parser.link_target, link_target_gc);
921     _Wikitext_encode_link_target(&parser);
922     return string_from_str(parser.link_target);
923 }
924
925 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
926 // returns 0 (false) otherwise
927 bool _Wikitext_blank(str_t *str)
928 {
929     if (str->len == 0)
930         return true;
931     for (char *ptr = str->ptr,
932         *end = str->ptr + str->len;
933         ptr < end; ptr++)
934     {
935         if (*ptr != ' ')
936             return false;
937     }
938     return true;
939 }
940
941 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
942 {
943     if (!IN(LINK_START))
944         return; // nothing to do!
945     int scope_includes_separator = IN(SEPARATOR);
946     _Wikitext_pop_from_stack_up_to(parser, NULL, LINK_START, true);
947     str_append(parser->output, link_start, sizeof(link_start) - 1);
948     if (parser->link_target->len > 0)
949     {
950         _Wikitext_append_sanitized_link_target(parser, parser->output, false);
951         if (scope_includes_separator)
952         {
953             str_append(parser->output, separator, sizeof(separator) - 1);
954             if (parser->link_text->len > 0)
955                 str_append_str(parser->output, parser->link_text);
956         }
957     }
958     parser->capture = NULL;
959     str_clear(parser->link_target);
960     str_clear(parser->link_text);
961 }
962
963 void _Wikitext_rollback_failed_external_link(parser_t *parser)
964 {
965     if (!IN(EXT_LINK_START))
966         return; // nothing to do!
967
968     // store a couple of values before popping
969     int scope_includes_space = IN(SPACE);
970     VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
971     _Wikitext_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
972
973     str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
974     if (parser->link_target->len > 0)
975     {
976         _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
977         if (scope_includes_space)
978         {
979             str_append(parser->output, space, sizeof(space) - 1);
980             if (parser->link_text->len > 0)
981                 str_append_str(parser->output, parser->link_text);
982         }
983     }
984     parser->capture = NULL;
985     str_clear(parser->link_target);
986     str_clear(parser->link_text);
987 }
988
989 void _Wikitext_rollback_failed_link(parser_t *parser)
990 {
991     _Wikitext_rollback_failed_internal_link(parser);
992     _Wikitext_rollback_failed_external_link(parser);
993 }
994
995 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
996 {
997     // process arguments
998     VALUE options;
999     if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
1000         options = Qnil;
1001
1002     // defaults
1003     VALUE autolink                      = Qtrue;
1004     VALUE line_ending                   = rb_str_new2("\n");
1005     VALUE external_link_class           = rb_str_new2("external");
1006     VALUE mailto_class                  = rb_str_new2("mailto");
1007     VALUE internal_link_prefix          = rb_str_new2("/wiki/");
1008     VALUE img_prefix                    = rb_str_new2("/images/");
1009     VALUE space_to_underscore           = Qtrue;
1010     VALUE minimum_fulltext_token_length = INT2NUM(3);
1011     VALUE base_heading_level            = INT2NUM(0);
1012
1013     // process options hash (override defaults)
1014     if (!NIL_P(options) && TYPE(options) == T_HASH)
1015     {
1016 #define OVERRIDE_IF_SET(name)   rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1017                                 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1018         autolink                        = OVERRIDE_IF_SET(autolink);
1019         line_ending                     = OVERRIDE_IF_SET(line_ending);
1020         external_link_class             = OVERRIDE_IF_SET(external_link_class);
1021         mailto_class                    = OVERRIDE_IF_SET(mailto_class);
1022         internal_link_prefix            = OVERRIDE_IF_SET(internal_link_prefix);
1023         img_prefix                      = OVERRIDE_IF_SET(img_prefix);
1024         space_to_underscore             = OVERRIDE_IF_SET(space_to_underscore);
1025         minimum_fulltext_token_length   = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1026         base_heading_level              = OVERRIDE_IF_SET(base_heading_level);
1027     }
1028
1029     // no need to call super here; rb_call_super()
1030     rb_iv_set(self, "@autolink",                        autolink);
1031     rb_iv_set(self, "@line_ending",                     line_ending);
1032     rb_iv_set(self, "@external_link_class",             external_link_class);
1033     rb_iv_set(self, "@mailto_class",                    mailto_class);
1034     rb_iv_set(self, "@internal_link_prefix",            internal_link_prefix);
1035     rb_iv_set(self, "@img_prefix",                      img_prefix);
1036     rb_iv_set(self, "@space_to_underscore",             space_to_underscore);
1037     rb_iv_set(self, "@minimum_fulltext_token_length",   minimum_fulltext_token_length);
1038     rb_iv_set(self, "@base_heading_level",              base_heading_level);
1039     return self;
1040 }
1041
1042 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1043 {
1044     for (int i = 0; i < 100000; i++)
1045         Wikitext_parser_parse(1, &string, self);
1046     return Qnil;
1047 }
1048
1049 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1050 {
1051     // process arguments
1052     VALUE string, options;
1053     if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1054         options = Qnil;
1055     if (NIL_P(string))
1056         return Qnil;
1057     string = StringValue(string);
1058
1059     // process options hash
1060     int base_indent = 0;
1061     int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1062     if (!NIL_P(options) && TYPE(options) == T_HASH)
1063     {
1064         // :indent => 0 (or more)
1065         if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1066         {
1067             VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1068             if (indent == Qfalse)
1069                 base_indent = -1; // indentation disabled
1070             else
1071             {
1072                 base_indent = NUM2INT(indent);
1073                 if (base_indent < 0)
1074                     base_indent = 0;
1075             }
1076         }
1077
1078         // :base_heading_level => 0/1/2/3/4/5/6
1079         if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1080             base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1081     }
1082
1083     // normalize, regardless of whether this came from instance variable or override
1084     if (base_heading_level < 0)
1085         base_heading_level = 0;
1086     if (base_heading_level > 6)
1087         base_heading_level = 6;
1088
1089     // set up scanner
1090     char *p = RSTRING_PTR(string);
1091     long len = RSTRING_LEN(string);
1092     char *pe = p + len;
1093
1094     // the eventual return value
1095     VALUE out = rb_str_new2("");
1096
1097     // access these once per parse
1098     VALUE line_ending   = rb_iv_get(self, "@line_ending");
1099     line_ending         = StringValue(line_ending);
1100     VALUE link_class    = rb_iv_get(self, "@external_link_class");
1101     link_class          = NIL_P(link_class) ? Qnil : StringValue(link_class);
1102     VALUE mailto_class  = rb_iv_get(self, "@mailto_class");
1103     mailto_class        = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1104     VALUE prefix        = rb_iv_get(self, "@internal_link_prefix");
1105
1106     // set up parser struct to make passing parameters a little easier
1107     parser_t *parser                = parser_new();
1108     GC_WRAP_PARSER(parser, parser_gc);
1109     parser->external_link_class     = link_class;
1110     parser->mailto_class            = mailto_class;
1111     parser->img_prefix              = rb_iv_get(self, "@img_prefix");
1112     parser->autolink                = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1113     parser->space_to_underscore     = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1114     parser->line_ending             = str_new_from_string(line_ending);
1115     parser->base_indent             = base_indent;
1116     parser->base_heading_level      = base_heading_level;
1117
1118     // this simple looping design leads to a single enormous function,
1119     // but it's faster than doing actual recursive descent and also secure in the face of
1120     // malicious input that seeks to overflow the stack
1121     // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1122     // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1123     // than a straightforward looping translator like this one anyway
1124     token_t _token;
1125     _token.type = NO_TOKEN;
1126     token_t *token = NULL;
1127     do
1128     {
1129         // note that whenever we grab a token we push it into the line buffer
1130         // this provides us with context-sensitive "memory" of what's been seen so far on this line
1131 #define NEXT_TOKEN()    token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1132
1133         // check to see if we have a token hanging around from a previous iteration of this loop
1134         if (token == NULL)
1135         {
1136             if (_token.type == NO_TOKEN)
1137             {
1138                 // first time here (haven't started scanning yet)
1139                 token = &_token;
1140                 next_token(token, NULL, p, pe);
1141                 ary_push(parser->line_buffer, token->type);
1142             }
1143             else
1144                 // already scanning
1145                 NEXT_TOKEN();
1146         }
1147         int type = token->type;
1148
1149         // can't declare new variables inside a switch statement, so predeclare them here
1150         long remove_strong          = -1;
1151         long remove_em              = -1;
1152
1153         // general purpose counters, flags and pointers
1154         long i                      = 0;
1155         long j                      = 0;
1156         long k                      = 0;
1157         str_t *output               = NULL;
1158         str_t _token_str;
1159         str_t *token_str            = &_token_str;
1160
1161         // The following giant switch statement contains cases for all the possible token types.
1162         // In the most basic sense we are emitting the HTML that corresponds to each token,
1163         // but some tokens require context information in order to decide what to output.
1164         // For example, does the STRONG token (''') translate to <strong> or </strong>?
1165         // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1166         //
1167         //  - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1168         //  - the line buffer (records tokens seen so far on the current line)
1169         //  - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1170         //
1171         // Although this is fairly complicated, there is one key simplifying factor:
1172         // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1173         // scope stack (up to the current token) is valid; our translator can take this as a given.
1174         // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1175         // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1176         switch (type)
1177         {
1178             case PRE:
1179                 if (IN(NO_WIKI_START) || IN(PRE_START))
1180                 {
1181                     str_append(parser->output, space, sizeof(space) - 1);
1182                     break;
1183                 }
1184                 else if (IN(BLOCKQUOTE_START))
1185                 {
1186                     // this kind of nesting not allowed (to avoid user confusion)
1187                     _Wikitext_pop_excess_elements(parser);
1188                     _Wikitext_start_para_if_necessary(parser);
1189                     output = parser->capture ? parser->capture : parser->output;
1190                     str_append(output, space, sizeof(space) - 1);
1191                     break;
1192                 }
1193
1194                 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1195                 ary_push(parser->line, PRE);
1196                 i = ary_count(parser->line, BLOCKQUOTE);
1197                 j = ary_count(parser->scope, BLOCKQUOTE);
1198                 if (i < j)
1199                 {
1200                     // must pop (reduce nesting level)
1201                     for (i = j - i; i > 0; i--)
1202                         _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1203                 }
1204
1205                 if (!IN(PRE))
1206                 {
1207                     parser->pending_crlf = false;
1208                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1209                     _Wikitext_indent(parser);
1210                     str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1211                     ary_push(parser->scope, PRE);
1212                 }
1213                 break;
1214
1215             case PRE_START:
1216                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1217                 {
1218                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1219                     str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1220                 }
1221                 else if (IN(BLOCKQUOTE_START))
1222                 {
1223                     _Wikitext_rollback_failed_link(parser); // if any
1224                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1225                     _Wikitext_indent(parser);
1226                     str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1227                     ary_push(parser->scope, PRE_START);
1228                     ary_push(parser->line, PRE_START);
1229                 }
1230                 else if (IN(BLOCKQUOTE))
1231                 {
1232                     if (token->column_start == 1) // only allowed in first column
1233                     {
1234                         _Wikitext_rollback_failed_link(parser); // if any
1235                         _Wikitext_pop_all_from_stack(parser);
1236                         _Wikitext_indent(parser);
1237                         str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1238                         ary_push(parser->scope, PRE_START);
1239                         ary_push(parser->line, PRE_START);
1240                     }
1241                     else // PRE_START illegal here
1242                     {
1243                         output = parser->capture ? parser->capture : parser->output;
1244                         _Wikitext_pop_excess_elements(parser);
1245                         _Wikitext_start_para_if_necessary(parser);
1246                         str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1247                     }
1248                 }
1249                 else
1250                 {
1251                     _Wikitext_rollback_failed_link(parser); // if any
1252                     _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1253                     _Wikitext_indent(parser);
1254                     str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1255                     ary_push(parser->scope, PRE_START);
1256                     ary_push(parser->line, PRE_START);
1257                 }
1258                 break;
1259
1260             case PRE_END:
1261                 if (IN(NO_WIKI_START) || IN(PRE))
1262                 {
1263                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1264                     str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1265                 }
1266                 else
1267                 {
1268                     if (IN(PRE_START))
1269                         _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1270                     else
1271                     {
1272                         output = parser->capture ? parser->capture : parser->output;
1273                         _Wikitext_pop_excess_elements(parser);
1274                         _Wikitext_start_para_if_necessary(parser);
1275                         str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1276                     }
1277                 }
1278                 break;
1279
1280             case BLOCKQUOTE:
1281                 if (IN(NO_WIKI_START) || IN(PRE_START))
1282                     // no need to check for <pre>; can never appear inside it
1283                     str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit "&gt;" or "&gt; "
1284                 else if (IN(BLOCKQUOTE_START))
1285                 {
1286                     // this kind of nesting not allowed (to avoid user confusion)
1287                     _Wikitext_pop_excess_elements(parser);
1288                     _Wikitext_start_para_if_necessary(parser);
1289                     output = parser->capture ? parser->capture : parser->output;
1290                     str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit "&gt;" or "&gt; "
1291                     break;
1292                 }
1293                 else
1294                 {
1295                     ary_push(parser->line, BLOCKQUOTE);
1296
1297                     // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1298                     i = ary_count(parser->line, BLOCKQUOTE);
1299                     j = ary_count(parser->scope, BLOCKQUOTE);
1300
1301                     // 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
1302                     while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1303                     {
1304                         ary_push(parser->line, BLOCKQUOTE);
1305                         i++;
1306                     }
1307
1308                     // now decide whether to push, pop or do nothing
1309                     if (i > j)
1310                     {
1311                         // must push (increase nesting level)
1312                         _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1313                         for (i = i - j; i > 0; i--)
1314                         {
1315                             _Wikitext_indent(parser);
1316                             str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1317                             str_append_str(parser->output, parser->line_ending);
1318                             ary_push(parser->scope, BLOCKQUOTE);
1319                         }
1320                     }
1321                     else if (i < j)
1322                     {
1323                         // must pop (reduce nesting level)
1324                         for (i = j - i; i > 0; i--)
1325                             _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1326                     }
1327
1328                     // jump to top of the loop to process token we scanned during lookahead
1329                     continue;
1330                 }
1331                 break;
1332
1333             case BLOCKQUOTE_START:
1334                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1335                 {
1336                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1337                     str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1338                 }
1339                 else if (IN(BLOCKQUOTE_START))
1340                 {
1341                     // nesting is fine here
1342                     _Wikitext_rollback_failed_link(parser); // if any
1343                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1344                     _Wikitext_indent(parser);
1345                     str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1346                     str_append_str(parser->output, parser->line_ending);
1347                     ary_push(parser->scope, BLOCKQUOTE_START);
1348                     ary_push(parser->line, BLOCKQUOTE_START);
1349                 }
1350                 else if (IN(BLOCKQUOTE))
1351                 {
1352                     if (token->column_start == 1) // only allowed in first column
1353                     {
1354                         _Wikitext_rollback_failed_link(parser); // if any
1355                         _Wikitext_pop_all_from_stack(parser);
1356                         _Wikitext_indent(parser);
1357                         str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1358                         str_append_str(parser->output, parser->line_ending);
1359                         ary_push(parser->scope, BLOCKQUOTE_START);
1360                         ary_push(parser->line, BLOCKQUOTE_START);
1361                     }
1362                     else // BLOCKQUOTE_START illegal here
1363                     {
1364                         output = parser->capture ? parser->capture : parser->output;
1365                         _Wikitext_pop_excess_elements(parser);
1366                         _Wikitext_start_para_if_necessary(parser);
1367                         str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1368                     }
1369                 }
1370                 else
1371                 {
1372                     // would be nice to eliminate the repetition here but it's probably the clearest way
1373                     _Wikitext_rollback_failed_link(parser); // if any
1374                     _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1375                     _Wikitext_indent(parser);
1376                     str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1377                     str_append_str(parser->output, parser->line_ending);
1378                     ary_push(parser->scope, BLOCKQUOTE_START);
1379                     ary_push(parser->line, BLOCKQUOTE_START);
1380                 }
1381                 break;
1382
1383             case BLOCKQUOTE_END:
1384                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1385                 {
1386                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1387                     str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1388                 }
1389                 else
1390                 {
1391                     if (IN(BLOCKQUOTE_START))
1392                         _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1393                     else
1394                     {
1395                         output = parser->capture ? parser->capture : parser->output;
1396                         _Wikitext_pop_excess_elements(parser);
1397                         _Wikitext_start_para_if_necessary(parser);
1398                         str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1399                     }
1400                 }
1401                 break;
1402
1403             case NO_WIKI_START:
1404                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1405                 {
1406                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1407                     str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1408                 }
1409                 else
1410                 {
1411                     _Wikitext_pop_excess_elements(parser);
1412                     _Wikitext_start_para_if_necessary(parser);
1413                     ary_push(parser->scope, NO_WIKI_START);
1414                     ary_push(parser->line, NO_WIKI_START);
1415                 }
1416                 break;
1417
1418             case NO_WIKI_END:
1419                 if (IN(NO_WIKI_START))
1420                     // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1421                     _Wikitext_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1422                 else
1423                 {
1424                     _Wikitext_pop_excess_elements(parser);
1425                     _Wikitext_start_para_if_necessary(parser);
1426                     str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1427                 }
1428                 break;
1429
1430             case STRONG_EM:
1431                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1432                 {
1433                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1434                     str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1435                     break;
1436                 }
1437
1438                 output = parser->capture ? parser->capture : parser->output;
1439                 _Wikitext_pop_excess_elements(parser);
1440
1441                 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1442                 // otherwise, must open them
1443                 remove_strong  = -1;
1444                 remove_em      = -1;
1445                 j              = parser->scope->count;
1446                 for (j = j - 1; j >= 0; j--)
1447                 {
1448                     int val = ary_entry(parser->scope, j);
1449                     if (val == STRONG || val == STRONG_START)
1450                     {
1451                         str_append(output, strong_end, sizeof(strong_end) - 1);
1452                         remove_strong = j;
1453                     }
1454                     else if (val == EM || val == EM_START)
1455                     {
1456                         str_append(output, em_end, sizeof(em_end) - 1);
1457                         remove_em = j;
1458                     }
1459                 }
1460
1461                 if (remove_strong > remove_em)      // must remove strong first
1462                 {
1463                     ary_pop(parser->scope);
1464                     if (remove_em > -1)
1465                         ary_pop(parser->scope);
1466                     else    // there was no em to remove!, so consider this an opening em tag
1467                     {
1468                         str_append(output, em_start, sizeof(em_start) - 1);
1469                         ary_push(parser->scope, EM);
1470                         ary_push(parser->line, EM);
1471                     }
1472                 }
1473                 else if (remove_em > remove_strong) // must remove em first
1474                 {
1475                     ary_pop(parser->scope);
1476                     if (remove_strong > -1)
1477                         ary_pop(parser->scope);
1478                     else    // there was no strong to remove!, so consider this an opening strong tag
1479                     {
1480                         str_append(output, strong_start, sizeof(strong_start) - 1);
1481                         ary_push(parser->scope, STRONG);
1482                         ary_push(parser->line, STRONG);
1483                     }
1484                 }
1485                 else    // no strong or em to remove, so this must be a new opening of both
1486                 {
1487                     _Wikitext_start_para_if_necessary(parser);
1488                     str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1489                     ary_push(parser->scope, STRONG);
1490                     ary_push(parser->line, STRONG);
1491                     ary_push(parser->scope, EM);
1492                     ary_push(parser->line, EM);
1493                 }
1494                 break;
1495
1496             case STRONG:
1497                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1498                 {
1499                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1500                     str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1501                 }
1502                 else
1503                 {
1504                     output = parser->capture ? parser->capture : parser->output;
1505                     if (IN(STRONG_START))
1506                         // already in span started with <strong>, no choice but to emit this literally
1507                         str_append(output, literal_strong, sizeof(literal_strong) - 1);
1508                     else if (IN(STRONG))
1509                         // STRONG already seen, this is a closing tag
1510                         _Wikitext_pop_from_stack_up_to(parser, output, STRONG, true);
1511                     else
1512                     {
1513                         // this is a new opening
1514                         _Wikitext_pop_excess_elements(parser);
1515                         _Wikitext_start_para_if_necessary(parser);
1516                         str_append(output, strong_start, sizeof(strong_start) - 1);
1517                         ary_push(parser->scope, STRONG);
1518                         ary_push(parser->line, STRONG);
1519                     }
1520                 }
1521                 break;
1522
1523             case STRONG_START:
1524                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1525                 {
1526                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1527                     str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1528                 }
1529                 else
1530                 {
1531                     output = parser->capture ? parser->capture : parser->output;
1532                     if (IN(STRONG_START) || IN(STRONG))
1533                         str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1534                     else
1535                     {
1536                         _Wikitext_pop_excess_elements(parser);
1537                         _Wikitext_start_para_if_necessary(parser);
1538                         str_append(output, strong_start, sizeof(strong_start) - 1);
1539                         ary_push(parser->scope, STRONG_START);
1540                         ary_push(parser->line, STRONG_START);
1541                     }
1542                 }
1543                 break;
1544
1545             case STRONG_END:
1546                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1547                 {
1548                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1549                     str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1550                 }
1551                 else
1552                 {
1553                     output = parser->capture ? parser->capture : parser->output;
1554                     if (IN(STRONG_START))
1555                         _Wikitext_pop_from_stack_up_to(parser, output, STRONG_START, true);
1556                     else
1557                     {
1558                         // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1559                         _Wikitext_pop_excess_elements(parser);
1560                         _Wikitext_start_para_if_necessary(parser);
1561                         str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1562                     }
1563                 }
1564                 break;
1565
1566             case EM:
1567                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1568                 {
1569                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1570                     str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1571                 }
1572                 else
1573                 {
1574                     output = parser->capture ? parser->capture : parser->output;
1575                     if (IN(EM_START))
1576                         // already in span started with <em>, no choice but to emit this literally
1577                         str_append(output, literal_em, sizeof(literal_em) - 1);
1578                     else if (IN(EM))
1579                         // EM already seen, this is a closing tag
1580                         _Wikitext_pop_from_stack_up_to(parser, output, EM, true);
1581                     else
1582                     {
1583                         // this is a new opening
1584                         _Wikitext_pop_excess_elements(parser);
1585                         _Wikitext_start_para_if_necessary(parser);
1586                         str_append(output, em_start, sizeof(em_start) - 1);
1587                         ary_push(parser->scope, EM);
1588                         ary_push(parser->line, EM);
1589                     }
1590                 }
1591                 break;
1592
1593             case EM_START:
1594                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1595                 {
1596                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1597                     str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1598                 }
1599                 else
1600                 {
1601                     output = parser->capture ? parser->capture : parser->output;
1602                     if (IN(EM_START) || IN(EM))
1603                         str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1604                     else
1605                     {
1606                         _Wikitext_pop_excess_elements(parser);
1607                         _Wikitext_start_para_if_necessary(parser);
1608                         str_append(output, em_start, sizeof(em_start) - 1);
1609                         ary_push(parser->scope, EM_START);
1610                         ary_push(parser->line, EM_START);
1611                     }
1612                 }
1613                 break;
1614
1615             case EM_END:
1616                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1617                 {
1618                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1619                     str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1620                 }
1621                 else
1622                 {
1623                     output = parser->capture ? parser->capture : parser->output;
1624                     if (IN(EM_START))
1625                         _Wikitext_pop_from_stack_up_to(parser, output, EM_START, true);
1626                     else
1627                     {
1628                         // no EM_START in scope, so must interpret the TT_END without any special meaning
1629                         _Wikitext_pop_excess_elements(parser);
1630                         _Wikitext_start_para_if_necessary(parser);
1631                         str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1632                     }
1633                 }
1634                 break;
1635
1636             case TT:
1637                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1638                 {
1639                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1640                     str_append(parser->output, backtick, sizeof(backtick) - 1);
1641                 }
1642                 else
1643                 {
1644                     output = parser->capture ? parser->capture : parser->output;
1645                     if (IN(TT_START))
1646                         // already in span started with <tt>, no choice but to emit this literally
1647                         str_append(output, backtick, sizeof(backtick) - 1);
1648                     else if (IN(TT))
1649                         // TT (`) already seen, this is a closing tag
1650                         _Wikitext_pop_from_stack_up_to(parser, output, TT, true);
1651                     else
1652                     {
1653                         // this is a new opening
1654                         _Wikitext_pop_excess_elements(parser);
1655                         _Wikitext_start_para_if_necessary(parser);
1656                         str_append(output, tt_start, sizeof(tt_start) - 1);
1657                         ary_push(parser->scope, TT);
1658                         ary_push(parser->line, TT);
1659                     }
1660                 }
1661                 break;
1662
1663             case TT_START:
1664                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1665                 {
1666                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1667                     str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1668                 }
1669                 else
1670                 {
1671                     output = parser->capture ? parser->capture : parser->output;
1672                     if (IN(TT_START) || IN(TT))
1673                         str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1674                     else
1675                     {
1676                         _Wikitext_pop_excess_elements(parser);
1677                         _Wikitext_start_para_if_necessary(parser);
1678                         str_append(output, tt_start, sizeof(tt_start) - 1);
1679                         ary_push(parser->scope, TT_START);
1680                         ary_push(parser->line, TT_START);
1681                     }
1682                 }
1683                 break;
1684
1685             case TT_END:
1686                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1687                 {
1688                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1689                     str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1690                 }
1691                 else
1692                 {
1693                     output = parser->capture ? parser->capture : parser->output;
1694                     if (IN(TT_START))
1695                         _Wikitext_pop_from_stack_up_to(parser, output, TT_START, true);
1696                     else
1697                     {
1698                         // no TT_START in scope, so must interpret the TT_END without any special meaning
1699                         _Wikitext_pop_excess_elements(parser);
1700                         _Wikitext_start_para_if_necessary(parser);
1701                         str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1702                     }
1703                 }
1704                 break;
1705
1706             case OL:
1707             case UL:
1708                 if (IN(NO_WIKI_START) || IN(PRE_START))
1709                 {
1710                     // no need to check for PRE; can never appear inside it
1711                     str_append(parser->output, token->start, TOKEN_LEN(token));
1712                     break;
1713                 }
1714
1715                 // count number of tokens in line and scope stacks
1716                 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1717                 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1718                 j = parser->scope->count - bq_count;
1719                 k = i;
1720
1721                 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1722                 for (;;)
1723                 {
1724                     type = token->type;
1725                     if (type == OL || type == UL)
1726                     {
1727                         token = NULL;
1728                         if (i - k >= 2)                             // already seen at least one OL or UL
1729                         {
1730                             ary_push(parser->line, NESTED_LIST);    // which means this is a nested list
1731                             i += 3;
1732                         }
1733                         else
1734                             i += 2;
1735                         ary_push(parser->line, type);
1736                         ary_push(parser->line, LI);
1737
1738                         // want to compare line with scope but can only do so if scope has enough items on it
1739                         if (j >= i)
1740                         {
1741                             if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1742                                 ary_entry(parser->scope, i + bq_count - 1) == LI)
1743                             {
1744                                 // line and scope match at this point: do nothing yet
1745                             }
1746                             else
1747                             {
1748                                 // item just pushed onto line does not match corresponding slot of scope!
1749                                 for (; j >= i - 2; j--)
1750                                     // must pop back before emitting
1751                                     _Wikitext_pop_from_stack(parser, NULL);
1752
1753                                 // will emit UL or OL, then LI
1754                                 break;
1755                             }
1756                         }
1757                         else        // line stack size now exceeds scope stack size: must increase nesting level
1758                             break;  // will emit UL or OL, then LI
1759                     }
1760                     else
1761                     {
1762                         // not a OL or UL token!
1763                         if (j == i)
1764                             // must close existing LI and re-open new one
1765                             _Wikitext_pop_from_stack(parser, NULL);
1766                         else if (j > i)
1767                         {
1768                             // item just pushed onto line does not match corresponding slot of scope!
1769                             for (; j >= i; j--)
1770                                 // must pop back before emitting
1771                                 _Wikitext_pop_from_stack(parser, NULL);
1772                         }
1773                         break;
1774                     }
1775                     NEXT_TOKEN();
1776                 }
1777
1778                 // will emit
1779                 if (type == OL || type == UL)
1780                 {
1781                     // if LI is at the top of a stack this is the start of a nested list
1782                     if (j > 0 && ary_entry(parser->scope, -1) == LI)
1783                     {
1784                         // so we should precede it with a CRLF, and indicate that it's a nested list
1785                         str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1786                         ary_push(parser->scope, NESTED_LIST);
1787                     }
1788                     else
1789                     {
1790                         // this is a new list
1791                         if (IN(BLOCKQUOTE_START))
1792                             _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1793                         else
1794                             _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1795                     }
1796
1797                     // emit
1798                     _Wikitext_indent(parser);
1799                     if (type == OL)
1800                         str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1801                     else if (type == UL)
1802                         str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1803                     ary_push(parser->scope, type);
1804                     str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1805                 }
1806                 else if (type == SPACE)
1807                     // silently throw away the optional SPACE token after final list marker
1808                     token = NULL;
1809
1810                 _Wikitext_indent(parser);
1811                 str_append(parser->output, li_start, sizeof(li_start) - 1);
1812                 ary_push(parser->scope, LI);
1813
1814                 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1815                 if (type == OL || type == UL)
1816                 {
1817                     k = 0;
1818                     while (k++, NEXT_TOKEN(), (type = token->type))
1819                     {
1820                         if (type == OL || type == UL)
1821                             str_append(parser->output, token->start, TOKEN_LEN(token));
1822                         else if (type == SPACE && k == 1)
1823                         {
1824                             // silently throw away the optional SPACE token after final list marker
1825                             token = NULL;
1826                             break;
1827                         }
1828                         else
1829                             break;
1830                     }
1831                 }
1832
1833                 // jump to top of the loop to process token we scanned during lookahead
1834                 continue;
1835
1836             case H6_START:
1837             case H5_START:
1838             case H4_START:
1839             case H3_START:
1840             case H2_START:
1841             case H1_START:
1842                 if (IN(NO_WIKI_START) || IN(PRE_START))
1843                 {
1844                     // no need to check for PRE; can never appear inside it
1845                     str_append(parser->output, token->start, TOKEN_LEN(token));
1846                     break;
1847                 }
1848
1849                 // pop up to but not including the last BLOCKQUOTE on the scope stack
1850                 if (IN(BLOCKQUOTE_START))
1851                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1852                 else
1853                     _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1854
1855                 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1856                 ary_push(parser->line, type);
1857                 i = ary_count(parser->line, BLOCKQUOTE);
1858                 j = ary_count(parser->scope, BLOCKQUOTE);
1859
1860                 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1861                 if (i < j)
1862                 {
1863                     // must pop (reduce nesting level)
1864                     for (i = j - i; i > 0; i--)
1865                         _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1866                 }
1867
1868                 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1869                 while (NEXT_TOKEN(), (token->type == SPACE))
1870                     ; // discard
1871
1872                 ary_push(parser->scope, type);
1873                 _Wikitext_indent(parser);
1874
1875                 // take base_heading_level into account
1876                 type += base_heading_level;
1877                 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1878                     type = H6_START;
1879
1880                 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1881                 if (type == H6_START)
1882                     str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1883                 else if (type == H5_START)
1884                     str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1885                 else if (type == H4_START)
1886                     str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1887                 else if (type == H3_START)
1888                     str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1889                 else if (type == H2_START)
1890                     str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1891                 else if (type == H1_START)
1892                     str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1893
1894                 // jump to top of the loop to process token we scanned during lookahead
1895                 continue;
1896
1897             case H6_END:
1898                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1899                 {
1900                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1901                     str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1902                 }
1903                 else
1904                 {
1905                     _Wikitext_rollback_failed_external_link(parser); // if any
1906                     if (!IN(H6_START))
1907                     {
1908                         // literal output only if not in h6 scope (we stay silent in that case)
1909                         _Wikitext_start_para_if_necessary(parser);
1910                         str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1911                     }
1912                 }
1913                 break;
1914
1915             case H5_END:
1916                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1917                 {
1918                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1919                     str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1920                 }
1921                 else
1922                 {
1923                     _Wikitext_rollback_failed_external_link(parser); // if any
1924                     if (!IN(H5_START))
1925                     {
1926                         // literal output only if not in h5 scope (we stay silent in that case)
1927                         _Wikitext_start_para_if_necessary(parser);
1928                         str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1929                     }
1930                 }
1931                 break;
1932
1933             case H4_END:
1934                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1935                 {
1936                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1937                     str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1938                 }
1939                 else
1940                 {
1941                     _Wikitext_rollback_failed_external_link(parser); // if any
1942                     if (!IN(H4_START))
1943                     {
1944                         // literal output only if not in h4 scope (we stay silent in that case)
1945                         _Wikitext_start_para_if_necessary(parser);
1946                         str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1947                     }
1948                 }
1949                 break;
1950
1951             case H3_END:
1952                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1953                 {
1954                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1955                     str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1956                 }
1957                 else
1958                 {
1959                     _Wikitext_rollback_failed_external_link(parser); // if any
1960                     if (!IN(H3_START))
1961                     {
1962                         // literal output only if not in h3 scope (we stay silent in that case)
1963                         _Wikitext_start_para_if_necessary(parser);
1964                         str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1965                     }
1966                 }
1967                 break;
1968
1969             case H2_END:
1970                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1971                 {
1972                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1973                     str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1974                 }
1975                 else
1976                 {
1977                     _Wikitext_rollback_failed_external_link(parser); // if any
1978                     if (!IN(H2_START))
1979                     {
1980                         // literal output only if not in h2 scope (we stay silent in that case)
1981                         _Wikitext_start_para_if_necessary(parser);
1982                         str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1983                     }
1984                 }
1985                 break;
1986
1987             case H1_END:
1988                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1989                 {
1990                     _Wikitext_emit_pending_crlf_if_necessary(parser);
1991                     str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1992                 }
1993                 else
1994                 {
1995                     _Wikitext_rollback_failed_external_link(parser); // if any
1996                     if (!IN(H1_START))
1997                     {
1998                         // literal output only if not in h1 scope (we stay silent in that case)
1999                         _Wikitext_start_para_if_necessary(parser);
2000                         str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
2001                     }
2002                 }
2003                 break;
2004
2005             case MAIL:
2006                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2007                 {
2008                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2009                     str_append(parser->output, token->start, TOKEN_LEN(token));
2010                 }
2011                 else
2012                 {
2013                     _Wikitext_pop_excess_elements(parser);
2014                     _Wikitext_start_para_if_necessary(parser);
2015                     token_str->ptr = token->start;
2016                     token_str->len = TOKEN_LEN(token);
2017                     _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
2018                 }
2019                 break;
2020
2021             case URI:
2022                 if (IN(NO_WIKI_START))
2023                     // user can temporarily suppress autolinking by using <nowiki></nowiki>
2024                     // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
2025                     str_append(parser->output, token->start, TOKEN_LEN(token));
2026                 else if (IN(LINK_START))
2027                 {
2028                     // if the URI were allowed it would have been handled already in LINK_START
2029                     _Wikitext_rollback_failed_internal_link(parser);
2030                     token_str->ptr = token->start;
2031                     token_str->len = TOKEN_LEN(token);
2032                     _Wikitext_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2033                 }
2034                 else if (IN(EXT_LINK_START))
2035                 {
2036                     if (parser->link_target->len == 0)
2037                     {
2038                         // this must be our link target: look ahead to make sure we see the space we're expecting to see
2039                         token_str->ptr = token->start;
2040                         token_str->len = TOKEN_LEN(token);
2041                         NEXT_TOKEN();
2042                         if (token->type == SPACE)
2043                         {
2044                             ary_push(parser->scope, SPACE);
2045                             str_append_str(parser->link_target, token_str);
2046                             str_clear(parser->link_text);
2047                             parser->capture     = parser->link_text;
2048                             token               = NULL; // silently consume space
2049                         }
2050                         else
2051                         {
2052                             // didn't see the space! this must be an error
2053                             _Wikitext_pop_from_stack(parser, NULL);
2054                             _Wikitext_pop_excess_elements(parser);
2055                             _Wikitext_start_para_if_necessary(parser);
2056                             str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2057                             _Wikitext_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2058                         }
2059                     }
2060                     else
2061                         str_append(parser->link_text, token->start, TOKEN_LEN(token));
2062                 }
2063                 else
2064                 {
2065                     _Wikitext_pop_excess_elements(parser);
2066                     _Wikitext_start_para_if_necessary(parser);
2067                     token_str->ptr = token->start;
2068                     token_str->len = TOKEN_LEN(token);
2069                     _Wikitext_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2070                 }
2071                 break;
2072
2073             case PATH:
2074                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2075                     str_append(parser->output, token->start, TOKEN_LEN(token));
2076                 else if (IN(EXT_LINK_START))
2077                 {
2078                     if (parser->link_target->len == 0)
2079                     {
2080                         // this must be our link target: look ahead to make sure we see the space we're expecting to see
2081                         token_str->ptr = token->start;
2082                         token_str->len = TOKEN_LEN(token);
2083                         NEXT_TOKEN();
2084                         if (token->type == SPACE)
2085                         {
2086                             ary_push(parser->scope, PATH);
2087                             ary_push(parser->scope, SPACE);
2088                             str_append_str(parser->link_target, token_str);
2089                             str_clear(parser->link_text);
2090                             parser->capture     = parser->link_text;
2091                             token               = NULL; // silently consume space
2092                         }
2093                         else
2094                         {
2095                             // didn't see the space! this must be an error
2096                             _Wikitext_pop_from_stack(parser, NULL);
2097                             _Wikitext_pop_excess_elements(parser);
2098                             _Wikitext_start_para_if_necessary(parser);
2099                             str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2100                             str_append_str(parser->output, token_str);
2101                         }
2102                     }
2103                     else
2104                         str_append(parser->link_text, token->start, TOKEN_LEN(token));
2105                 }
2106                 else
2107                 {
2108                     output = parser->capture ? parser->capture : parser->output;
2109                     _Wikitext_pop_excess_elements(parser);
2110                     _Wikitext_start_para_if_necessary(parser);
2111                     str_append(output, token->start, TOKEN_LEN(token));
2112                 }
2113                 break;
2114
2115             // internal links (links to other wiki articles) look like this:
2116             //      [[another article]] (would point at, for example, "/wiki/another_article")
2117             //      [[the other article|the link text we'll use for it]]
2118             //      [[the other article | the link text we'll use for it]]
2119             // MediaWiki has strict requirements about what it will accept as a link target:
2120             //      all wikitext markup is disallowed:
2121             //          example [[foo ''bar'' baz]]
2122             //          renders [[foo <em>bar</em> baz]]        (ie. not a link)
2123             //          example [[foo <em>bar</em> baz]]
2124             //          renders [[foo <em>bar</em> baz]]        (ie. not a link)
2125             //          example [[foo <nowiki>''</nowiki> baz]]
2126             //          renders [[foo '' baz]]                  (ie. not a link)
2127             //          example [[foo <bar> baz]]
2128             //          renders [[foo &lt;bar&gt; baz]]         (ie. not a link)
2129             //      HTML entities and non-ASCII, however, make it through:
2130             //          example [[foo &euro;]]
2131             //          renders <a href="/wiki/Foo_%E2%82%AC">foo &euro;</a>
2132             //          example [[foo â‚¬]]
2133             //          renders <a href="/wiki/Foo_%E2%82%AC">foo â‚¬</a>
2134             // we'll impose similar restrictions here for the link target; allowed tokens will be:
2135             //      SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2136             // everything else will be rejected
2137             case LINK_START:
2138                 output = parser->capture ? parser->capture : parser->output;
2139                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2140                 {
2141                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2142                     str_append(output, link_start, sizeof(link_start) - 1);
2143                 }
2144                 else if (IN(EXT_LINK_START))
2145                     // already in external link scope! (and in fact, must be capturing link_text right now)
2146                     str_append(output, link_start, sizeof(link_start) - 1);
2147                 else if (IN(LINK_START))
2148                 {
2149                     // already in internal link scope! this is a syntax error
2150                     _Wikitext_rollback_failed_internal_link(parser);
2151                     str_append(parser->output, link_start, sizeof(link_start) - 1);
2152                 }
2153                 else if (IN(SEPARATOR))
2154                 {
2155                     // scanning internal link text
2156                 }
2157                 else // not in internal link scope yet
2158                 {
2159                     // will either emit a link, or the rollback of a failed link, so start the para now
2160                     _Wikitext_pop_excess_elements(parser);
2161                     _Wikitext_start_para_if_necessary(parser);
2162                     ary_push(parser->scope, LINK_START);
2163
2164                     // look ahead and try to gobble up link target
2165                     while (NEXT_TOKEN(), (type = token->type))
2166                     {
2167                         if (type == SPACE               ||
2168                             type == SPECIAL_URI_CHARS   ||
2169                             type == PATH                ||
2170                             type == PRINTABLE           ||
2171                             type == ALNUM               ||
2172                             type == DEFAULT             ||
2173                             type == QUOT                ||
2174                             type == QUOT_ENTITY         ||
2175                             type == AMP                 ||
2176                             type == AMP_ENTITY          ||
2177                             type == IMG_START           ||
2178                             type == IMG_END             ||
2179                             type == LEFT_CURLY          ||
2180                             type == RIGHT_CURLY)
2181                         {
2182                             // accumulate these tokens into link_target
2183                             if (parser->link_target->len == 0)
2184                             {
2185                                 str_clear(parser->link_target);
2186                                 parser->capture = parser->link_target;
2187                             }
2188                             if (type == QUOT_ENTITY)
2189                                 // don't insert the entity, insert the literal quote
2190                                 str_append(parser->link_target, quote, sizeof(quote) - 1);
2191                             else if (type == AMP_ENTITY)
2192                                 // don't insert the entity, insert the literal ampersand
2193                                 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2194                             else
2195                                 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2196                         }
2197                         else if (type == LINK_END)
2198                         {
2199                             if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2200                                 _Wikitext_rollback_failed_internal_link(parser);
2201                             break; // jump back to top of loop (will handle this in LINK_END case below)
2202                         }
2203                         else if (type == SEPARATOR)
2204                         {
2205                             if (parser->link_target->len == 0) // bail for inputs like "[[|"
2206                                 _Wikitext_rollback_failed_internal_link(parser);
2207                             else
2208                             {
2209                                 ary_push(parser->scope, SEPARATOR);
2210                                 str_clear(parser->link_text);
2211                                 parser->capture     = parser->link_text;
2212                                 token               = NULL;
2213                             }
2214                             break;
2215                         }
2216                         else // unexpected token (syntax error)
2217                         {
2218                             _Wikitext_rollback_failed_internal_link(parser);
2219                             break; // jump back to top of loop to handle unexpected token
2220                         }
2221                     }
2222
2223                     // jump to top of the loop to process token we scanned during lookahead (if any)
2224                     continue;
2225                 }
2226                 break;
2227
2228             case LINK_END:
2229                 output = parser->capture ? parser->capture : parser->output;
2230                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2231                 {
2232                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2233                     str_append(output, link_end, sizeof(link_end) - 1);
2234                 }
2235                 else if (IN(EXT_LINK_START))
2236                     // already in external link scope! (and in fact, must be capturing link_text right now)
2237                     str_append(output, link_end, sizeof(link_end) - 1);
2238                 else if (IN(LINK_START)) // in internal link scope!
2239                 {
2240                     if (_Wikitext_blank(parser->link_target))
2241                     {
2242                         // special case for inputs like "[[    ]]"
2243                         _Wikitext_rollback_failed_internal_link(parser);
2244                         str_append(parser->output, link_end, sizeof(link_end) - 1);
2245                         break;
2246                     }
2247                     if (parser->link_text->len == 0 ||
2248                         _Wikitext_blank(parser->link_text))
2249                     {
2250                         // use link target as link text
2251                         str_clear(parser->link_text);
2252                         _Wikitext_append_sanitized_link_target(parser, parser->link_text, true);
2253                     }
2254                     else
2255                         _Wikitext_trim_link_text(parser);
2256                     _Wikitext_encode_link_target(parser);
2257                     _Wikitext_pop_from_stack_up_to(parser, output, LINK_START, true);
2258                     parser->capture = NULL;
2259                     _Wikitext_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, false);
2260                     str_clear(parser->link_target);
2261                     str_clear(parser->link_text);
2262                 }
2263                 else // wasn't in internal link scope
2264                 {
2265                     _Wikitext_pop_excess_elements(parser);
2266                     _Wikitext_start_para_if_necessary(parser);
2267                     str_append(output, link_end, sizeof(link_end) - 1);
2268                 }
2269                 break;
2270
2271             // external links look like this:
2272             //      [http://google.com/ the link text]
2273             //      [/other/page/on/site see this page]
2274             // strings in square brackets which don't match this syntax get passed through literally; eg:
2275             //      he was very angery [sic] about the turn of events
2276             case EXT_LINK_START:
2277                 output = parser->capture ? parser->capture : parser->output;
2278                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2279                 {
2280                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2281                     str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2282                 }
2283                 else if (IN(EXT_LINK_START))
2284                     // already in external link scope! (and in fact, must be capturing link_text right now)
2285                     str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2286                 else if (IN(LINK_START))
2287                 {
2288                     // already in internal link scope!
2289                     if (parser->link_target->len == 0 || !IN(SPACE))
2290                         str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2291                     else // link target has already been scanned
2292                         str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2293                 }
2294                 else // not in external link scope yet
2295                 {
2296                     // will either emit a link, or the rollback of a failed link, so start the para now
2297                     _Wikitext_pop_excess_elements(parser);
2298                     _Wikitext_start_para_if_necessary(parser);
2299
2300                     // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2301                     NEXT_TOKEN();
2302                     if (token->type == URI || token->type == PATH)
2303                         ary_push(parser->scope, EXT_LINK_START);    // so far so good, jump back to the top of the loop
2304                     else
2305                         // only get here if there was a syntax error (missing URI)
2306                         str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2307                     continue; // jump back to top of loop to handle token (either URI or whatever it is)
2308                 }
2309                 break;
2310
2311             case EXT_LINK_END:
2312                 output = parser->capture ? parser->capture : parser->output;
2313                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2314                 {
2315                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2316                     str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2317                 }
2318                 else if (IN(EXT_LINK_START))
2319                 {
2320                     if (parser->link_text->len == 0)
2321                         // syntax error: external link with no link text
2322                         _Wikitext_rollback_failed_external_link(parser);
2323                     else
2324                     {
2325                         // success!
2326                         j = IN(PATH) ? Qnil : parser->external_link_class;
2327                         _Wikitext_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2328                         parser->capture = NULL;
2329                         _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2330                     }
2331                     str_clear(parser->link_target);
2332                     str_clear(parser->link_text);
2333                 }
2334                 else
2335                 {
2336                     _Wikitext_pop_excess_elements(parser);
2337                     _Wikitext_start_para_if_necessary(parser);
2338                     str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2339                 }
2340                 break;
2341
2342             case SEPARATOR:
2343                 output = parser->capture ? parser->capture : parser->output;
2344                 _Wikitext_pop_excess_elements(parser);
2345                 _Wikitext_start_para_if_necessary(parser);
2346                 str_append(output, separator, sizeof(separator) - 1);
2347                 break;
2348
2349             case SPACE:
2350                 output = parser->capture ? parser->capture : parser->output;
2351                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2352                 {
2353                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2354                     str_append(output, token->start, TOKEN_LEN(token));
2355                 }
2356                 else
2357                 {
2358                     // peek ahead to see next token
2359                     char    *token_ptr  = token->start;
2360                     int     token_len   = TOKEN_LEN(token);
2361                     NEXT_TOKEN();
2362                     type = token->type;
2363                     if (((type == H6_END) && IN(H6_START)) ||
2364                         ((type == H5_END) && IN(H5_START)) ||
2365                         ((type == H4_END) && IN(H4_START)) ||
2366                         ((type == H3_END) && IN(H3_START)) ||
2367                         ((type == H2_END) && IN(H2_START)) ||
2368                         ((type == H1_END) && IN(H1_START)))
2369                     {
2370                         // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2371                     }
2372                     else
2373                     {
2374                         // emit the space
2375                         _Wikitext_pop_excess_elements(parser);
2376                         _Wikitext_start_para_if_necessary(parser);
2377                         str_append(output, token_ptr, token_len);
2378                     }
2379
2380                     // jump to top of the loop to process token we scanned during lookahead
2381                     continue;
2382                 }
2383                 break;
2384
2385             case QUOT_ENTITY:
2386             case AMP_ENTITY:
2387             case NAMED_ENTITY:
2388             case DECIMAL_ENTITY:
2389                 // pass these through unaltered as they are case sensitive
2390                 output = parser->capture ? parser->capture : parser->output;
2391                 _Wikitext_pop_excess_elements(parser);
2392                 _Wikitext_start_para_if_necessary(parser);
2393                 str_append(output, token->start, TOKEN_LEN(token));
2394                 break;
2395
2396             case HEX_ENTITY:
2397                 // normalize hex entities (downcase them)
2398                 output = parser->capture ? parser->capture : parser->output;
2399                 _Wikitext_pop_excess_elements(parser);
2400                 _Wikitext_start_para_if_necessary(parser);
2401                 str_append(output, token->start, TOKEN_LEN(token));
2402                 _Wikitext_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2403                 break;
2404
2405             case QUOT:
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, quot_entity, sizeof(quot_entity) - 1);
2410                 break;
2411
2412             case AMP:
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, amp_entity, sizeof(amp_entity) - 1);
2417                 break;
2418
2419             case LESS:
2420                 output = parser->capture ? parser->capture : parser->output;
2421                 _Wikitext_pop_excess_elements(parser);
2422                 _Wikitext_start_para_if_necessary(parser);
2423                 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2424                 break;
2425
2426             case GREATER:
2427                 output = parser->capture ? parser->capture : parser->output;
2428                 _Wikitext_pop_excess_elements(parser);
2429                 _Wikitext_start_para_if_necessary(parser);
2430                 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2431                 break;
2432
2433             case IMG_START:
2434                 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2435                 {
2436                     _Wikitext_emit_pending_crlf_if_necessary(parser);
2437                     str_append(parser->output, token->start, TOKEN_LEN(token));
2438                 }
2439                 else if (parser->capture)
2440                     str_append(parser->capture, token->start, TOKEN_LEN(token));
2441                 else
2442                 {
2443                     // not currently capturing: will be emitting something on success or failure, so get ready
2444                     _Wikitext_pop_excess_elements(parser);
2445                     _Wikitext_start_para_if_necessary(parser);
2446
2447                     // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2448                     // will cheat here and abuse the link_target capture buffer to accumulate text
2449                     while (NEXT_TOKEN(), (type = token->type))
2450                     {
2451                         if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2452                             str_append(parser->link_target, token->start, TOKEN_LEN(token));
2453                         else if (type == IMG_END && parser->link_target->len > 0)
2454                         {
2455                             // success
2456                             _Wikitext_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2457                             token = NULL;
2458                             break;
2459                         }
2460                         else // unexpected token or zero-length target (syntax error)
2461                         {
2462                             // rollback
2463                             str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2464                             if (parser->link_target->len > 0)
2465                                 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2466                             break;
2467                         }
2468                     }
2469
2470                     // jump to top of the loop to process token we scanned during lookahead
2471                     str_clear(parser->link_target);
2472                     continue;
2473                 }
2474                 break;
2475
2476             case CRLF:
2477                 i = parser->pending_crlf;
2478                 parser->pending_crlf = false;
2479                 _Wikitext_rollback_failed_link(parser); // if any
2480                 if (IN(NO_WIKI_START) || IN(PRE_START))
2481                 {
2482                     ary_clear(parser->line_buffer);
2483                     str_append_str(parser->output, parser->line_ending);
2484                     break;
2485                 }
2486                 else if (IN(PRE))
2487                 {
2488                     // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2489                     if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2490                         // don't emit in this case
2491                         _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2492                     else
2493                     {
2494                         if (ary_entry(parser->line_buffer, -2) == PRE)
2495                         {
2496                              // only thing on line is the PRE: emit pending line ending (if we had one)
2497                              if (i)
2498                                  str_append_str(parser->output, parser->line_ending);
2499                         }
2500
2501                         // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2502                         ary_clear(parser->line);
2503                         ary_clear(parser->line_buffer);
2504
2505                         // peek ahead to see if this is definitely the end of the PRE block
2506                         NEXT_TOKEN();
2507                         type = token->type;
2508                         if (type != BLOCKQUOTE && type != PRE)
2509                             // this is definitely the end of the block, so don't emit
2510                             _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2511                         else
2512                             // potentially will emit
2513                             parser->pending_crlf = true;
2514
2515                         continue; // jump back to top of loop to handle token grabbed via lookahead
2516                     }
2517                 }
2518                 else
2519                 {
2520                     parser->pending_crlf = true;
2521
2522                     // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2523                     // as a side effect, this handles any open span-level elements and unclosed blocks
2524                     // (with special handling for P blocks and LI elements)
2525                     i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2526                     for (j = parser->scope->count; j > i; j--)
2527                     {
2528                         if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2529                         {
2530                             parser->pending_crlf = false;
2531                             break;
2532                         }
2533
2534                         // special handling on last iteration through the loop if the top item on the scope is a P block
2535                         if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2536                         {
2537                             // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2538                             // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2539                             // because in those blocks BLOCKQUOTE tokens have no special meaning)
2540                             if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2541                                 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2542                                 // paragraph break
2543                                 parser->pending_crlf = false;
2544                             else
2545                                 // not a paragraph break!
2546                                 continue;
2547                         }
2548                         _Wikitext_pop_from_stack(parser, NULL);
2549                     }
2550                 }
2551
2552                 // delete the entire contents of the line scope stack and buffer
2553                 ary_clear(parser->line);
2554                 ary_clear(parser->line_buffer);
2555                 break;
2556
2557             case SPECIAL_URI_CHARS:
2558             case PRINTABLE:
2559             case ALNUM:
2560             case IMG_END:
2561             case LEFT_CURLY:
2562             case RIGHT_CURLY:
2563                 output = parser->capture ? parser->capture : parser->output;
2564                 _Wikitext_pop_excess_elements(parser);
2565                 _Wikitext_start_para_if_necessary(parser);
2566                 str_append(output, token->start, TOKEN_LEN(token));
2567                 break;
2568
2569             case DEFAULT:
2570                 output = parser->capture ? parser->capture : parser->output;
2571                 _Wikitext_pop_excess_elements(parser);
2572                 _Wikitext_start_para_if_necessary(parser);
2573                 //str_append_string(output, _Wikitext_utf32_char_to_entity(token->code_point));    // convert to entity
2574                 // TODO: replace this with a different append function
2575                 str_grow(output, output->len + 8);
2576                 _Wikitext_append_entity_from_utf32_char(output->ptr + output->len, token->code_point);
2577                 output->len += 8;
2578                 break;
2579
2580             case END_OF_FILE:
2581                 // special case for input like " foo\n " (see pre_spec.rb)
2582                 if (IN(PRE) &&
2583                     ary_entry(parser->line_buffer, -2) == PRE &&
2584                     parser->pending_crlf)
2585                     str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2586
2587                 // close any open scopes on hitting EOF
2588                 _Wikitext_rollback_failed_link(parser); // if any
2589                 _Wikitext_pop_all_from_stack(parser);
2590                 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2591
2592             default:
2593                 break;
2594         }
2595
2596         // reset current token; forcing lexer to return another token at the top of the loop
2597         token = NULL;
2598     } while (1);
2599 return_output:
2600     // nasty hack to avoid re-allocating our return value
2601     str_append(parser->output, null_str, 1); // null-terminate
2602
2603     // won't work for Ruby 1.9
2604     free(RSTRING(out)->ptr);
2605     RSTRING(out)->ptr = parser->output->ptr;
2606     RSTRING(out)->len = parser->output->len - 1; // don't count null termination
2607     parser->output->ptr = NULL; // don't double-free
2608     return out;
2609 }