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