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