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