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