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