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