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