1 // Copyright 2007-2012 Wincent Colaiuta. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are met:
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.
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.
30 #include "wikitext_ragel.h"
32 #define IN(type) ary_includes(parser->scope, type)
33 #define IN_EITHER_OF(type1, type2) ary_includes2(parser->scope, type1, type2)
34 #define IN_ANY_OF(type1, type2, type3) ary_includes3(parser->scope, type1, type2, type3)
37 enum { HTML_OUTPUT, XML_OUTPUT };
39 // poor man's object orientation in C:
40 // instead of passing around multiple parameters between functions in the parser
41 // we pack everything into a struct and pass around only a pointer to that
44 str_t *capture; // capturing to link_target, link_text, or NULL (direct to output, not capturing)
45 str_t *output; // for accumulating output to be returned
46 str_t *link_target; // short term "memory" for parsing links
47 str_t *link_text; // short term "memory" for parsing links
49 str_t *tabulation; // caching buffer for emitting indentation
50 ary_t *scope; // stack for tracking scope
51 ary_t *line; // stack for tracking scope as implied by current line
52 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
53 VALUE external_link_class; // CSS class applied to external links
54 VALUE external_link_rel; // rel attribute applied to external links
55 VALUE mailto_class; // CSS class applied to email (mailto) links
56 VALUE img_prefix; // path prepended when emitting img tags
57 int output_style; // HTML_OUTPUT (default) or XML_OUTPUT
58 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
59 int current_indent; // fluctuates according to currently nested structures
60 int base_heading_level;
63 bool space_to_underscore;
66 const char null_str[] = { 0 };
67 const char escaped_no_wiki_start[] = "<nowiki>";
68 const char escaped_no_wiki_end[] = "</nowiki>";
69 const char literal_strong_em[] = "'''''";
70 const char literal_strong[] = "'''";
71 const char literal_em[] = "''";
72 const char escaped_em_start[] = "<em>";
73 const char escaped_em_end[] = "</em>";
74 const char escaped_strong_start[] = "<strong>";
75 const char escaped_strong_end[] = "</strong>";
76 const char escaped_tt_start[] = "<tt>";
77 const char escaped_tt_end[] = "</tt>";
78 const char pre_start[] = "<pre>";
79 const char pre_end[] = "</pre>";
80 const char escaped_pre_start[] = "<pre>";
81 const char escaped_pre_end[] = "</pre>";
82 const char blockquote_start[] = "<blockquote>";
83 const char blockquote_end[] = "</blockquote>";
84 const char escaped_blockquote_start[] = "<blockquote>";
85 const char escaped_blockquote_end[] = "</blockquote>";
86 const char strong_em_start[] = "<strong><em>";
87 const char strong_start[] = "<strong>";
88 const char strong_end[] = "</strong>";
89 const char em_start[] = "<em>";
90 const char em_end[] = "</em>";
91 const char code_start[] = "<code>";
92 const char code_end[] = "</code>";
93 const char ol_start[] = "<ol>";
94 const char ol_end[] = "</ol>";
95 const char ul_start[] = "<ul>";
96 const char ul_end[] = "</ul>";
97 const char li_start[] = "<li>";
98 const char li_end[] = "</li>";
99 const char h6_start[] = "<h6>";
100 const char h6_end[] = "</h6>";
101 const char h5_start[] = "<h5>";
102 const char h5_end[] = "</h5>";
103 const char h4_start[] = "<h4>";
104 const char h4_end[] = "</h4>";
105 const char h3_start[] = "<h3>";
106 const char h3_end[] = "</h3>";
107 const char h2_start[] = "<h2>";
108 const char h2_end[] = "</h2>";
109 const char h1_start[] = "<h1>";
110 const char h1_end[] = "</h1>";
111 const char p_start[] = "<p>";
112 const char p_end[] = "</p>";
113 const char space[] = " ";
114 const char a_start[] = "<a href=\"";
115 const char a_class[] = "\" class=\"";
116 const char a_rel[] = "\" rel=\"";
117 const char a_start_close[] = "\">";
118 const char a_end[] = "</a>";
119 const char link_start[] = "[[";
120 const char link_end[] = "]]";
121 const char separator[] = "|";
122 const char ext_link_start[] = "[";
123 const char backtick[] = "`";
124 const char quote[] = "\"";
125 const char ampersand[] = "&";
126 const char quot_entity[] = """;
127 const char amp_entity[] = "&";
128 const char lt_entity[] = "<";
129 const char gt_entity[] = ">";
130 const char escaped_blockquote[] = "> ";
131 const char ext_link_end[] = "]";
132 const char literal_img_start[] = "{{";
133 const char img_start[] = "<img src=\"";
134 const char img_end_xml[] = "\" />";
135 const char img_end_html[] = "\">";
136 const char img_alt[] = "\" alt=\"";
137 const char pre_class_start[] = "<pre class=\"";
138 const char pre_class_end[] = "-syntax\">";
140 // Mark the parser struct designated by ptr as a participant in Ruby's
141 // mark-and-sweep garbage collection scheme. A variable named name is placed on
142 // the C stack to prevent the structure from being prematurely collected.
143 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
145 parser_t *parser_new(void)
147 parser_t *parser = ALLOC_N(parser_t, 1);
148 parser->capture = NULL; // not a real instance, pointer to other member's instance
149 parser->output = str_new();
150 parser->link_target = str_new();
151 parser->link_text = str_new();
152 parser->line_ending = NULL; // caller should set up
153 parser->tabulation = str_new();
154 parser->scope = ary_new();
155 parser->line = ary_new();
156 parser->line_buffer = ary_new();
157 parser->external_link_class = Qnil; // caller should set up
158 parser->external_link_rel = Qnil; // caller should set up
159 parser->mailto_class = Qnil; // caller should set up
160 parser->img_prefix = Qnil; // caller should set up
161 parser->output_style = HTML_OUTPUT;
162 parser->base_indent = 0;
163 parser->current_indent = 0;
164 parser->base_heading_level = 0;
165 parser->pending_crlf = false;
166 parser->autolink = true;
167 parser->space_to_underscore = true;
171 void parser_free(parser_t *parser)
173 // we don't free parser->capture; it's just a redundant pointer
174 if (parser->output) str_free(parser->output);
175 if (parser->link_target) str_free(parser->link_target);
176 if (parser->link_text) str_free(parser->link_text);
177 if (parser->line_ending) str_free(parser->line_ending);
178 if (parser->tabulation) str_free(parser->tabulation);
179 if (parser->scope) ary_free(parser->scope);
180 if (parser->line) ary_free(parser->line);
181 if (parser->line_buffer) ary_free(parser->line_buffer);
185 // for testing and debugging only
186 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
190 string = StringValue(string);
191 VALUE tokens = rb_ary_new();
192 char *p = RSTRING_PTR(string);
193 long len = RSTRING_LEN(string);
196 next_token(&token, NULL, p, pe);
197 rb_ary_push(tokens, wiki_token(&token));
198 while (token.type != END_OF_FILE)
200 next_token(&token, &token, NULL, pe);
201 rb_ary_push(tokens, wiki_token(&token));
206 // for benchmarking raw tokenization speed only
207 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
211 string = StringValue(string);
212 char *p = RSTRING_PTR(string);
213 long len = RSTRING_LEN(string);
216 next_token(&token, NULL, p, pe);
217 while (token.type != END_OF_FILE)
218 next_token(&token, &token, NULL, pe);
222 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
225 VALUE string, options;
226 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
230 string = StringValue(string);
231 VALUE tokens = rb_ary_new();
233 // check instance variables
234 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
236 // process options hash (can override instance variables)
237 if (!NIL_P(options) && TYPE(options) == T_HASH)
239 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
240 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
242 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
247 char *p = RSTRING_PTR(string);
248 long len = RSTRING_LEN(string);
251 token_t *_token = &token;
252 next_token(&token, NULL, p, pe);
253 while (token.type != END_OF_FILE)
260 if (TOKEN_LEN(_token) >= min_len)
261 rb_ary_push(tokens, TOKEN_TEXT(_token));
264 // ignore everything else
267 next_token(&token, &token, NULL, pe);
272 // we downcase "in place", overwriting the original contents of the buffer
273 void wiki_downcase_bang(char *ptr, long len)
275 for (long i = 0; i < len; i++)
277 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
282 // prepare hyperlink and append it to parser->output
283 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
284 // or merely the literal link target
285 // if link_text is Qnil, the link_target is re-used for the link text
286 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, VALUE link_rel, bool check_autolink)
288 if (check_autolink && !parser->autolink)
289 str_append_str(parser->output, link_target);
292 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
293 if (!NIL_P(link_prefix))
294 str_append_string(parser->output, link_prefix);
295 str_append_str(parser->output, link_target);
297 // special handling for mailto URIs
298 const char *mailto = "mailto:";
299 long mailto_len = (long)sizeof(mailto) - 1; // don't count NUL byte
300 if ((link_target->len >= mailto_len &&
301 strncmp(mailto, link_target->ptr, mailto_len) == 0) ||
302 (!NIL_P(link_prefix) &&
303 RSTRING_LEN(link_prefix) >= mailto_len &&
304 strncmp(mailto, RSTRING_PTR(link_prefix), mailto_len) == 0))
305 link_class = parser->mailto_class; // use mailto_class from parser
306 if (link_class != Qnil)
308 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
309 str_append_string(parser->output, link_class);
311 if (link_rel != Qnil)
313 str_append(parser->output, a_rel, sizeof(a_rel) - 1); // " rel="
314 str_append_string(parser->output, link_rel);
316 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
317 if (!link_text || link_text->len == 0) // re-use link_target
318 str_append_str(parser->output, link_target);
320 str_append_str(parser->output, link_text);
321 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
325 void wiki_append_img(parser_t *parser, char *token_ptr, int token_len)
327 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
328 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
329 str_append_string(parser->output, parser->img_prefix);
330 str_append(parser->output, token_ptr, token_len);
331 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
332 str_append(parser->output, token_ptr, token_len);
333 if (parser->output_style == XML_OUTPUT)
334 str_append(parser->output, img_end_xml, sizeof(img_end_xml) - 1); // " />
336 str_append(parser->output, img_end_html, sizeof(img_end_html) - 1); // ">
339 // will emit indentation only if we are about to emit any of:
340 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
341 // each time we enter one of those spans must ++ the indentation level
342 void wiki_indent(parser_t *parser)
344 if (parser->base_indent == -1) // indentation disabled
346 int space_count = parser->current_indent + parser->base_indent;
349 char *old_end, *new_end;
350 if (parser->tabulation->len < space_count)
351 str_grow(parser->tabulation, space_count); // reallocates if necessary
352 old_end = parser->tabulation->ptr + parser->tabulation->len;
353 new_end = parser->tabulation->ptr + space_count;
354 while (old_end < new_end)
356 if (space_count > parser->tabulation->len)
357 parser->tabulation->len = space_count;
358 str_append(parser->output, parser->tabulation->ptr, space_count);
360 parser->current_indent += 2;
363 void wiki_append_pre_start(parser_t *parser, token_t *token)
366 if ((size_t)TOKEN_LEN(token) > sizeof(pre_start) - 1)
368 str_append(parser->output, pre_class_start, sizeof(pre_class_start) - 1); // <pre class="
369 str_append(parser->output, token->start + 11, TOKEN_LEN(token) - 13); // (the "lang" substring)
370 str_append(parser->output, pre_class_end, sizeof(pre_class_end) - 1); // -syntax">
373 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
374 ary_push(parser->scope, PRE_START);
375 ary_push(parser->line, PRE_START);
378 void wiki_dedent(parser_t *parser, bool emit)
380 if (parser->base_indent == -1) // indentation disabled
382 parser->current_indent -= 2;
385 int space_count = parser->current_indent + parser->base_indent;
387 str_append(parser->output, parser->tabulation->ptr, space_count);
390 // Pops a single item off the parser's scope stack.
391 // A corresponding closing tag is written to the target string.
392 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
393 void wiki_pop_from_stack(parser_t *parser, str_t *target)
395 int top = ary_entry(parser->scope, -1);
399 target = parser->output;
401 // for headings, take base_heading_level into account
402 if (top >= H1_START && top <= H6_START)
404 top += parser->base_heading_level;
405 // no need to check for underflow (base_heading_level is never negative)
414 str_append(target, pre_end, sizeof(pre_end) - 1);
415 str_append_str(target, parser->line_ending);
416 wiki_dedent(parser, false);
420 case BLOCKQUOTE_START:
421 wiki_dedent(parser, true);
422 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
423 str_append_str(target, parser->line_ending);
427 // not a real HTML tag; so nothing to pop
432 str_append(target, strong_end, sizeof(strong_end) - 1);
437 str_append(target, em_end, sizeof(em_end) - 1);
442 str_append(target, code_end, sizeof(code_end) - 1);
446 wiki_dedent(parser, true);
447 str_append(target, ol_end, sizeof(ol_end) - 1);
448 str_append_str(target, parser->line_ending);
452 wiki_dedent(parser, true);
453 str_append(target, ul_end, sizeof(ul_end) - 1);
454 str_append_str(target, parser->line_ending);
458 // next token to pop will be a LI
459 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
460 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
461 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
462 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
463 wiki_dedent(parser, true); // we really only want to emit the spaces
464 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
468 str_append(target, li_end, sizeof(li_end) - 1);
469 str_append_str(target, parser->line_ending);
470 wiki_dedent(parser, false);
474 str_append(target, h6_end, sizeof(h6_end) - 1);
475 str_append_str(target, parser->line_ending);
476 wiki_dedent(parser, false);
480 str_append(target, h5_end, sizeof(h5_end) - 1);
481 str_append_str(target, parser->line_ending);
482 wiki_dedent(parser, false);
486 str_append(target, h4_end, sizeof(h4_end) - 1);
487 str_append_str(target, parser->line_ending);
488 wiki_dedent(parser, false);
492 str_append(target, h3_end, sizeof(h3_end) - 1);
493 str_append_str(target, parser->line_ending);
494 wiki_dedent(parser, false);
498 str_append(target, h2_end, sizeof(h2_end) - 1);
499 str_append_str(target, parser->line_ending);
500 wiki_dedent(parser, false);
504 str_append(target, h1_end, sizeof(h1_end) - 1);
505 str_append_str(target, parser->line_ending);
506 wiki_dedent(parser, false);
510 // not an HTML tag; so nothing to emit
514 // not an HTML tag; so nothing to emit
518 // not an HTML tag; so nothing to emit
522 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
526 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
530 str_append(target, p_end, sizeof(p_end) - 1);
531 str_append_str(target, parser->line_ending);
532 wiki_dedent(parser, false);
540 // should probably raise an exception here
543 ary_pop(parser->scope);
546 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
547 // If including is true then the item itself is also popped.
548 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
549 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
551 int continue_looping = 1;
554 int top = ary_entry(parser->scope, -1);
561 continue_looping = 0;
563 wiki_pop_from_stack(parser, target);
564 } while (continue_looping);
567 void wiki_pop_all_from_stack(parser_t *parser)
569 for (int i = 0, max = parser->scope->count; i < max; i++)
570 wiki_pop_from_stack(parser, NULL);
573 void wiki_start_para_if_necessary(parser_t *parser)
578 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
579 if (parser->scope->count == 0 ||
580 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
581 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
584 str_append(parser->output, p_start, sizeof(p_start) - 1);
585 ary_push(parser->scope, P);
586 ary_push(parser->line, P);
588 else if (parser->pending_crlf)
591 // already in a paragraph block; convert pending CRLF into a space
592 str_append(parser->output, space, sizeof(space) - 1);
594 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
595 str_append_str(parser->output, parser->line_ending);
597 parser->pending_crlf = false;
600 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
602 if (parser->pending_crlf)
604 str_append_str(parser->output, parser->line_ending);
605 parser->pending_crlf = false;
609 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
610 // For example, given input like:
615 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
616 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
621 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
622 // but not on the line scope:
627 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
628 // on the line scope.
629 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
630 // entering the for loop.
631 void wiki_pop_excess_elements(parser_t *parser)
635 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
637 // special case for last item on scope
640 // don't auto-pop P if it is only item on scope
641 if (ary_entry(parser->scope, -1) == P)
643 // add P to the line scope to prevent us entering the loop at all next time around
644 ary_push(parser->line, P);
648 wiki_pop_from_stack(parser, NULL);
652 // Convert a single UTF-8 codepoint to UTF-32
654 // Expects an input buffer, src, containing a UTF-8 encoded character (which
655 // may be multi-byte). The end of the input buffer, end, is also passed in to
656 // allow the detection of invalidly truncated codepoints. The number of bytes
657 // in the UTF-8 character (between 1 and 4) is returned by reference in
660 // Raises a RangeError if the supplied character is invalid UTF-8.
661 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
664 if ((unsigned char)src[0] <= 0x7f)
670 else if ((src[0] & 0xe0) == 0xc0)
672 // byte starts with 110..... : this should be a two-byte sequence
675 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
676 else if (((unsigned char)src[0] == 0xc0) ||
677 ((unsigned char)src[0] == 0xc1))
678 // overlong encoding: lead byte of 110..... but code point <= 127
679 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
680 else if ((src[1] & 0xc0) != 0x80 )
681 // should have second byte starting with 10......
682 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
685 ((uint32_t)(src[0] & 0x1f)) << 6 |
689 else if ((src[0] & 0xf0) == 0xe0)
691 // byte starts with 1110.... : this should be a three-byte sequence
693 // missing second or third byte
694 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
695 else if (((src[1] & 0xc0) != 0x80 ) ||
696 ((src[2] & 0xc0) != 0x80 ))
697 // should have second and third bytes starting with 10......
698 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
701 ((uint32_t)(src[0] & 0x0f)) << 12 |
702 ((uint32_t)(src[1] & 0x3f)) << 6 |
706 else if ((src[0] & 0xf8) == 0xf0)
708 // bytes starts with 11110... : this should be a four-byte sequence
710 // missing second, third, or fourth byte
711 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
712 else if ((unsigned char)src[0] >= 0xf5 &&
713 (unsigned char)src[0] <= 0xf7)
714 // disallowed by RFC 3629 (codepoints above 0x10ffff)
715 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
716 else if (((src[1] & 0xc0) != 0x80 ) ||
717 ((src[2] & 0xc0) != 0x80 ) ||
718 ((src[3] & 0xc0) != 0x80 ))
719 // should have second and third bytes starting with 10......
720 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
723 ((uint32_t)(src[0] & 0x07)) << 18 |
724 ((uint32_t)(src[1] & 0x3f)) << 12 |
725 ((uint32_t)(src[1] & 0x3f)) << 6 |
730 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
734 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
736 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
737 char scratch = (character & 0xf000) >> 12;
738 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
739 scratch = (character & 0x0f00) >> 8;
740 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
741 scratch = (character & 0x00f0) >> 4;
742 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
743 scratch = character & 0x000f;
744 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
745 str_append(output, hex_string, sizeof(hex_string));
748 // trim parser->link_text in place
749 void wiki_trim_link_text(parser_t *parser)
751 char *src = parser->link_text->ptr;
752 char *start = src; // remember this so we can check if we're at the start
754 char *non_space = src; // remember last non-space character output
755 char *end = src + parser->link_text->len;
767 if (left != start || non_space + 1 != end)
769 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
770 parser->link_text->len = (non_space + 1) - left;
771 memmove(parser->link_text->ptr, left, parser->link_text->len);
775 // - non-printable (non-ASCII) characters converted to numeric entities
776 // - QUOT and AMP characters converted to named entities
777 // - if trim is true, leading and trailing whitespace trimmed
778 // - if trim is false, there is no special treatment of spaces
779 void wiki_append_sanitized_link_target(str_t *link_target, str_t *output, bool trim)
781 char *src = link_target->ptr;
782 char *start = src; // remember this so we can check if we're at the start
783 char *non_space = output->ptr + output->len; // remember last non-space character output
784 char *end = src + link_target->len;
787 // need at most 8 bytes to display each input character (�)
788 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
790 char *old_ptr = output->ptr;
791 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
792 if (old_ptr != output->ptr) // may have moved
793 non_space += output->ptr - old_ptr;
798 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
799 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
801 else if (*src == '&')
803 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
804 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
806 else if (*src == '<' || *src == '>')
807 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
808 else if (*src == ' ' && src == start && trim)
809 start++; // we eat leading space
810 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
812 *(output->ptr + output->len) = *src;
815 else // all others: must convert to entities
818 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
820 non_space = output->ptr + output->len;
824 non_space = output->ptr + output->len;
828 // trim trailing space if necessary
829 if (trim && output->ptr + output->len != non_space)
830 output->len -= (output->ptr + output->len) - non_space;
833 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
836 parser.link_target = str_new_from_string(string);
837 GC_WRAP_STR(parser.link_target, link_target_gc);
838 str_t *output = str_new();
839 GC_WRAP_STR(output, output_gc);
840 wiki_append_sanitized_link_target(parser.link_target, output, true);
841 return string_from_str(output);
844 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
846 // Leading and trailing whitespace trimmed. Spaces are converted to
847 // underscores if the parser space_to_underscore member is true.
848 static void wiki_encode_link_target(parser_t *parser)
850 char *src = parser->link_target->ptr;
851 char *start = src; // remember this so we can check if we're at the start
852 long len = parser->link_target->len;
855 char *end = src + len;
856 long dest_len = len * 2;
857 char *dest = ALLOC_N(char, dest_len);
858 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
859 char *non_space = dest; // remember last non-space character output
860 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
861 for (; src < end; src++)
863 // worst case: a single character may grow to 3 characters once encoded
864 if ((dest + 3) > (dest_ptr + dest_len))
866 // outgrowing buffer, must reallocate
867 char *old_dest = dest;
868 char *old_dest_ptr = dest_ptr;
870 dest = realloc(dest_ptr, dest_len);
873 // would have used reallocf, but this has to run on Linux too, not just Darwin
875 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
878 dest = dest_ptr + (old_dest - old_dest_ptr);
879 non_space = dest_ptr + (non_space - old_dest_ptr);
882 // pass through unreserved characters
883 if ((*src >= 'a' && *src <= 'z') ||
884 (*src >= 'A' && *src <= 'Z') ||
885 (*src >= '0' && *src <= '9') ||
894 else if (*src == ' ' && src == start)
895 start++; // we eat leading space
896 else if (*src == ' ' && parser->space_to_underscore)
898 else // everything else gets URL-encoded
901 *dest++ = hex[(unsigned char)(*src) / 16]; // left
902 *dest++ = hex[(unsigned char)(*src) % 16]; // right
908 // trim trailing space if necessary
909 if (non_space > dest_ptr && dest != non_space)
910 dest_len = non_space - dest_ptr;
912 dest_len = dest - dest_ptr;
913 str_clear(parser->link_target);
914 str_append(parser->link_target, dest_ptr, dest_len);
918 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
921 parser.space_to_underscore = false;
922 parser.link_target = str_new_from_string(in);
923 GC_WRAP_STR(parser.link_target, link_target_gc);
924 wiki_encode_link_target(&parser);
925 return string_from_str(parser.link_target);
928 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
929 // returns 0 (false) otherwise
930 bool wiki_blank(str_t *str)
934 for (char *ptr = str->ptr,
935 *end = str->ptr + str->len;
944 void wiki_rollback_failed_internal_link(parser_t *parser)
947 return; // nothing to do!
948 int scope_includes_separator = IN(SEPARATOR);
949 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
950 str_append(parser->output, link_start, sizeof(link_start) - 1);
951 if (parser->link_target->len > 0)
953 wiki_append_sanitized_link_target(parser->link_target, parser->output, false);
954 if (scope_includes_separator)
956 str_append(parser->output, separator, sizeof(separator) - 1);
957 if (parser->link_text->len > 0)
958 str_append_str(parser->output, parser->link_text);
961 parser->capture = NULL;
962 str_clear(parser->link_target);
963 str_clear(parser->link_text);
966 void wiki_rollback_failed_external_link(parser_t *parser)
968 if (!IN(EXT_LINK_START))
969 return; // nothing to do!
971 // store a couple of values before popping
972 int scope_includes_space = IN(SPACE);
973 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
974 VALUE link_rel = IN(PATH) ? Qnil : parser->external_link_rel;
975 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
977 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
978 if (parser->link_target->len > 0)
980 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, link_rel, true);
981 if (scope_includes_space)
983 str_append(parser->output, space, sizeof(space) - 1);
984 if (parser->link_text->len > 0)
985 str_append_str(parser->output, parser->link_text);
988 parser->capture = NULL;
989 str_clear(parser->link_target);
990 str_clear(parser->link_text);
993 void wiki_rollback_failed_link(parser_t *parser)
995 wiki_rollback_failed_internal_link(parser);
996 wiki_rollback_failed_external_link(parser);
999 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
1001 // process arguments
1003 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
1007 VALUE autolink = Qtrue;
1008 VALUE line_ending = rb_str_new2("\n");
1009 VALUE external_link_class = rb_str_new2("external");
1010 VALUE external_link_rel = Qnil;
1011 VALUE mailto_class = rb_str_new2("mailto");
1012 VALUE internal_link_prefix = rb_str_new2("/wiki/");
1013 VALUE img_prefix = rb_str_new2("/images/");
1014 VALUE output_style = ID2SYM(rb_intern("html"));
1015 VALUE space_to_underscore = Qtrue;
1016 VALUE minimum_fulltext_token_length = INT2NUM(3);
1017 VALUE base_heading_level = INT2NUM(0);
1019 // process options hash (override defaults)
1020 if (!NIL_P(options) && TYPE(options) == T_HASH)
1022 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1023 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1024 autolink = OVERRIDE_IF_SET(autolink);
1025 line_ending = OVERRIDE_IF_SET(line_ending);
1026 external_link_class = OVERRIDE_IF_SET(external_link_class);
1027 external_link_rel = OVERRIDE_IF_SET(external_link_rel);
1028 mailto_class = OVERRIDE_IF_SET(mailto_class);
1029 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1030 img_prefix = OVERRIDE_IF_SET(img_prefix);
1031 output_style = OVERRIDE_IF_SET(output_style);
1032 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1033 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1034 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1037 // no need to call super here; rb_call_super()
1038 rb_iv_set(self, "@autolink", autolink);
1039 rb_iv_set(self, "@line_ending", line_ending);
1040 rb_iv_set(self, "@external_link_class", external_link_class);
1041 rb_iv_set(self, "@external_link_rel", external_link_rel);
1042 rb_iv_set(self, "@mailto_class", mailto_class);
1043 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1044 rb_iv_set(self, "@img_prefix", img_prefix);
1045 rb_iv_set(self, "@output_style", output_style);
1046 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1047 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1048 rb_iv_set(self, "@base_heading_level", base_heading_level);
1052 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1054 for (int i = 0; i < 100000; i++)
1055 Wikitext_parser_parse(1, &string, self);
1059 // convert a Ruby object (:xml, :html etc) into an int output style
1060 int Wikitext_output_style(VALUE output)
1062 if (TYPE(output) == T_SYMBOL)
1064 if (SYM2ID(output) == rb_intern("xml"))
1067 return HTML_OUTPUT; // fall back to default
1070 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1072 // process arguments
1073 VALUE string, options;
1074 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1078 string = StringValue(string);
1080 // access these once per parse
1081 VALUE line_ending = rb_iv_get(self, "@line_ending");
1082 line_ending = StringValue(line_ending);
1083 VALUE link_class = rb_iv_get(self, "@external_link_class");
1084 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1085 VALUE link_rel = rb_iv_get(self, "@external_link_rel");
1086 link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
1087 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1088 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1089 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1090 int output_style = Wikitext_output_style(rb_iv_get(self, "@output_style"));
1092 // process options hash
1093 int base_indent = 0;
1094 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1095 VALUE link_proc = Qnil;
1096 if (!NIL_P(options) && TYPE(options) == T_HASH)
1098 // :indent => 0 (or more)
1099 ID has_key = rb_intern("has_key?");
1100 ID id = ID2SYM(rb_intern("indent"));
1101 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1103 VALUE indent = rb_hash_aref(options, id);
1104 if (indent == Qfalse)
1105 base_indent = -1; // indentation disabled
1108 base_indent = NUM2INT(indent);
1109 if (base_indent < 0)
1114 // :base_heading_level => 0/1/2/3/4/5/6
1115 id = ID2SYM(rb_intern("base_heading_level"));
1116 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1117 base_heading_level = NUM2INT(rb_hash_aref(options, id));
1119 // :external_link_rel => 'nofollow'
1120 id = ID2SYM(rb_intern("external_link_rel"));
1121 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1123 link_rel = rb_hash_aref(options, id);
1124 link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
1127 // :output_style => :html/:xml
1128 id = ID2SYM(rb_intern("output_style"));
1129 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1130 output_style = Wikitext_output_style(rb_hash_aref(options, id));
1132 // :link_proc => lambda { |link_target| ... }
1133 id = ID2SYM(rb_intern("link_proc"));
1134 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1135 link_proc = rb_hash_aref(options, id);
1138 // normalize, regardless of whether this came from instance variable or override
1139 if (base_heading_level < 0)
1140 base_heading_level = 0;
1141 if (base_heading_level > 6)
1142 base_heading_level = 6;
1145 char *p = RSTRING_PTR(string);
1146 long len = RSTRING_LEN(string);
1149 // set up parser struct to make passing parameters a little easier
1150 parser_t *parser = parser_new();
1151 GC_WRAP_PARSER(parser, parser_gc);
1152 parser->external_link_class = link_class;
1153 parser->external_link_rel = link_rel;
1154 parser->mailto_class = mailto_class;
1155 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1156 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1157 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1158 parser->line_ending = str_new_from_string(line_ending);
1159 parser->base_indent = base_indent;
1160 parser->base_heading_level = base_heading_level;
1161 parser->output_style = output_style;
1163 // this simple looping design leads to a single enormous function,
1164 // but it's faster than doing actual recursive descent and also secure in the face of
1165 // malicious input that seeks to overflow the stack
1166 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1167 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1168 // than a straightforward looping translator like this one anyway
1170 _token.type = NO_TOKEN;
1171 token_t *token = NULL;
1174 // note that whenever we grab a token we push it into the line buffer
1175 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1176 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1178 // check to see if we have a token hanging around from a previous iteration of this loop
1181 if (_token.type == NO_TOKEN)
1183 // first time here (haven't started scanning yet)
1185 next_token(token, NULL, p, pe);
1186 ary_push(parser->line_buffer, token->type);
1192 int type = token->type;
1194 // can't declare new variables inside a switch statement, so predeclare them here
1195 long remove_strong = -1;
1196 long remove_em = -1;
1198 // general purpose counters, flags and pointers
1202 str_t *output = NULL;
1204 str_t *token_str = &_token_str;
1206 // The following giant switch statement contains cases for all the possible token types.
1207 // In the most basic sense we are emitting the HTML that corresponds to each token,
1208 // but some tokens require context information in order to decide what to output.
1209 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1210 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1212 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1213 // - the line buffer (records tokens seen so far on the current line)
1214 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1216 // Although this is fairly complicated, there is one key simplifying factor:
1217 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1218 // scope stack (up to the current token) is valid; our translator can take this as a given.
1219 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1220 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1224 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1226 str_append(parser->output, space, sizeof(space) - 1);
1229 else if (IN(BLOCKQUOTE_START))
1231 // this kind of nesting not allowed (to avoid user confusion)
1232 wiki_pop_excess_elements(parser);
1233 wiki_start_para_if_necessary(parser);
1234 output = parser->capture ? parser->capture : parser->output;
1235 str_append(output, space, sizeof(space) - 1);
1239 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1240 ary_push(parser->line, PRE);
1241 i = ary_count(parser->line, BLOCKQUOTE);
1242 j = ary_count(parser->scope, BLOCKQUOTE);
1245 // must pop (reduce nesting level)
1246 for (i = j - i; i > 0; i--)
1247 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1252 parser->pending_crlf = false;
1253 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1254 wiki_indent(parser);
1255 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1256 ary_push(parser->scope, PRE);
1261 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1263 wiki_emit_pending_crlf_if_necessary(parser);
1264 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1266 else if (IN(BLOCKQUOTE_START))
1268 wiki_rollback_failed_link(parser); // if any
1269 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1270 wiki_append_pre_start(parser, token);
1272 else if (IN(BLOCKQUOTE))
1274 if (token->column_start == 1) // only allowed in first column
1276 wiki_rollback_failed_link(parser); // if any
1277 wiki_pop_all_from_stack(parser);
1278 wiki_append_pre_start(parser, token);
1280 else // PRE_START illegal here
1282 output = parser->capture ? parser->capture : parser->output;
1283 wiki_pop_excess_elements(parser);
1284 wiki_start_para_if_necessary(parser);
1285 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1290 wiki_rollback_failed_link(parser); // if any
1291 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1292 wiki_append_pre_start(parser, token);
1297 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1299 wiki_emit_pending_crlf_if_necessary(parser);
1300 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1305 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1308 output = parser->capture ? parser->capture : parser->output;
1309 wiki_pop_excess_elements(parser);
1310 wiki_start_para_if_necessary(parser);
1311 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1317 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1318 // no need to check for <pre>; can never appear inside it
1319 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1320 else if (IN(BLOCKQUOTE_START))
1322 // this kind of nesting not allowed (to avoid user confusion)
1323 wiki_pop_excess_elements(parser);
1324 wiki_start_para_if_necessary(parser);
1325 output = parser->capture ? parser->capture : parser->output;
1326 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1331 ary_push(parser->line, BLOCKQUOTE);
1333 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1334 i = ary_count(parser->line, BLOCKQUOTE);
1335 j = ary_count(parser->scope, BLOCKQUOTE);
1337 // given that BLOCKQUOTE tokens can be nested, peek ahead and see if there are any more which might affect the decision to push or pop
1338 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1340 ary_push(parser->line, BLOCKQUOTE);
1344 // now decide whether to push, pop or do nothing
1347 // must push (increase nesting level)
1348 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1349 for (i = i - j; i > 0; i--)
1351 wiki_indent(parser);
1352 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1353 str_append_str(parser->output, parser->line_ending);
1354 ary_push(parser->scope, BLOCKQUOTE);
1359 // must pop (reduce nesting level)
1360 for (i = j - i; i > 0; i--)
1361 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1364 // jump to top of the loop to process token we scanned during lookahead
1369 case BLOCKQUOTE_START:
1370 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1372 wiki_emit_pending_crlf_if_necessary(parser);
1373 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1375 else if (IN(BLOCKQUOTE_START))
1377 // nesting is fine here
1378 wiki_rollback_failed_link(parser); // if any
1379 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1380 wiki_indent(parser);
1381 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1382 str_append_str(parser->output, parser->line_ending);
1383 ary_push(parser->scope, BLOCKQUOTE_START);
1384 ary_push(parser->line, BLOCKQUOTE_START);
1386 else if (IN(BLOCKQUOTE))
1388 if (token->column_start == 1) // only allowed in first column
1390 wiki_rollback_failed_link(parser); // if any
1391 wiki_pop_all_from_stack(parser);
1392 wiki_indent(parser);
1393 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1394 str_append_str(parser->output, parser->line_ending);
1395 ary_push(parser->scope, BLOCKQUOTE_START);
1396 ary_push(parser->line, BLOCKQUOTE_START);
1398 else // BLOCKQUOTE_START illegal here
1400 output = parser->capture ? parser->capture : parser->output;
1401 wiki_pop_excess_elements(parser);
1402 wiki_start_para_if_necessary(parser);
1403 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1408 // would be nice to eliminate the repetition here but it's probably the clearest way
1409 wiki_rollback_failed_link(parser); // if any
1410 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1411 wiki_indent(parser);
1412 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1413 str_append_str(parser->output, parser->line_ending);
1414 ary_push(parser->scope, BLOCKQUOTE_START);
1415 ary_push(parser->line, BLOCKQUOTE_START);
1419 case BLOCKQUOTE_END:
1420 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1422 wiki_emit_pending_crlf_if_necessary(parser);
1423 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1427 if (IN(BLOCKQUOTE_START))
1428 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1431 output = parser->capture ? parser->capture : parser->output;
1432 wiki_pop_excess_elements(parser);
1433 wiki_start_para_if_necessary(parser);
1434 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1440 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1442 wiki_emit_pending_crlf_if_necessary(parser);
1443 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1447 wiki_pop_excess_elements(parser);
1448 wiki_start_para_if_necessary(parser);
1449 ary_push(parser->scope, NO_WIKI_START);
1450 ary_push(parser->line, NO_WIKI_START);
1455 if (IN(NO_WIKI_START))
1456 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1457 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1460 wiki_pop_excess_elements(parser);
1461 wiki_start_para_if_necessary(parser);
1462 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1467 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1469 wiki_emit_pending_crlf_if_necessary(parser);
1470 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1474 output = parser->capture ? parser->capture : parser->output;
1475 wiki_pop_excess_elements(parser);
1477 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1478 // otherwise, must open them
1481 j = parser->scope->count;
1482 for (j = j - 1; j >= 0; j--)
1484 int val = ary_entry(parser->scope, j);
1485 if (val == STRONG || val == STRONG_START)
1487 str_append(output, strong_end, sizeof(strong_end) - 1);
1490 else if (val == EM || val == EM_START)
1492 str_append(output, em_end, sizeof(em_end) - 1);
1497 if (remove_strong > remove_em) // must remove strong first
1499 ary_pop(parser->scope);
1501 ary_pop(parser->scope);
1502 else // there was no em to remove!, so consider this an opening em tag
1504 str_append(output, em_start, sizeof(em_start) - 1);
1505 ary_push(parser->scope, EM);
1506 ary_push(parser->line, EM);
1509 else if (remove_em > remove_strong) // must remove em first
1511 ary_pop(parser->scope);
1512 if (remove_strong > -1)
1513 ary_pop(parser->scope);
1514 else // there was no strong to remove!, so consider this an opening strong tag
1516 str_append(output, strong_start, sizeof(strong_start) - 1);
1517 ary_push(parser->scope, STRONG);
1518 ary_push(parser->line, STRONG);
1521 else // no strong or em to remove, so this must be a new opening of both
1523 wiki_start_para_if_necessary(parser);
1524 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1525 ary_push(parser->scope, STRONG);
1526 ary_push(parser->line, STRONG);
1527 ary_push(parser->scope, EM);
1528 ary_push(parser->line, EM);
1533 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1535 wiki_emit_pending_crlf_if_necessary(parser);
1536 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1540 output = parser->capture ? parser->capture : parser->output;
1541 if (IN(STRONG_START))
1542 // already in span started with <strong>, no choice but to emit this literally
1543 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1544 else if (IN(STRONG))
1545 // STRONG already seen, this is a closing tag
1546 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1549 // this is a new opening
1550 wiki_pop_excess_elements(parser);
1551 wiki_start_para_if_necessary(parser);
1552 str_append(output, strong_start, sizeof(strong_start) - 1);
1553 ary_push(parser->scope, STRONG);
1554 ary_push(parser->line, STRONG);
1560 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1562 wiki_emit_pending_crlf_if_necessary(parser);
1563 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1567 output = parser->capture ? parser->capture : parser->output;
1568 if (IN_EITHER_OF(STRONG_START, STRONG))
1569 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1572 wiki_pop_excess_elements(parser);
1573 wiki_start_para_if_necessary(parser);
1574 str_append(output, strong_start, sizeof(strong_start) - 1);
1575 ary_push(parser->scope, STRONG_START);
1576 ary_push(parser->line, STRONG_START);
1582 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1584 wiki_emit_pending_crlf_if_necessary(parser);
1585 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1589 output = parser->capture ? parser->capture : parser->output;
1590 if (IN(STRONG_START))
1591 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1594 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1595 wiki_pop_excess_elements(parser);
1596 wiki_start_para_if_necessary(parser);
1597 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1603 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1605 wiki_emit_pending_crlf_if_necessary(parser);
1606 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1610 output = parser->capture ? parser->capture : parser->output;
1612 // already in span started with <em>, no choice but to emit this literally
1613 str_append(output, literal_em, sizeof(literal_em) - 1);
1615 // EM already seen, this is a closing tag
1616 wiki_pop_from_stack_up_to(parser, output, EM, true);
1619 // this is a new opening
1620 wiki_pop_excess_elements(parser);
1621 wiki_start_para_if_necessary(parser);
1622 str_append(output, em_start, sizeof(em_start) - 1);
1623 ary_push(parser->scope, EM);
1624 ary_push(parser->line, EM);
1630 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1632 wiki_emit_pending_crlf_if_necessary(parser);
1633 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1637 output = parser->capture ? parser->capture : parser->output;
1638 if (IN_EITHER_OF(EM_START, EM))
1639 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1642 wiki_pop_excess_elements(parser);
1643 wiki_start_para_if_necessary(parser);
1644 str_append(output, em_start, sizeof(em_start) - 1);
1645 ary_push(parser->scope, EM_START);
1646 ary_push(parser->line, EM_START);
1652 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1654 wiki_emit_pending_crlf_if_necessary(parser);
1655 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1659 output = parser->capture ? parser->capture : parser->output;
1661 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1664 // no EM_START in scope, so must interpret the EM_END without any special meaning
1665 wiki_pop_excess_elements(parser);
1666 wiki_start_para_if_necessary(parser);
1667 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1673 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1675 wiki_emit_pending_crlf_if_necessary(parser);
1676 str_append(parser->output, backtick, sizeof(backtick) - 1);
1680 output = parser->capture ? parser->capture : parser->output;
1682 // already in span started with <tt>, no choice but to emit this literally
1683 str_append(output, backtick, sizeof(backtick) - 1);
1685 // TT (`) already seen, this is a closing tag
1686 wiki_pop_from_stack_up_to(parser, output, TT, true);
1689 // this is a new opening
1690 wiki_pop_excess_elements(parser);
1691 wiki_start_para_if_necessary(parser);
1692 str_append(output, code_start, sizeof(code_start) - 1);
1693 ary_push(parser->scope, TT);
1694 ary_push(parser->line, TT);
1700 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1702 wiki_emit_pending_crlf_if_necessary(parser);
1703 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1707 output = parser->capture ? parser->capture : parser->output;
1708 if (IN_EITHER_OF(TT_START, TT))
1709 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1712 wiki_pop_excess_elements(parser);
1713 wiki_start_para_if_necessary(parser);
1714 str_append(output, code_start, sizeof(code_start) - 1);
1715 ary_push(parser->scope, TT_START);
1716 ary_push(parser->line, TT_START);
1722 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1724 wiki_emit_pending_crlf_if_necessary(parser);
1725 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1729 output = parser->capture ? parser->capture : parser->output;
1731 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1734 // no TT_START in scope, so must interpret the TT_END without any special meaning
1735 wiki_pop_excess_elements(parser);
1736 wiki_start_para_if_necessary(parser);
1737 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1744 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1746 // no need to check for PRE; can never appear inside it
1747 str_append(parser->output, token->start, TOKEN_LEN(token));
1751 // count number of tokens in line and scope stacks
1752 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1753 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1754 j = parser->scope->count - bq_count;
1757 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1761 if (type == OL || type == UL)
1764 if (i - k >= 2) // already seen at least one OL or UL
1766 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1771 ary_push(parser->line, type);
1772 ary_push(parser->line, LI);
1774 // want to compare line with scope but can only do so if scope has enough items on it
1777 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1778 ary_entry(parser->scope, i + bq_count - 1) == LI)
1780 // line and scope match at this point: do nothing yet
1784 // item just pushed onto line does not match corresponding slot of scope!
1785 for (; j >= i - 2; j--)
1786 // must pop back before emitting
1787 wiki_pop_from_stack(parser, NULL);
1789 // will emit UL or OL, then LI
1793 else // line stack size now exceeds scope stack size: must increase nesting level
1794 break; // will emit UL or OL, then LI
1798 // not a OL or UL token!
1800 // must close existing LI and re-open new one
1801 wiki_pop_from_stack(parser, NULL);
1804 // item just pushed onto line does not match corresponding slot of scope!
1806 // must pop back before emitting
1807 wiki_pop_from_stack(parser, NULL);
1815 if (type == OL || type == UL)
1817 // if LI is at the top of a stack this is the start of a nested list
1818 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1820 // so we should precede it with a CRLF, and indicate that it's a nested list
1821 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1822 ary_push(parser->scope, NESTED_LIST);
1826 // this is a new list
1827 if (IN(BLOCKQUOTE_START))
1828 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1830 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1834 wiki_indent(parser);
1836 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1837 else if (type == UL)
1838 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1839 ary_push(parser->scope, type);
1840 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1842 else if (type == SPACE)
1843 // silently throw away the optional SPACE token after final list marker
1846 wiki_indent(parser);
1847 str_append(parser->output, li_start, sizeof(li_start) - 1);
1848 ary_push(parser->scope, LI);
1850 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1851 if (type == OL || type == UL)
1854 while (k++, NEXT_TOKEN(), (type = token->type))
1856 if (type == OL || type == UL)
1857 str_append(parser->output, token->start, TOKEN_LEN(token));
1858 else if (type == SPACE && k == 1)
1860 // silently throw away the optional SPACE token after final list marker
1869 // jump to top of the loop to process token we scanned during lookahead
1878 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1880 // no need to check for PRE; can never appear inside it
1881 str_append(parser->output, token->start, TOKEN_LEN(token));
1885 // pop up to but not including the last BLOCKQUOTE on the scope stack
1886 if (IN(BLOCKQUOTE_START))
1887 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1889 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1891 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1892 ary_push(parser->line, type);
1893 i = ary_count(parser->line, BLOCKQUOTE);
1894 j = ary_count(parser->scope, BLOCKQUOTE);
1896 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1899 // must pop (reduce nesting level)
1900 for (i = j - i; i > 0; i--)
1901 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1904 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1905 while (NEXT_TOKEN(), (token->type == SPACE))
1908 ary_push(parser->scope, type);
1909 wiki_indent(parser);
1911 // take base_heading_level into account
1912 type += base_heading_level;
1913 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1916 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1917 if (type == H6_START)
1918 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1919 else if (type == H5_START)
1920 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1921 else if (type == H4_START)
1922 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1923 else if (type == H3_START)
1924 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1925 else if (type == H2_START)
1926 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1927 else if (type == H1_START)
1928 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1930 // jump to top of the loop to process token we scanned during lookahead
1939 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1941 wiki_emit_pending_crlf_if_necessary(parser);
1942 str_append(parser->output, token->start, TOKEN_LEN(token));
1946 wiki_rollback_failed_external_link(parser); // if any
1947 if ((type == H6_END && !IN(H6_START)) ||
1948 (type == H5_END && !IN(H5_START)) ||
1949 (type == H4_END && !IN(H4_START)) ||
1950 (type == H3_END && !IN(H3_START)) ||
1951 (type == H2_END && !IN(H2_START)) ||
1952 (type == H1_END && !IN(H1_START)))
1954 // literal output only if not in appropriate scope (we stay silent in that case)
1955 wiki_start_para_if_necessary(parser);
1956 str_append(parser->output, token->start, TOKEN_LEN(token));
1962 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1964 wiki_emit_pending_crlf_if_necessary(parser);
1965 str_append(parser->output, token->start, TOKEN_LEN(token));
1967 else if (IN(EXT_LINK_START))
1968 // must be capturing and this must be part of the link text
1969 str_append(parser->capture, token->start, TOKEN_LEN(token));
1972 wiki_pop_excess_elements(parser);
1973 wiki_start_para_if_necessary(parser);
1974 token_str->ptr = token->start;
1975 token_str->len = TOKEN_LEN(token);
1976 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, Qnil, true);
1981 if (IN(NO_WIKI_START))
1982 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1983 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1984 str_append(parser->output, token->start, TOKEN_LEN(token));
1985 else if (IN(LINK_START))
1987 // if the URI were allowed it would have been handled already in LINK_START
1988 wiki_rollback_failed_internal_link(parser);
1989 token_str->ptr = token->start;
1990 token_str->len = TOKEN_LEN(token);
1991 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
1993 else if (IN(EXT_LINK_START))
1995 if (parser->link_target->len == 0)
1997 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1998 token_str->ptr = token->start;
1999 token_str->len = TOKEN_LEN(token);
2001 if (token->type == SPACE)
2003 ary_push(parser->scope, SPACE);
2004 str_append_str(parser->link_target, token_str);
2005 str_clear(parser->link_text);
2006 parser->capture = parser->link_text;
2007 token = NULL; // silently consume space
2011 // didn't see the space! this must be an error
2012 wiki_pop_from_stack(parser, NULL);
2013 wiki_pop_excess_elements(parser);
2014 wiki_start_para_if_necessary(parser);
2015 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2016 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2021 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2025 wiki_pop_excess_elements(parser);
2026 wiki_start_para_if_necessary(parser);
2027 token_str->ptr = token->start;
2028 token_str->len = TOKEN_LEN(token);
2029 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2034 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2036 wiki_emit_pending_crlf_if_necessary(parser);
2037 str_append(parser->output, token->start, TOKEN_LEN(token));
2039 else if (IN(EXT_LINK_START))
2041 if (parser->link_target->len == 0)
2043 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2044 token_str->ptr = token->start;
2045 token_str->len = TOKEN_LEN(token);
2047 if (token->type == SPACE)
2049 ary_push(parser->scope, PATH);
2050 ary_push(parser->scope, SPACE);
2051 str_append_str(parser->link_target, token_str);
2052 str_clear(parser->link_text);
2053 parser->capture = parser->link_text;
2054 token = NULL; // silently consume space
2058 // didn't see the space! this must be an error
2059 wiki_pop_from_stack(parser, NULL);
2060 wiki_pop_excess_elements(parser);
2061 wiki_start_para_if_necessary(parser);
2062 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2063 str_append_str(parser->output, token_str);
2068 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2072 output = parser->capture ? parser->capture : parser->output;
2073 wiki_pop_excess_elements(parser);
2074 wiki_start_para_if_necessary(parser);
2075 str_append(output, token->start, TOKEN_LEN(token));
2079 // internal links (links to other wiki articles) look like this:
2080 // [[another article]] (would point at, for example, "/wiki/another_article")
2081 // [[the other article|the link text we'll use for it]]
2082 // [[the other article | the link text we'll use for it]]
2083 // MediaWiki has strict requirements about what it will accept as a link target:
2084 // all wikitext markup is disallowed:
2085 // example [[foo ''bar'' baz]]
2086 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2087 // example [[foo <em>bar</em> baz]]
2088 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2089 // example [[foo <nowiki>''</nowiki> baz]]
2090 // renders [[foo '' baz]] (ie. not a link)
2091 // example [[foo <bar> baz]]
2092 // renders [[foo <bar> baz]] (ie. not a link)
2093 // HTML entities and non-ASCII, however, make it through:
2094 // example [[foo €]]
2095 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2096 // example [[foo €]]
2097 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2098 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2099 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2100 // everything else will be rejected
2102 output = parser->capture ? parser->capture : parser->output;
2103 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2105 wiki_emit_pending_crlf_if_necessary(parser);
2106 str_append(output, link_start, sizeof(link_start) - 1);
2108 else if (IN(EXT_LINK_START))
2109 // already in external link scope! (and in fact, must be capturing link_text right now)
2110 str_append(output, link_start, sizeof(link_start) - 1);
2111 else if (IN(LINK_START))
2113 // already in internal link scope! this is a syntax error
2114 wiki_rollback_failed_internal_link(parser);
2115 str_append(parser->output, link_start, sizeof(link_start) - 1);
2117 else if (IN(SEPARATOR))
2119 // scanning internal link text
2121 else // not in internal link scope yet
2123 // will either emit a link, or the rollback of a failed link, so start the para now
2124 wiki_pop_excess_elements(parser);
2125 wiki_start_para_if_necessary(parser);
2126 ary_push(parser->scope, LINK_START);
2128 // look ahead and try to gobble up link target
2129 while (NEXT_TOKEN(), (type = token->type))
2131 if (type == SPACE ||
2132 type == SPECIAL_URI_CHARS ||
2134 type == PRINTABLE ||
2138 type == QUOT_ENTITY ||
2140 type == AMP_ENTITY ||
2141 type == IMG_START ||
2143 type == LEFT_CURLY ||
2144 type == RIGHT_CURLY)
2146 // accumulate these tokens into link_target
2147 if (parser->link_target->len == 0)
2149 str_clear(parser->link_target);
2150 parser->capture = parser->link_target;
2152 if (type == QUOT_ENTITY)
2153 // don't insert the entity, insert the literal quote
2154 str_append(parser->link_target, quote, sizeof(quote) - 1);
2155 else if (type == AMP_ENTITY)
2156 // don't insert the entity, insert the literal ampersand
2157 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2159 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2161 else if (type == LINK_END)
2163 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2164 wiki_rollback_failed_internal_link(parser);
2165 break; // jump back to top of loop (will handle this in LINK_END case below)
2167 else if (type == SEPARATOR)
2169 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2170 wiki_rollback_failed_internal_link(parser);
2173 ary_push(parser->scope, SEPARATOR);
2174 str_clear(parser->link_text);
2175 parser->capture = parser->link_text;
2180 else // unexpected token (syntax error)
2182 wiki_rollback_failed_internal_link(parser);
2183 break; // jump back to top of loop to handle unexpected token
2187 // jump to top of the loop to process token we scanned during lookahead (if any)
2193 output = parser->capture ? parser->capture : parser->output;
2194 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2196 wiki_emit_pending_crlf_if_necessary(parser);
2197 str_append(output, link_end, sizeof(link_end) - 1);
2199 else if (IN(EXT_LINK_START))
2200 // already in external link scope! (and in fact, must be capturing link_text right now)
2201 str_append(output, link_end, sizeof(link_end) - 1);
2202 else if (IN(LINK_START)) // in internal link scope!
2204 if (wiki_blank(parser->link_target))
2206 // special case for inputs like "[[ ]]"
2207 wiki_rollback_failed_internal_link(parser);
2208 str_append(parser->output, link_end, sizeof(link_end) - 1);
2211 if (parser->link_text->len == 0 ||
2212 wiki_blank(parser->link_text))
2214 // use link target as link text
2215 str_clear(parser->link_text);
2216 wiki_append_sanitized_link_target(parser->link_target, parser->link_text, true);
2219 wiki_trim_link_text(parser);
2221 // perform "redlink" check before manipulating link_target
2222 if (NIL_P(link_proc))
2226 j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
2229 VALUE l = j; // can't cast inside StringValue macro
2233 wiki_encode_link_target(parser);
2234 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2235 parser->capture = NULL;
2236 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, Qnil, false);
2237 str_clear(parser->link_target);
2238 str_clear(parser->link_text);
2240 else // wasn't in internal link scope
2242 wiki_pop_excess_elements(parser);
2243 wiki_start_para_if_necessary(parser);
2244 str_append(output, link_end, sizeof(link_end) - 1);
2248 // external links look like this:
2249 // [http://google.com/ the link text]
2250 // [/other/page/on/site see this page]
2251 // strings in square brackets which don't match this syntax get passed through literally; eg:
2252 // he was very angery [sic] about the turn of events
2253 case EXT_LINK_START:
2254 output = parser->capture ? parser->capture : parser->output;
2255 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2257 wiki_emit_pending_crlf_if_necessary(parser);
2258 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2260 else if (IN(EXT_LINK_START))
2261 // already in external link scope! (and in fact, must be capturing link_text right now)
2262 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2263 else if (IN(LINK_START))
2265 // already in internal link scope!
2266 if (parser->link_target->len == 0 || !IN(SPACE))
2267 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2268 else // link target has already been scanned
2269 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2271 else // not in external link scope yet
2273 // will either emit a link, or the rollback of a failed link, so start the para now
2274 wiki_pop_excess_elements(parser);
2275 wiki_start_para_if_necessary(parser);
2277 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2279 if (token->type == URI || token->type == PATH)
2280 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2282 // only get here if there was a syntax error (missing URI)
2283 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2284 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2289 output = parser->capture ? parser->capture : parser->output;
2290 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2292 wiki_emit_pending_crlf_if_necessary(parser);
2293 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2295 else if (IN(EXT_LINK_START))
2297 if (parser->link_text->len == 0)
2298 // syntax error: external link with no link text
2299 wiki_rollback_failed_external_link(parser);
2303 j = IN(PATH) ? Qnil : parser->external_link_class;
2304 k = IN(PATH) ? Qnil : parser->external_link_rel;
2305 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2306 parser->capture = NULL;
2307 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, k, false);
2309 str_clear(parser->link_target);
2310 str_clear(parser->link_text);
2314 wiki_pop_excess_elements(parser);
2315 wiki_start_para_if_necessary(parser);
2316 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2321 output = parser->capture ? parser->capture : parser->output;
2322 wiki_pop_excess_elements(parser);
2323 wiki_start_para_if_necessary(parser);
2324 str_append(output, separator, sizeof(separator) - 1);
2328 output = parser->capture ? parser->capture : parser->output;
2329 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2331 wiki_emit_pending_crlf_if_necessary(parser);
2332 str_append(output, token->start, TOKEN_LEN(token));
2336 // peek ahead to see next token
2337 char *token_ptr = token->start;
2338 int token_len = TOKEN_LEN(token);
2341 if ((type == H6_END && IN(H6_START)) ||
2342 (type == H5_END && IN(H5_START)) ||
2343 (type == H4_END && IN(H4_START)) ||
2344 (type == H3_END && IN(H3_START)) ||
2345 (type == H2_END && IN(H2_START)) ||
2346 (type == H1_END && IN(H1_START)))
2348 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2353 wiki_pop_excess_elements(parser);
2354 wiki_start_para_if_necessary(parser);
2355 str_append(output, token_ptr, token_len);
2358 // jump to top of the loop to process token we scanned during lookahead
2366 case DECIMAL_ENTITY:
2367 // pass these through unaltered as they are case sensitive
2368 output = parser->capture ? parser->capture : parser->output;
2369 wiki_pop_excess_elements(parser);
2370 wiki_start_para_if_necessary(parser);
2371 str_append(output, token->start, TOKEN_LEN(token));
2375 // normalize hex entities (downcase them)
2376 output = parser->capture ? parser->capture : parser->output;
2377 wiki_pop_excess_elements(parser);
2378 wiki_start_para_if_necessary(parser);
2379 str_append(output, token->start, TOKEN_LEN(token));
2380 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2384 output = parser->capture ? parser->capture : parser->output;
2385 wiki_pop_excess_elements(parser);
2386 wiki_start_para_if_necessary(parser);
2387 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2391 output = parser->capture ? parser->capture : parser->output;
2392 wiki_pop_excess_elements(parser);
2393 wiki_start_para_if_necessary(parser);
2394 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2398 output = parser->capture ? parser->capture : parser->output;
2399 wiki_pop_excess_elements(parser);
2400 wiki_start_para_if_necessary(parser);
2401 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2405 output = parser->capture ? parser->capture : parser->output;
2406 wiki_pop_excess_elements(parser);
2407 wiki_start_para_if_necessary(parser);
2408 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2412 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2414 wiki_emit_pending_crlf_if_necessary(parser);
2415 str_append(parser->output, token->start, TOKEN_LEN(token));
2417 else if (parser->capture)
2418 str_append(parser->capture, token->start, TOKEN_LEN(token));
2421 // not currently capturing: will be emitting something on success or failure, so get ready
2422 wiki_pop_excess_elements(parser);
2423 wiki_start_para_if_necessary(parser);
2425 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2426 // will cheat here and abuse the link_target capture buffer to accumulate text
2427 while (NEXT_TOKEN(), (type = token->type))
2429 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2430 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2431 else if (type == IMG_END && parser->link_target->len > 0)
2434 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2438 else // unexpected token or zero-length target (syntax error)
2441 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2442 if (parser->link_target->len > 0)
2443 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2448 // jump to top of the loop to process token we scanned during lookahead
2449 str_clear(parser->link_target);
2455 i = parser->pending_crlf;
2456 parser->pending_crlf = false;
2457 wiki_rollback_failed_link(parser); // if any
2458 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2460 ary_clear(parser->line_buffer);
2461 str_append_str(parser->output, parser->line_ending);
2466 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2467 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2468 // don't emit in this case
2469 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2472 if (ary_entry(parser->line_buffer, -2) == PRE)
2474 // only thing on line is the PRE: emit pending line ending (if we had one)
2476 str_append_str(parser->output, parser->line_ending);
2479 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2480 ary_clear(parser->line);
2481 ary_clear(parser->line_buffer);
2483 // peek ahead to see if this is definitely the end of the PRE block
2486 if (type != BLOCKQUOTE && type != PRE)
2487 // this is definitely the end of the block, so don't emit
2488 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2490 // potentially will emit
2491 parser->pending_crlf = true;
2493 continue; // jump back to top of loop to handle token grabbed via lookahead
2498 parser->pending_crlf = true;
2500 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2501 // as a side effect, this handles any open span-level elements and unclosed blocks
2502 // (with special handling for P blocks and LI elements)
2503 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2504 for (j = parser->scope->count; j > i; j--)
2506 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2508 parser->pending_crlf = false;
2512 // special handling on last iteration through the loop if the top item on the scope is a P block
2513 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2515 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2516 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2517 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2518 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2519 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2521 parser->pending_crlf = false;
2523 // not a paragraph break!
2526 wiki_pop_from_stack(parser, NULL);
2530 // delete the entire contents of the line scope stack and buffer
2531 ary_clear(parser->line);
2532 ary_clear(parser->line_buffer);
2535 case SPECIAL_URI_CHARS:
2541 output = parser->capture ? parser->capture : parser->output;
2542 wiki_pop_excess_elements(parser);
2543 wiki_start_para_if_necessary(parser);
2544 str_append(output, token->start, TOKEN_LEN(token));
2548 output = parser->capture ? parser->capture : parser->output;
2549 wiki_pop_excess_elements(parser);
2550 wiki_start_para_if_necessary(parser);
2551 wiki_append_entity_from_utf32_char(output, token->code_point);
2555 // special case for input like " foo\n " (see pre_spec.rb)
2557 ary_entry(parser->line_buffer, -2) == PRE &&
2558 parser->pending_crlf)
2559 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2561 // close any open scopes on hitting EOF
2562 wiki_rollback_failed_link(parser); // if any
2563 wiki_pop_all_from_stack(parser);
2564 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2570 // reset current token; forcing lexer to return another token at the top of the loop
2574 // nasty hack to avoid re-allocating our return value
2575 str_append(parser->output, null_str, 1); // null-terminate
2576 len = parser->output->len - 1; // don't count null termination
2578 #if defined(RUBY_1_9_x)
2579 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2580 free(RSTRING_PTR(out));
2581 RSTRING(out)->as.heap.aux.capa = len;
2582 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2583 RSTRING(out)->as.heap.len = len;
2584 #elif defined(RUBY_1_8_x)
2585 VALUE out = rb_str_new2("");
2586 free(RSTRING_PTR(out));
2587 RSTRING(out)->len = len;
2588 RSTRING(out)->aux.capa = len;
2589 RSTRING(out)->ptr = parser->output->ptr;
2591 #error unsupported RUBY_VERSION
2593 parser->output->ptr = NULL; // don't double-free