1 // Copyright 2007-2009 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)
36 // poor man's object orientation in C:
37 // instead of passing around multiple parameters between functions in the parser
38 // we pack everything into a struct and pass around only a pointer to that
41 str_t *capture; // capturing to link_target, link_text, or NULL (direct to output, not capturing)
42 str_t *output; // for accumulating output to be returned
43 str_t *link_target; // short term "memory" for parsing links
44 str_t *link_text; // short term "memory" for parsing links
46 str_t *tabulation; // caching buffer for emitting indentation
47 ary_t *scope; // stack for tracking scope
48 ary_t *line; // stack for tracking scope as implied by current line
49 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
50 VALUE external_link_class; // CSS class applied to external links
51 VALUE mailto_class; // CSS class applied to email (mailto) links
52 VALUE img_prefix; // path prepended when emitting img tags
53 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
54 int current_indent; // fluctuates according to currently nested structures
55 int base_heading_level;
58 bool space_to_underscore;
61 const char null_str[] = { 0 };
62 const char escaped_no_wiki_start[] = "<nowiki>";
63 const char escaped_no_wiki_end[] = "</nowiki>";
64 const char literal_strong_em[] = "'''''";
65 const char literal_strong[] = "'''";
66 const char literal_em[] = "''";
67 const char escaped_em_start[] = "<em>";
68 const char escaped_em_end[] = "</em>";
69 const char escaped_strong_start[] = "<strong>";
70 const char escaped_strong_end[] = "</strong>";
71 const char escaped_tt_start[] = "<tt>";
72 const char escaped_tt_end[] = "</tt>";
73 const char pre_start[] = "<pre>";
74 const char pre_end[] = "</pre>";
75 const char escaped_pre_start[] = "<pre>";
76 const char escaped_pre_end[] = "</pre>";
77 const char blockquote_start[] = "<blockquote>";
78 const char blockquote_end[] = "</blockquote>";
79 const char escaped_blockquote_start[] = "<blockquote>";
80 const char escaped_blockquote_end[] = "</blockquote>";
81 const char strong_em_start[] = "<strong><em>";
82 const char strong_start[] = "<strong>";
83 const char strong_end[] = "</strong>";
84 const char em_start[] = "<em>";
85 const char em_end[] = "</em>";
86 const char tt_start[] = "<tt>";
87 const char tt_end[] = "</tt>";
88 const char ol_start[] = "<ol>";
89 const char ol_end[] = "</ol>";
90 const char ul_start[] = "<ul>";
91 const char ul_end[] = "</ul>";
92 const char li_start[] = "<li>";
93 const char li_end[] = "</li>";
94 const char h6_start[] = "<h6>";
95 const char h6_end[] = "</h6>";
96 const char h5_start[] = "<h5>";
97 const char h5_end[] = "</h5>";
98 const char h4_start[] = "<h4>";
99 const char h4_end[] = "</h4>";
100 const char h3_start[] = "<h3>";
101 const char h3_end[] = "</h3>";
102 const char h2_start[] = "<h2>";
103 const char h2_end[] = "</h2>";
104 const char h1_start[] = "<h1>";
105 const char h1_end[] = "</h1>";
106 const char p_start[] = "<p>";
107 const char p_end[] = "</p>";
108 const char space[] = " ";
109 const char a_start[] = "<a href=\"";
110 const char a_class[] = "\" class=\"";
111 const char a_start_close[] = "\">";
112 const char a_end[] = "</a>";
113 const char link_start[] = "[[";
114 const char link_end[] = "]]";
115 const char separator[] = "|";
116 const char ext_link_start[] = "[";
117 const char backtick[] = "`";
118 const char quote[] = "\"";
119 const char ampersand[] = "&";
120 const char quot_entity[] = """;
121 const char amp_entity[] = "&";
122 const char lt_entity[] = "<";
123 const char gt_entity[] = ">";
124 const char escaped_blockquote[] = "> ";
125 const char ext_link_end[] = "]";
126 const char literal_img_start[] = "{{";
127 const char img_start[] = "<img src=\"";
128 const char img_end[] = "\" />";
129 const char img_alt[] = "\" alt=\"";
130 const char pre_class_start[] = "<pre class=\"";
131 const char pre_class_end[] = "-syntax\">";
133 // Mark the parser struct designated by ptr as a participant in Ruby's
134 // mark-and-sweep garbage collection scheme. A variable named name is placed on
135 // the C stack to prevent the structure from being prematurely collected.
136 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
138 parser_t *parser_new(void)
140 parser_t *parser = ALLOC_N(parser_t, 1);
141 parser->capture = NULL; // not a real instance, pointer to other member's instance
142 parser->output = str_new();
143 parser->link_target = str_new();
144 parser->link_text = str_new();
145 parser->line_ending = NULL; // caller should set up
146 parser->tabulation = str_new();
147 parser->scope = ary_new();
148 parser->line = ary_new();
149 parser->line_buffer = ary_new();
150 parser->external_link_class = Qnil; // caller should set up
151 parser->mailto_class = Qnil; // caller should set up
152 parser->img_prefix = Qnil; // caller should set up
153 parser->base_indent = 0;
154 parser->current_indent = 0;
155 parser->base_heading_level = 0;
156 parser->pending_crlf = false;
157 parser->autolink = true;
158 parser->space_to_underscore = true;
162 void parser_free(parser_t *parser)
164 // we don't free parser->capture; it's just a redundant pointer
165 if (parser->output) str_free(parser->output);
166 if (parser->link_target) str_free(parser->link_target);
167 if (parser->link_text) str_free(parser->link_text);
168 if (parser->line_ending) str_free(parser->line_ending);
169 if (parser->tabulation) str_free(parser->tabulation);
170 if (parser->scope) ary_free(parser->scope);
171 if (parser->line) ary_free(parser->line);
172 if (parser->line_buffer) ary_free(parser->line_buffer);
176 // for testing and debugging only
177 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
181 string = StringValue(string);
182 VALUE tokens = rb_ary_new();
183 char *p = RSTRING_PTR(string);
184 long len = RSTRING_LEN(string);
187 next_token(&token, NULL, p, pe);
188 rb_ary_push(tokens, wiki_token(&token));
189 while (token.type != END_OF_FILE)
191 next_token(&token, &token, NULL, pe);
192 rb_ary_push(tokens, wiki_token(&token));
197 // for benchmarking raw tokenization speed only
198 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
202 string = StringValue(string);
203 char *p = RSTRING_PTR(string);
204 long len = RSTRING_LEN(string);
207 next_token(&token, NULL, p, pe);
208 while (token.type != END_OF_FILE)
209 next_token(&token, &token, NULL, pe);
213 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
216 VALUE string, options;
217 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
221 string = StringValue(string);
222 VALUE tokens = rb_ary_new();
224 // check instance variables
225 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
227 // process options hash (can override instance variables)
228 if (!NIL_P(options) && TYPE(options) == T_HASH)
230 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
231 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
233 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
238 char *p = RSTRING_PTR(string);
239 long len = RSTRING_LEN(string);
242 token_t *_token = &token;
243 next_token(&token, NULL, p, pe);
244 while (token.type != END_OF_FILE)
251 if (TOKEN_LEN(_token) >= min_len)
252 rb_ary_push(tokens, TOKEN_TEXT(_token));
255 // ignore everything else
258 next_token(&token, &token, NULL, pe);
263 // we downcase "in place", overwriting the original contents of the buffer
264 void wiki_downcase_bang(char *ptr, long len)
266 for (long i = 0; i < len; i++)
268 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
273 // prepare hyperlink and append it to parser->output
274 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
275 // or merely the literal link target
276 // if link_text is Qnil, the link_target is re-used for the link text
277 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, bool check_autolink)
279 if (check_autolink && !parser->autolink)
280 str_append_str(parser->output, link_target);
283 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
284 if (!NIL_P(link_prefix))
285 str_append_string(parser->output, link_prefix);
286 str_append_str(parser->output, link_target);
288 // special handling for mailto URIs
289 const char *mailto = "mailto:";
290 if (NIL_P(link_prefix) &&
291 link_target->len >= (long)sizeof(mailto) &&
292 strncmp(mailto, link_target->ptr, sizeof(mailto)) == 0)
293 link_class = parser->mailto_class; // use mailto_class from parser
294 if (link_class != Qnil)
296 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
297 str_append_string(parser->output, link_class);
299 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
300 if (!link_text || link_text->len == 0) // re-use link_target
301 str_append_str(parser->output, link_target);
303 str_append_str(parser->output, link_text);
304 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
308 void wiki_append_img(parser_t *parser, char *token_ptr, int token_len)
310 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
311 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
312 str_append_string(parser->output, parser->img_prefix);
313 str_append(parser->output, token_ptr, token_len);
314 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
315 str_append(parser->output, token_ptr, token_len);
316 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
319 // will emit indentation only if we are about to emit any of:
320 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
321 // each time we enter one of those spans must ++ the indentation level
322 void wiki_indent(parser_t *parser)
324 if (parser->base_indent == -1) // indentation disabled
326 int space_count = parser->current_indent + parser->base_indent;
329 char *old_end, *new_end;
330 if (parser->tabulation->len < space_count)
331 str_grow(parser->tabulation, space_count); // reallocates if necessary
332 old_end = parser->tabulation->ptr + parser->tabulation->len;
333 new_end = parser->tabulation->ptr + space_count;
334 while (old_end < new_end)
336 if (space_count > parser->tabulation->len)
337 parser->tabulation->len = space_count;
338 str_append(parser->output, parser->tabulation->ptr, space_count);
340 parser->current_indent += 2;
343 void wiki_append_pre_start(parser_t *parser, token_t *token)
346 if ((size_t)TOKEN_LEN(token) > sizeof(pre_start) - 1)
348 str_append(parser->output, pre_class_start, sizeof(pre_class_start) - 1); // <pre class="
349 str_append(parser->output, token->start + 11, TOKEN_LEN(token) - 13); // (the "lang" substring)
350 str_append(parser->output, pre_class_end, sizeof(pre_class_end) - 1); // -syntax">
353 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
354 ary_push(parser->scope, PRE_START);
355 ary_push(parser->line, PRE_START);
358 void wiki_dedent(parser_t *parser, bool emit)
360 if (parser->base_indent == -1) // indentation disabled
362 parser->current_indent -= 2;
365 int space_count = parser->current_indent + parser->base_indent;
367 str_append(parser->output, parser->tabulation->ptr, space_count);
370 // Pops a single item off the parser's scope stack.
371 // A corresponding closing tag is written to the target string.
372 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
373 void wiki_pop_from_stack(parser_t *parser, str_t *target)
375 int top = ary_entry(parser->scope, -1);
379 target = parser->output;
381 // for headings, take base_heading_level into account
382 if (top >= H1_START && top <= H6_START)
384 top += parser->base_heading_level;
385 // no need to check for underflow (base_heading_level is never negative)
394 str_append(target, pre_end, sizeof(pre_end) - 1);
395 str_append_str(target, parser->line_ending);
396 wiki_dedent(parser, false);
400 case BLOCKQUOTE_START:
401 wiki_dedent(parser, true);
402 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
403 str_append_str(target, parser->line_ending);
407 // not a real HTML tag; so nothing to pop
412 str_append(target, strong_end, sizeof(strong_end) - 1);
417 str_append(target, em_end, sizeof(em_end) - 1);
422 str_append(target, tt_end, sizeof(tt_end) - 1);
426 wiki_dedent(parser, true);
427 str_append(target, ol_end, sizeof(ol_end) - 1);
428 str_append_str(target, parser->line_ending);
432 wiki_dedent(parser, true);
433 str_append(target, ul_end, sizeof(ul_end) - 1);
434 str_append_str(target, parser->line_ending);
438 // next token to pop will be a LI
439 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
440 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
441 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
442 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
443 wiki_dedent(parser, true); // we really only want to emit the spaces
444 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
448 str_append(target, li_end, sizeof(li_end) - 1);
449 str_append_str(target, parser->line_ending);
450 wiki_dedent(parser, false);
454 str_append(target, h6_end, sizeof(h6_end) - 1);
455 str_append_str(target, parser->line_ending);
456 wiki_dedent(parser, false);
460 str_append(target, h5_end, sizeof(h5_end) - 1);
461 str_append_str(target, parser->line_ending);
462 wiki_dedent(parser, false);
466 str_append(target, h4_end, sizeof(h4_end) - 1);
467 str_append_str(target, parser->line_ending);
468 wiki_dedent(parser, false);
472 str_append(target, h3_end, sizeof(h3_end) - 1);
473 str_append_str(target, parser->line_ending);
474 wiki_dedent(parser, false);
478 str_append(target, h2_end, sizeof(h2_end) - 1);
479 str_append_str(target, parser->line_ending);
480 wiki_dedent(parser, false);
484 str_append(target, h1_end, sizeof(h1_end) - 1);
485 str_append_str(target, parser->line_ending);
486 wiki_dedent(parser, false);
490 // not an HTML tag; so nothing to emit
494 // not an HTML tag; so nothing to emit
498 // not an HTML tag; so nothing to emit
502 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
506 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
510 str_append(target, p_end, sizeof(p_end) - 1);
511 str_append_str(target, parser->line_ending);
512 wiki_dedent(parser, false);
520 // should probably raise an exception here
523 ary_pop(parser->scope);
526 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
527 // If including is true then the item itself is also popped.
528 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
529 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
531 int continue_looping = 1;
534 int top = ary_entry(parser->scope, -1);
541 continue_looping = 0;
543 wiki_pop_from_stack(parser, target);
544 } while (continue_looping);
547 void wiki_pop_all_from_stack(parser_t *parser)
549 for (int i = 0, max = parser->scope->count; i < max; i++)
550 wiki_pop_from_stack(parser, NULL);
553 void wiki_start_para_if_necessary(parser_t *parser)
558 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
559 if (parser->scope->count == 0 ||
560 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
561 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
564 str_append(parser->output, p_start, sizeof(p_start) - 1);
565 ary_push(parser->scope, P);
566 ary_push(parser->line, P);
568 else if (parser->pending_crlf)
571 // already in a paragraph block; convert pending CRLF into a space
572 str_append(parser->output, space, sizeof(space) - 1);
574 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
575 str_append_str(parser->output, parser->line_ending);
577 parser->pending_crlf = false;
580 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
582 if (parser->pending_crlf)
584 str_append_str(parser->output, parser->line_ending);
585 parser->pending_crlf = false;
589 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
590 // For example, given input like:
595 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
596 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
601 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
602 // but not on the line scope:
607 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
608 // on the line scope.
609 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
610 // entering the for loop.
611 void wiki_pop_excess_elements(parser_t *parser)
615 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
617 // special case for last item on scope
620 // don't auto-pop P if it is only item on scope
621 if (ary_entry(parser->scope, -1) == P)
623 // add P to the line scope to prevent us entering the loop at all next time around
624 ary_push(parser->line, P);
628 wiki_pop_from_stack(parser, NULL);
632 // Convert a single UTF-8 codepoint to UTF-32
634 // Expects an input buffer, src, containing a UTF-8 encoded character (which
635 // may be multi-byte). The end of the input buffer, end, is also passed in to
636 // allow the detection of invalidly truncated codepoints. The number of bytes
637 // in the UTF-8 character (between 1 and 4) is returned by reference in
640 // Raises a RangeError if the supplied character is invalid UTF-8.
641 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
644 if ((unsigned char)src[0] <= 0x7f)
650 else if ((src[0] & 0xe0) == 0xc0)
652 // byte starts with 110..... : this should be a two-byte sequence
655 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
656 else if (((unsigned char)src[0] == 0xc0) ||
657 ((unsigned char)src[0] == 0xc1))
658 // overlong encoding: lead byte of 110..... but code point <= 127
659 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
660 else if ((src[1] & 0xc0) != 0x80 )
661 // should have second byte starting with 10......
662 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
665 ((uint32_t)(src[0] & 0x1f)) << 6 |
669 else if ((src[0] & 0xf0) == 0xe0)
671 // byte starts with 1110.... : this should be a three-byte sequence
673 // missing second or third byte
674 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
675 else if (((src[1] & 0xc0) != 0x80 ) ||
676 ((src[2] & 0xc0) != 0x80 ))
677 // should have second and third bytes starting with 10......
678 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
681 ((uint32_t)(src[0] & 0x0f)) << 12 |
682 ((uint32_t)(src[1] & 0x3f)) << 6 |
686 else if ((src[0] & 0xf8) == 0xf0)
688 // bytes starts with 11110... : this should be a four-byte sequence
690 // missing second, third, or fourth byte
691 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
692 else if ((unsigned char)src[0] >= 0xf5 &&
693 (unsigned char)src[0] <= 0xf7)
694 // disallowed by RFC 3629 (codepoints above 0x10ffff)
695 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
696 else if (((src[1] & 0xc0) != 0x80 ) ||
697 ((src[2] & 0xc0) != 0x80 ) ||
698 ((src[3] & 0xc0) != 0x80 ))
699 // should have second and third bytes starting with 10......
700 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
703 ((uint32_t)(src[0] & 0x07)) << 18 |
704 ((uint32_t)(src[1] & 0x3f)) << 12 |
705 ((uint32_t)(src[1] & 0x3f)) << 6 |
710 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
714 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
716 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
717 char scratch = (character & 0xf000) >> 12;
718 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
719 scratch = (character & 0x0f00) >> 8;
720 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
721 scratch = (character & 0x00f0) >> 4;
722 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
723 scratch = character & 0x000f;
724 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
725 str_append(output, hex_string, sizeof(hex_string));
728 // trim parser->link_text in place
729 void wiki_trim_link_text(parser_t *parser)
731 char *src = parser->link_text->ptr;
732 char *start = src; // remember this so we can check if we're at the start
734 char *non_space = src; // remember last non-space character output
735 char *end = src + parser->link_text->len;
747 if (left != start || non_space + 1 != end)
749 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
750 parser->link_text->len = (non_space + 1) - left;
751 memmove(parser->link_text->ptr, left, parser->link_text->len);
755 // - non-printable (non-ASCII) characters converted to numeric entities
756 // - QUOT and AMP characters converted to named entities
757 // - if trim is true, leading and trailing whitespace trimmed
758 // - if trim is false, there is no special treatment of spaces
759 void wiki_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
761 char *src = parser->link_target->ptr;
762 char *start = src; // remember this so we can check if we're at the start
763 char *non_space = output->ptr + output->len; // remember last non-space character output
764 char *end = src + parser->link_target->len;
767 // need at most 8 bytes to display each input character (�)
768 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
770 char *old_ptr = output->ptr;
771 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
772 if (old_ptr != output->ptr) // may have moved
773 non_space += output->ptr - old_ptr;
778 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
779 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
781 else if (*src == '&')
783 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
784 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
786 else if (*src == '<' || *src == '>')
787 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
788 else if (*src == ' ' && src == start && trim)
789 start++; // we eat leading space
790 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
792 *(output->ptr + output->len) = *src;
795 else // all others: must convert to entities
798 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
800 non_space = output->ptr + output->len;
804 non_space = output->ptr + output->len;
808 // trim trailing space if necessary
809 if (trim && output->ptr + output->len != non_space)
810 output->len -= (output->ptr + output->len) - non_space;
813 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
816 parser.link_target = str_new_from_string(string);
817 GC_WRAP_STR(parser.link_target, link_target_gc);
818 str_t *output = str_new();
819 GC_WRAP_STR(output, output_gc);
820 wiki_append_sanitized_link_target(&parser, output, true);
821 return string_from_str(output);
824 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
826 // Leading and trailing whitespace trimmed. Spaces are converted to
827 // underscores if the parser space_to_underscore member is true.
828 static void wiki_encode_link_target(parser_t *parser)
830 char *src = parser->link_target->ptr;
831 char *start = src; // remember this so we can check if we're at the start
832 long len = parser->link_target->len;
835 char *end = src + len;
836 long dest_len = len * 2;
837 char *dest = ALLOC_N(char, dest_len);
838 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
839 char *non_space = dest; // remember last non-space character output
840 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
841 for (; src < end; src++)
843 // worst case: a single character may grow to 3 characters once encoded
844 if ((dest + 3) > (dest_ptr + dest_len))
846 // outgrowing buffer, must reallocate
847 char *old_dest = dest;
848 char *old_dest_ptr = dest_ptr;
850 dest = realloc(dest_ptr, dest_len);
853 // would have used reallocf, but this has to run on Linux too, not just Darwin
855 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
858 dest = dest_ptr + (old_dest - old_dest_ptr);
859 non_space = dest_ptr + (non_space - old_dest_ptr);
862 // pass through unreserved characters
863 if ((*src >= 'a' && *src <= 'z') ||
864 (*src >= 'A' && *src <= 'Z') ||
865 (*src >= '0' && *src <= '9') ||
874 else if (*src == ' ' && src == start)
875 start++; // we eat leading space
876 else if (*src == ' ' && parser->space_to_underscore)
878 else // everything else gets URL-encoded
881 *dest++ = hex[(unsigned char)(*src) / 16]; // left
882 *dest++ = hex[(unsigned char)(*src) % 16]; // right
888 // trim trailing space if necessary
889 if (non_space > dest_ptr && dest != non_space)
890 dest_len = non_space - dest_ptr;
892 dest_len = dest - dest_ptr;
893 str_clear(parser->link_target);
894 str_append(parser->link_target, dest_ptr, dest_len);
898 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
901 parser.space_to_underscore = false;
902 parser.link_target = str_new_from_string(in);
903 GC_WRAP_STR(parser.link_target, link_target_gc);
904 wiki_encode_link_target(&parser);
905 return string_from_str(parser.link_target);
908 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
909 // returns 0 (false) otherwise
910 bool wiki_blank(str_t *str)
914 for (char *ptr = str->ptr,
915 *end = str->ptr + str->len;
924 void wiki_rollback_failed_internal_link(parser_t *parser)
927 return; // nothing to do!
928 int scope_includes_separator = IN(SEPARATOR);
929 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
930 str_append(parser->output, link_start, sizeof(link_start) - 1);
931 if (parser->link_target->len > 0)
933 wiki_append_sanitized_link_target(parser, parser->output, false);
934 if (scope_includes_separator)
936 str_append(parser->output, separator, sizeof(separator) - 1);
937 if (parser->link_text->len > 0)
938 str_append_str(parser->output, parser->link_text);
941 parser->capture = NULL;
942 str_clear(parser->link_target);
943 str_clear(parser->link_text);
946 void wiki_rollback_failed_external_link(parser_t *parser)
948 if (!IN(EXT_LINK_START))
949 return; // nothing to do!
951 // store a couple of values before popping
952 int scope_includes_space = IN(SPACE);
953 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
954 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
956 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
957 if (parser->link_target->len > 0)
959 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
960 if (scope_includes_space)
962 str_append(parser->output, space, sizeof(space) - 1);
963 if (parser->link_text->len > 0)
964 str_append_str(parser->output, parser->link_text);
967 parser->capture = NULL;
968 str_clear(parser->link_target);
969 str_clear(parser->link_text);
972 void wiki_rollback_failed_link(parser_t *parser)
974 wiki_rollback_failed_internal_link(parser);
975 wiki_rollback_failed_external_link(parser);
978 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
982 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
986 VALUE autolink = Qtrue;
987 VALUE line_ending = rb_str_new2("\n");
988 VALUE external_link_class = rb_str_new2("external");
989 VALUE mailto_class = rb_str_new2("mailto");
990 VALUE internal_link_prefix = rb_str_new2("/wiki/");
991 VALUE img_prefix = rb_str_new2("/images/");
992 VALUE space_to_underscore = Qtrue;
993 VALUE minimum_fulltext_token_length = INT2NUM(3);
994 VALUE base_heading_level = INT2NUM(0);
996 // process options hash (override defaults)
997 if (!NIL_P(options) && TYPE(options) == T_HASH)
999 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1000 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1001 autolink = OVERRIDE_IF_SET(autolink);
1002 line_ending = OVERRIDE_IF_SET(line_ending);
1003 external_link_class = OVERRIDE_IF_SET(external_link_class);
1004 mailto_class = OVERRIDE_IF_SET(mailto_class);
1005 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1006 img_prefix = OVERRIDE_IF_SET(img_prefix);
1007 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1008 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1009 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1012 // no need to call super here; rb_call_super()
1013 rb_iv_set(self, "@autolink", autolink);
1014 rb_iv_set(self, "@line_ending", line_ending);
1015 rb_iv_set(self, "@external_link_class", external_link_class);
1016 rb_iv_set(self, "@mailto_class", mailto_class);
1017 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1018 rb_iv_set(self, "@img_prefix", img_prefix);
1019 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1020 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1021 rb_iv_set(self, "@base_heading_level", base_heading_level);
1025 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1027 for (int i = 0; i < 100000; i++)
1028 Wikitext_parser_parse(1, &string, self);
1032 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1034 // process arguments
1035 VALUE string, options;
1036 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1040 string = StringValue(string);
1042 // process options hash
1043 int base_indent = 0;
1044 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1045 VALUE link_proc = Qnil;
1046 if (!NIL_P(options) && TYPE(options) == T_HASH)
1048 // :indent => 0 (or more)
1049 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1051 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1052 if (indent == Qfalse)
1053 base_indent = -1; // indentation disabled
1056 base_indent = NUM2INT(indent);
1057 if (base_indent < 0)
1062 // :base_heading_level => 0/1/2/3/4/5/6
1063 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1064 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1066 // :link_proc => lambda { |link_target| ... }
1067 // TODO: refactor to avoid some repeated calls to ID2SYM and rb_intern
1068 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("link_proc"))) == Qtrue)
1069 link_proc = rb_hash_aref(options, ID2SYM(rb_intern("link_proc")));
1072 // normalize, regardless of whether this came from instance variable or override
1073 if (base_heading_level < 0)
1074 base_heading_level = 0;
1075 if (base_heading_level > 6)
1076 base_heading_level = 6;
1079 char *p = RSTRING_PTR(string);
1080 long len = RSTRING_LEN(string);
1083 // access these once per parse
1084 VALUE line_ending = rb_iv_get(self, "@line_ending");
1085 line_ending = StringValue(line_ending);
1086 VALUE link_class = rb_iv_get(self, "@external_link_class");
1087 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1088 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1089 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1090 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1092 // set up parser struct to make passing parameters a little easier
1093 parser_t *parser = parser_new();
1094 GC_WRAP_PARSER(parser, parser_gc);
1095 parser->external_link_class = link_class;
1096 parser->mailto_class = mailto_class;
1097 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1098 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1099 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1100 parser->line_ending = str_new_from_string(line_ending);
1101 parser->base_indent = base_indent;
1102 parser->base_heading_level = base_heading_level;
1104 // this simple looping design leads to a single enormous function,
1105 // but it's faster than doing actual recursive descent and also secure in the face of
1106 // malicious input that seeks to overflow the stack
1107 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1108 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1109 // than a straightforward looping translator like this one anyway
1111 _token.type = NO_TOKEN;
1112 token_t *token = NULL;
1115 // note that whenever we grab a token we push it into the line buffer
1116 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1117 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1119 // check to see if we have a token hanging around from a previous iteration of this loop
1122 if (_token.type == NO_TOKEN)
1124 // first time here (haven't started scanning yet)
1126 next_token(token, NULL, p, pe);
1127 ary_push(parser->line_buffer, token->type);
1133 int type = token->type;
1135 // can't declare new variables inside a switch statement, so predeclare them here
1136 long remove_strong = -1;
1137 long remove_em = -1;
1139 // general purpose counters, flags and pointers
1143 str_t *output = NULL;
1145 str_t *token_str = &_token_str;
1147 // The following giant switch statement contains cases for all the possible token types.
1148 // In the most basic sense we are emitting the HTML that corresponds to each token,
1149 // but some tokens require context information in order to decide what to output.
1150 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1151 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1153 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1154 // - the line buffer (records tokens seen so far on the current line)
1155 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1157 // Although this is fairly complicated, there is one key simplifying factor:
1158 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1159 // scope stack (up to the current token) is valid; our translator can take this as a given.
1160 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1161 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1165 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1167 str_append(parser->output, space, sizeof(space) - 1);
1170 else if (IN(BLOCKQUOTE_START))
1172 // this kind of nesting not allowed (to avoid user confusion)
1173 wiki_pop_excess_elements(parser);
1174 wiki_start_para_if_necessary(parser);
1175 output = parser->capture ? parser->capture : parser->output;
1176 str_append(output, space, sizeof(space) - 1);
1180 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1181 ary_push(parser->line, PRE);
1182 i = ary_count(parser->line, BLOCKQUOTE);
1183 j = ary_count(parser->scope, BLOCKQUOTE);
1186 // must pop (reduce nesting level)
1187 for (i = j - i; i > 0; i--)
1188 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1193 parser->pending_crlf = false;
1194 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1195 wiki_indent(parser);
1196 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1197 ary_push(parser->scope, PRE);
1202 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1204 wiki_emit_pending_crlf_if_necessary(parser);
1205 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1207 else if (IN(BLOCKQUOTE_START))
1209 wiki_rollback_failed_link(parser); // if any
1210 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1211 wiki_append_pre_start(parser, token);
1213 else if (IN(BLOCKQUOTE))
1215 if (token->column_start == 1) // only allowed in first column
1217 wiki_rollback_failed_link(parser); // if any
1218 wiki_pop_all_from_stack(parser);
1219 wiki_append_pre_start(parser, token);
1221 else // PRE_START illegal here
1223 output = parser->capture ? parser->capture : parser->output;
1224 wiki_pop_excess_elements(parser);
1225 wiki_start_para_if_necessary(parser);
1226 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1231 wiki_rollback_failed_link(parser); // if any
1232 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1233 wiki_append_pre_start(parser, token);
1238 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1240 wiki_emit_pending_crlf_if_necessary(parser);
1241 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1246 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1249 output = parser->capture ? parser->capture : parser->output;
1250 wiki_pop_excess_elements(parser);
1251 wiki_start_para_if_necessary(parser);
1252 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1258 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1259 // no need to check for <pre>; can never appear inside it
1260 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1261 else if (IN(BLOCKQUOTE_START))
1263 // this kind of nesting not allowed (to avoid user confusion)
1264 wiki_pop_excess_elements(parser);
1265 wiki_start_para_if_necessary(parser);
1266 output = parser->capture ? parser->capture : parser->output;
1267 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1272 ary_push(parser->line, BLOCKQUOTE);
1274 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1275 i = ary_count(parser->line, BLOCKQUOTE);
1276 j = ary_count(parser->scope, BLOCKQUOTE);
1278 // given that BLOCKQUOTE tokens can be nested, peek ahead and see if there are any more which might affect the decision to push or pop
1279 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1281 ary_push(parser->line, BLOCKQUOTE);
1285 // now decide whether to push, pop or do nothing
1288 // must push (increase nesting level)
1289 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1290 for (i = i - j; i > 0; i--)
1292 wiki_indent(parser);
1293 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1294 str_append_str(parser->output, parser->line_ending);
1295 ary_push(parser->scope, BLOCKQUOTE);
1300 // must pop (reduce nesting level)
1301 for (i = j - i; i > 0; i--)
1302 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1305 // jump to top of the loop to process token we scanned during lookahead
1310 case BLOCKQUOTE_START:
1311 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1313 wiki_emit_pending_crlf_if_necessary(parser);
1314 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1316 else if (IN(BLOCKQUOTE_START))
1318 // nesting is fine here
1319 wiki_rollback_failed_link(parser); // if any
1320 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1321 wiki_indent(parser);
1322 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1323 str_append_str(parser->output, parser->line_ending);
1324 ary_push(parser->scope, BLOCKQUOTE_START);
1325 ary_push(parser->line, BLOCKQUOTE_START);
1327 else if (IN(BLOCKQUOTE))
1329 if (token->column_start == 1) // only allowed in first column
1331 wiki_rollback_failed_link(parser); // if any
1332 wiki_pop_all_from_stack(parser);
1333 wiki_indent(parser);
1334 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1335 str_append_str(parser->output, parser->line_ending);
1336 ary_push(parser->scope, BLOCKQUOTE_START);
1337 ary_push(parser->line, BLOCKQUOTE_START);
1339 else // BLOCKQUOTE_START illegal here
1341 output = parser->capture ? parser->capture : parser->output;
1342 wiki_pop_excess_elements(parser);
1343 wiki_start_para_if_necessary(parser);
1344 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1349 // would be nice to eliminate the repetition here but it's probably the clearest way
1350 wiki_rollback_failed_link(parser); // if any
1351 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1352 wiki_indent(parser);
1353 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1354 str_append_str(parser->output, parser->line_ending);
1355 ary_push(parser->scope, BLOCKQUOTE_START);
1356 ary_push(parser->line, BLOCKQUOTE_START);
1360 case BLOCKQUOTE_END:
1361 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1363 wiki_emit_pending_crlf_if_necessary(parser);
1364 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1368 if (IN(BLOCKQUOTE_START))
1369 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1372 output = parser->capture ? parser->capture : parser->output;
1373 wiki_pop_excess_elements(parser);
1374 wiki_start_para_if_necessary(parser);
1375 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1381 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1383 wiki_emit_pending_crlf_if_necessary(parser);
1384 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1388 wiki_pop_excess_elements(parser);
1389 wiki_start_para_if_necessary(parser);
1390 ary_push(parser->scope, NO_WIKI_START);
1391 ary_push(parser->line, NO_WIKI_START);
1396 if (IN(NO_WIKI_START))
1397 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1398 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1401 wiki_pop_excess_elements(parser);
1402 wiki_start_para_if_necessary(parser);
1403 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1408 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1410 wiki_emit_pending_crlf_if_necessary(parser);
1411 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1415 output = parser->capture ? parser->capture : parser->output;
1416 wiki_pop_excess_elements(parser);
1418 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1419 // otherwise, must open them
1422 j = parser->scope->count;
1423 for (j = j - 1; j >= 0; j--)
1425 int val = ary_entry(parser->scope, j);
1426 if (val == STRONG || val == STRONG_START)
1428 str_append(output, strong_end, sizeof(strong_end) - 1);
1431 else if (val == EM || val == EM_START)
1433 str_append(output, em_end, sizeof(em_end) - 1);
1438 if (remove_strong > remove_em) // must remove strong first
1440 ary_pop(parser->scope);
1442 ary_pop(parser->scope);
1443 else // there was no em to remove!, so consider this an opening em tag
1445 str_append(output, em_start, sizeof(em_start) - 1);
1446 ary_push(parser->scope, EM);
1447 ary_push(parser->line, EM);
1450 else if (remove_em > remove_strong) // must remove em first
1452 ary_pop(parser->scope);
1453 if (remove_strong > -1)
1454 ary_pop(parser->scope);
1455 else // there was no strong to remove!, so consider this an opening strong tag
1457 str_append(output, strong_start, sizeof(strong_start) - 1);
1458 ary_push(parser->scope, STRONG);
1459 ary_push(parser->line, STRONG);
1462 else // no strong or em to remove, so this must be a new opening of both
1464 wiki_start_para_if_necessary(parser);
1465 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1466 ary_push(parser->scope, STRONG);
1467 ary_push(parser->line, STRONG);
1468 ary_push(parser->scope, EM);
1469 ary_push(parser->line, EM);
1474 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1476 wiki_emit_pending_crlf_if_necessary(parser);
1477 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1481 output = parser->capture ? parser->capture : parser->output;
1482 if (IN(STRONG_START))
1483 // already in span started with <strong>, no choice but to emit this literally
1484 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1485 else if (IN(STRONG))
1486 // STRONG already seen, this is a closing tag
1487 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1490 // this is a new opening
1491 wiki_pop_excess_elements(parser);
1492 wiki_start_para_if_necessary(parser);
1493 str_append(output, strong_start, sizeof(strong_start) - 1);
1494 ary_push(parser->scope, STRONG);
1495 ary_push(parser->line, STRONG);
1501 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1503 wiki_emit_pending_crlf_if_necessary(parser);
1504 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1508 output = parser->capture ? parser->capture : parser->output;
1509 if (IN_EITHER_OF(STRONG_START, STRONG))
1510 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1513 wiki_pop_excess_elements(parser);
1514 wiki_start_para_if_necessary(parser);
1515 str_append(output, strong_start, sizeof(strong_start) - 1);
1516 ary_push(parser->scope, STRONG_START);
1517 ary_push(parser->line, STRONG_START);
1523 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1525 wiki_emit_pending_crlf_if_necessary(parser);
1526 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1530 output = parser->capture ? parser->capture : parser->output;
1531 if (IN(STRONG_START))
1532 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1535 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1536 wiki_pop_excess_elements(parser);
1537 wiki_start_para_if_necessary(parser);
1538 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1544 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1546 wiki_emit_pending_crlf_if_necessary(parser);
1547 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1551 output = parser->capture ? parser->capture : parser->output;
1553 // already in span started with <em>, no choice but to emit this literally
1554 str_append(output, literal_em, sizeof(literal_em) - 1);
1556 // EM already seen, this is a closing tag
1557 wiki_pop_from_stack_up_to(parser, output, EM, true);
1560 // this is a new opening
1561 wiki_pop_excess_elements(parser);
1562 wiki_start_para_if_necessary(parser);
1563 str_append(output, em_start, sizeof(em_start) - 1);
1564 ary_push(parser->scope, EM);
1565 ary_push(parser->line, EM);
1571 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1573 wiki_emit_pending_crlf_if_necessary(parser);
1574 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1578 output = parser->capture ? parser->capture : parser->output;
1579 if (IN_EITHER_OF(EM_START, EM))
1580 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1583 wiki_pop_excess_elements(parser);
1584 wiki_start_para_if_necessary(parser);
1585 str_append(output, em_start, sizeof(em_start) - 1);
1586 ary_push(parser->scope, EM_START);
1587 ary_push(parser->line, EM_START);
1593 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1595 wiki_emit_pending_crlf_if_necessary(parser);
1596 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1600 output = parser->capture ? parser->capture : parser->output;
1602 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1605 // no EM_START in scope, so must interpret the TT_END without any special meaning
1606 wiki_pop_excess_elements(parser);
1607 wiki_start_para_if_necessary(parser);
1608 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1614 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1616 wiki_emit_pending_crlf_if_necessary(parser);
1617 str_append(parser->output, backtick, sizeof(backtick) - 1);
1621 output = parser->capture ? parser->capture : parser->output;
1623 // already in span started with <tt>, no choice but to emit this literally
1624 str_append(output, backtick, sizeof(backtick) - 1);
1626 // TT (`) already seen, this is a closing tag
1627 wiki_pop_from_stack_up_to(parser, output, TT, true);
1630 // this is a new opening
1631 wiki_pop_excess_elements(parser);
1632 wiki_start_para_if_necessary(parser);
1633 str_append(output, tt_start, sizeof(tt_start) - 1);
1634 ary_push(parser->scope, TT);
1635 ary_push(parser->line, TT);
1641 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1643 wiki_emit_pending_crlf_if_necessary(parser);
1644 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1648 output = parser->capture ? parser->capture : parser->output;
1649 if (IN_EITHER_OF(TT_START, TT))
1650 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1653 wiki_pop_excess_elements(parser);
1654 wiki_start_para_if_necessary(parser);
1655 str_append(output, tt_start, sizeof(tt_start) - 1);
1656 ary_push(parser->scope, TT_START);
1657 ary_push(parser->line, TT_START);
1663 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1665 wiki_emit_pending_crlf_if_necessary(parser);
1666 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1670 output = parser->capture ? parser->capture : parser->output;
1672 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1675 // no TT_START in scope, so must interpret the TT_END without any special meaning
1676 wiki_pop_excess_elements(parser);
1677 wiki_start_para_if_necessary(parser);
1678 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1685 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1687 // no need to check for PRE; can never appear inside it
1688 str_append(parser->output, token->start, TOKEN_LEN(token));
1692 // count number of tokens in line and scope stacks
1693 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1694 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1695 j = parser->scope->count - bq_count;
1698 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1702 if (type == OL || type == UL)
1705 if (i - k >= 2) // already seen at least one OL or UL
1707 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1712 ary_push(parser->line, type);
1713 ary_push(parser->line, LI);
1715 // want to compare line with scope but can only do so if scope has enough items on it
1718 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1719 ary_entry(parser->scope, i + bq_count - 1) == LI)
1721 // line and scope match at this point: do nothing yet
1725 // item just pushed onto line does not match corresponding slot of scope!
1726 for (; j >= i - 2; j--)
1727 // must pop back before emitting
1728 wiki_pop_from_stack(parser, NULL);
1730 // will emit UL or OL, then LI
1734 else // line stack size now exceeds scope stack size: must increase nesting level
1735 break; // will emit UL or OL, then LI
1739 // not a OL or UL token!
1741 // must close existing LI and re-open new one
1742 wiki_pop_from_stack(parser, NULL);
1745 // item just pushed onto line does not match corresponding slot of scope!
1747 // must pop back before emitting
1748 wiki_pop_from_stack(parser, NULL);
1756 if (type == OL || type == UL)
1758 // if LI is at the top of a stack this is the start of a nested list
1759 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1761 // so we should precede it with a CRLF, and indicate that it's a nested list
1762 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1763 ary_push(parser->scope, NESTED_LIST);
1767 // this is a new list
1768 if (IN(BLOCKQUOTE_START))
1769 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1771 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1775 wiki_indent(parser);
1777 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1778 else if (type == UL)
1779 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1780 ary_push(parser->scope, type);
1781 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1783 else if (type == SPACE)
1784 // silently throw away the optional SPACE token after final list marker
1787 wiki_indent(parser);
1788 str_append(parser->output, li_start, sizeof(li_start) - 1);
1789 ary_push(parser->scope, LI);
1791 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1792 if (type == OL || type == UL)
1795 while (k++, NEXT_TOKEN(), (type = token->type))
1797 if (type == OL || type == UL)
1798 str_append(parser->output, token->start, TOKEN_LEN(token));
1799 else if (type == SPACE && k == 1)
1801 // silently throw away the optional SPACE token after final list marker
1810 // jump to top of the loop to process token we scanned during lookahead
1819 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1821 // no need to check for PRE; can never appear inside it
1822 str_append(parser->output, token->start, TOKEN_LEN(token));
1826 // pop up to but not including the last BLOCKQUOTE on the scope stack
1827 if (IN(BLOCKQUOTE_START))
1828 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1830 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1832 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1833 ary_push(parser->line, type);
1834 i = ary_count(parser->line, BLOCKQUOTE);
1835 j = ary_count(parser->scope, BLOCKQUOTE);
1837 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1840 // must pop (reduce nesting level)
1841 for (i = j - i; i > 0; i--)
1842 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1845 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1846 while (NEXT_TOKEN(), (token->type == SPACE))
1849 ary_push(parser->scope, type);
1850 wiki_indent(parser);
1852 // take base_heading_level into account
1853 type += base_heading_level;
1854 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1857 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1858 if (type == H6_START)
1859 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1860 else if (type == H5_START)
1861 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1862 else if (type == H4_START)
1863 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1864 else if (type == H3_START)
1865 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1866 else if (type == H2_START)
1867 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1868 else if (type == H1_START)
1869 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1871 // jump to top of the loop to process token we scanned during lookahead
1880 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1882 wiki_emit_pending_crlf_if_necessary(parser);
1883 str_append(parser->output, token->start, TOKEN_LEN(token));
1887 wiki_rollback_failed_external_link(parser); // if any
1888 if ((type == H6_END && !IN(H6_START)) ||
1889 (type == H5_END && !IN(H5_START)) ||
1890 (type == H4_END && !IN(H4_START)) ||
1891 (type == H3_END && !IN(H3_START)) ||
1892 (type == H2_END && !IN(H2_START)) ||
1893 (type == H1_END && !IN(H1_START)))
1895 // literal output only if not in appropriate scope (we stay silent in that case)
1896 wiki_start_para_if_necessary(parser);
1897 str_append(parser->output, token->start, TOKEN_LEN(token));
1903 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1905 wiki_emit_pending_crlf_if_necessary(parser);
1906 str_append(parser->output, token->start, TOKEN_LEN(token));
1910 wiki_pop_excess_elements(parser);
1911 wiki_start_para_if_necessary(parser);
1912 token_str->ptr = token->start;
1913 token_str->len = TOKEN_LEN(token);
1914 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
1919 if (IN(NO_WIKI_START))
1920 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1921 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1922 str_append(parser->output, token->start, TOKEN_LEN(token));
1923 else if (IN(LINK_START))
1925 // if the URI were allowed it would have been handled already in LINK_START
1926 wiki_rollback_failed_internal_link(parser);
1927 token_str->ptr = token->start;
1928 token_str->len = TOKEN_LEN(token);
1929 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1931 else if (IN(EXT_LINK_START))
1933 if (parser->link_target->len == 0)
1935 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1936 token_str->ptr = token->start;
1937 token_str->len = TOKEN_LEN(token);
1939 if (token->type == SPACE)
1941 ary_push(parser->scope, SPACE);
1942 str_append_str(parser->link_target, token_str);
1943 str_clear(parser->link_text);
1944 parser->capture = parser->link_text;
1945 token = NULL; // silently consume space
1949 // didn't see the space! this must be an error
1950 wiki_pop_from_stack(parser, NULL);
1951 wiki_pop_excess_elements(parser);
1952 wiki_start_para_if_necessary(parser);
1953 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1954 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1958 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1962 wiki_pop_excess_elements(parser);
1963 wiki_start_para_if_necessary(parser);
1964 token_str->ptr = token->start;
1965 token_str->len = TOKEN_LEN(token);
1966 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1971 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1972 str_append(parser->output, token->start, TOKEN_LEN(token));
1973 else if (IN(EXT_LINK_START))
1975 if (parser->link_target->len == 0)
1977 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1978 token_str->ptr = token->start;
1979 token_str->len = TOKEN_LEN(token);
1981 if (token->type == SPACE)
1983 ary_push(parser->scope, PATH);
1984 ary_push(parser->scope, SPACE);
1985 str_append_str(parser->link_target, token_str);
1986 str_clear(parser->link_text);
1987 parser->capture = parser->link_text;
1988 token = NULL; // silently consume space
1992 // didn't see the space! this must be an error
1993 wiki_pop_from_stack(parser, NULL);
1994 wiki_pop_excess_elements(parser);
1995 wiki_start_para_if_necessary(parser);
1996 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1997 str_append_str(parser->output, token_str);
2001 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2005 output = parser->capture ? parser->capture : parser->output;
2006 wiki_pop_excess_elements(parser);
2007 wiki_start_para_if_necessary(parser);
2008 str_append(output, token->start, TOKEN_LEN(token));
2012 // internal links (links to other wiki articles) look like this:
2013 // [[another article]] (would point at, for example, "/wiki/another_article")
2014 // [[the other article|the link text we'll use for it]]
2015 // [[the other article | the link text we'll use for it]]
2016 // MediaWiki has strict requirements about what it will accept as a link target:
2017 // all wikitext markup is disallowed:
2018 // example [[foo ''bar'' baz]]
2019 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2020 // example [[foo <em>bar</em> baz]]
2021 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2022 // example [[foo <nowiki>''</nowiki> baz]]
2023 // renders [[foo '' baz]] (ie. not a link)
2024 // example [[foo <bar> baz]]
2025 // renders [[foo <bar> baz]] (ie. not a link)
2026 // HTML entities and non-ASCII, however, make it through:
2027 // example [[foo €]]
2028 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2029 // example [[foo €]]
2030 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2031 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2032 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2033 // everything else will be rejected
2035 output = parser->capture ? parser->capture : parser->output;
2036 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2038 wiki_emit_pending_crlf_if_necessary(parser);
2039 str_append(output, link_start, sizeof(link_start) - 1);
2041 else if (IN(EXT_LINK_START))
2042 // already in external link scope! (and in fact, must be capturing link_text right now)
2043 str_append(output, link_start, sizeof(link_start) - 1);
2044 else if (IN(LINK_START))
2046 // already in internal link scope! this is a syntax error
2047 wiki_rollback_failed_internal_link(parser);
2048 str_append(parser->output, link_start, sizeof(link_start) - 1);
2050 else if (IN(SEPARATOR))
2052 // scanning internal link text
2054 else // not in internal link scope yet
2056 // will either emit a link, or the rollback of a failed link, so start the para now
2057 wiki_pop_excess_elements(parser);
2058 wiki_start_para_if_necessary(parser);
2059 ary_push(parser->scope, LINK_START);
2061 // look ahead and try to gobble up link target
2062 while (NEXT_TOKEN(), (type = token->type))
2064 if (type == SPACE ||
2065 type == SPECIAL_URI_CHARS ||
2067 type == PRINTABLE ||
2071 type == QUOT_ENTITY ||
2073 type == AMP_ENTITY ||
2074 type == IMG_START ||
2076 type == LEFT_CURLY ||
2077 type == RIGHT_CURLY)
2079 // accumulate these tokens into link_target
2080 if (parser->link_target->len == 0)
2082 str_clear(parser->link_target);
2083 parser->capture = parser->link_target;
2085 if (type == QUOT_ENTITY)
2086 // don't insert the entity, insert the literal quote
2087 str_append(parser->link_target, quote, sizeof(quote) - 1);
2088 else if (type == AMP_ENTITY)
2089 // don't insert the entity, insert the literal ampersand
2090 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2092 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2094 else if (type == LINK_END)
2096 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2097 wiki_rollback_failed_internal_link(parser);
2098 break; // jump back to top of loop (will handle this in LINK_END case below)
2100 else if (type == SEPARATOR)
2102 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2103 wiki_rollback_failed_internal_link(parser);
2106 ary_push(parser->scope, SEPARATOR);
2107 str_clear(parser->link_text);
2108 parser->capture = parser->link_text;
2113 else // unexpected token (syntax error)
2115 wiki_rollback_failed_internal_link(parser);
2116 break; // jump back to top of loop to handle unexpected token
2120 // jump to top of the loop to process token we scanned during lookahead (if any)
2126 output = parser->capture ? parser->capture : parser->output;
2127 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2129 wiki_emit_pending_crlf_if_necessary(parser);
2130 str_append(output, link_end, sizeof(link_end) - 1);
2132 else if (IN(EXT_LINK_START))
2133 // already in external link scope! (and in fact, must be capturing link_text right now)
2134 str_append(output, link_end, sizeof(link_end) - 1);
2135 else if (IN(LINK_START)) // in internal link scope!
2137 if (wiki_blank(parser->link_target))
2139 // special case for inputs like "[[ ]]"
2140 wiki_rollback_failed_internal_link(parser);
2141 str_append(parser->output, link_end, sizeof(link_end) - 1);
2144 if (parser->link_text->len == 0 ||
2145 wiki_blank(parser->link_text))
2147 // use link target as link text
2148 str_clear(parser->link_text);
2149 wiki_append_sanitized_link_target(parser, parser->link_text, true);
2152 wiki_trim_link_text(parser);
2154 // perform "redlink" check before manipulating link_target
2155 if (NIL_P(link_proc))
2159 j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
2163 wiki_encode_link_target(parser);
2164 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2165 parser->capture = NULL;
2166 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, false);
2167 str_clear(parser->link_target);
2168 str_clear(parser->link_text);
2170 else // wasn't in internal link scope
2172 wiki_pop_excess_elements(parser);
2173 wiki_start_para_if_necessary(parser);
2174 str_append(output, link_end, sizeof(link_end) - 1);
2178 // external links look like this:
2179 // [http://google.com/ the link text]
2180 // [/other/page/on/site see this page]
2181 // strings in square brackets which don't match this syntax get passed through literally; eg:
2182 // he was very angery [sic] about the turn of events
2183 case EXT_LINK_START:
2184 output = parser->capture ? parser->capture : parser->output;
2185 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2187 wiki_emit_pending_crlf_if_necessary(parser);
2188 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2190 else if (IN(EXT_LINK_START))
2191 // already in external link scope! (and in fact, must be capturing link_text right now)
2192 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2193 else if (IN(LINK_START))
2195 // already in internal link scope!
2196 if (parser->link_target->len == 0 || !IN(SPACE))
2197 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2198 else // link target has already been scanned
2199 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2201 else // not in external link scope yet
2203 // will either emit a link, or the rollback of a failed link, so start the para now
2204 wiki_pop_excess_elements(parser);
2205 wiki_start_para_if_necessary(parser);
2207 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2209 if (token->type == URI || token->type == PATH)
2210 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2212 // only get here if there was a syntax error (missing URI)
2213 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2214 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2219 output = parser->capture ? parser->capture : parser->output;
2220 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2222 wiki_emit_pending_crlf_if_necessary(parser);
2223 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2225 else if (IN(EXT_LINK_START))
2227 if (parser->link_text->len == 0)
2228 // syntax error: external link with no link text
2229 wiki_rollback_failed_external_link(parser);
2233 j = IN(PATH) ? Qnil : parser->external_link_class;
2234 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2235 parser->capture = NULL;
2236 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2238 str_clear(parser->link_target);
2239 str_clear(parser->link_text);
2243 wiki_pop_excess_elements(parser);
2244 wiki_start_para_if_necessary(parser);
2245 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2250 output = parser->capture ? parser->capture : parser->output;
2251 wiki_pop_excess_elements(parser);
2252 wiki_start_para_if_necessary(parser);
2253 str_append(output, separator, sizeof(separator) - 1);
2257 output = parser->capture ? parser->capture : parser->output;
2258 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2260 wiki_emit_pending_crlf_if_necessary(parser);
2261 str_append(output, token->start, TOKEN_LEN(token));
2265 // peek ahead to see next token
2266 char *token_ptr = token->start;
2267 int token_len = TOKEN_LEN(token);
2270 if ((type == H6_END && IN(H6_START)) ||
2271 (type == H5_END && IN(H5_START)) ||
2272 (type == H4_END && IN(H4_START)) ||
2273 (type == H3_END && IN(H3_START)) ||
2274 (type == H2_END && IN(H2_START)) ||
2275 (type == H1_END && IN(H1_START)))
2277 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2282 wiki_pop_excess_elements(parser);
2283 wiki_start_para_if_necessary(parser);
2284 str_append(output, token_ptr, token_len);
2287 // jump to top of the loop to process token we scanned during lookahead
2295 case DECIMAL_ENTITY:
2296 // pass these through unaltered as they are case sensitive
2297 output = parser->capture ? parser->capture : parser->output;
2298 wiki_pop_excess_elements(parser);
2299 wiki_start_para_if_necessary(parser);
2300 str_append(output, token->start, TOKEN_LEN(token));
2304 // normalize hex entities (downcase them)
2305 output = parser->capture ? parser->capture : parser->output;
2306 wiki_pop_excess_elements(parser);
2307 wiki_start_para_if_necessary(parser);
2308 str_append(output, token->start, TOKEN_LEN(token));
2309 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2313 output = parser->capture ? parser->capture : parser->output;
2314 wiki_pop_excess_elements(parser);
2315 wiki_start_para_if_necessary(parser);
2316 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2320 output = parser->capture ? parser->capture : parser->output;
2321 wiki_pop_excess_elements(parser);
2322 wiki_start_para_if_necessary(parser);
2323 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2327 output = parser->capture ? parser->capture : parser->output;
2328 wiki_pop_excess_elements(parser);
2329 wiki_start_para_if_necessary(parser);
2330 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2334 output = parser->capture ? parser->capture : parser->output;
2335 wiki_pop_excess_elements(parser);
2336 wiki_start_para_if_necessary(parser);
2337 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2341 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2343 wiki_emit_pending_crlf_if_necessary(parser);
2344 str_append(parser->output, token->start, TOKEN_LEN(token));
2346 else if (parser->capture)
2347 str_append(parser->capture, token->start, TOKEN_LEN(token));
2350 // not currently capturing: will be emitting something on success or failure, so get ready
2351 wiki_pop_excess_elements(parser);
2352 wiki_start_para_if_necessary(parser);
2354 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2355 // will cheat here and abuse the link_target capture buffer to accumulate text
2356 while (NEXT_TOKEN(), (type = token->type))
2358 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2359 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2360 else if (type == IMG_END && parser->link_target->len > 0)
2363 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2367 else // unexpected token or zero-length target (syntax error)
2370 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2371 if (parser->link_target->len > 0)
2372 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2377 // jump to top of the loop to process token we scanned during lookahead
2378 str_clear(parser->link_target);
2384 i = parser->pending_crlf;
2385 parser->pending_crlf = false;
2386 wiki_rollback_failed_link(parser); // if any
2387 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2389 ary_clear(parser->line_buffer);
2390 str_append_str(parser->output, parser->line_ending);
2395 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2396 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2397 // don't emit in this case
2398 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2401 if (ary_entry(parser->line_buffer, -2) == PRE)
2403 // only thing on line is the PRE: emit pending line ending (if we had one)
2405 str_append_str(parser->output, parser->line_ending);
2408 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2409 ary_clear(parser->line);
2410 ary_clear(parser->line_buffer);
2412 // peek ahead to see if this is definitely the end of the PRE block
2415 if (type != BLOCKQUOTE && type != PRE)
2416 // this is definitely the end of the block, so don't emit
2417 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2419 // potentially will emit
2420 parser->pending_crlf = true;
2422 continue; // jump back to top of loop to handle token grabbed via lookahead
2427 parser->pending_crlf = true;
2429 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2430 // as a side effect, this handles any open span-level elements and unclosed blocks
2431 // (with special handling for P blocks and LI elements)
2432 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2433 for (j = parser->scope->count; j > i; j--)
2435 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2437 parser->pending_crlf = false;
2441 // special handling on last iteration through the loop if the top item on the scope is a P block
2442 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2444 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2445 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2446 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2447 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2448 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2450 parser->pending_crlf = false;
2452 // not a paragraph break!
2455 wiki_pop_from_stack(parser, NULL);
2459 // delete the entire contents of the line scope stack and buffer
2460 ary_clear(parser->line);
2461 ary_clear(parser->line_buffer);
2464 case SPECIAL_URI_CHARS:
2470 output = parser->capture ? parser->capture : parser->output;
2471 wiki_pop_excess_elements(parser);
2472 wiki_start_para_if_necessary(parser);
2473 str_append(output, token->start, TOKEN_LEN(token));
2477 output = parser->capture ? parser->capture : parser->output;
2478 wiki_pop_excess_elements(parser);
2479 wiki_start_para_if_necessary(parser);
2480 wiki_append_entity_from_utf32_char(output, token->code_point);
2484 // special case for input like " foo\n " (see pre_spec.rb)
2486 ary_entry(parser->line_buffer, -2) == PRE &&
2487 parser->pending_crlf)
2488 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2490 // close any open scopes on hitting EOF
2491 wiki_rollback_failed_link(parser); // if any
2492 wiki_pop_all_from_stack(parser);
2493 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2499 // reset current token; forcing lexer to return another token at the top of the loop
2503 // nasty hack to avoid re-allocating our return value
2504 str_append(parser->output, null_str, 1); // null-terminate
2505 len = parser->output->len - 1; // don't count null termination
2507 #if defined(RUBY_1_9_x)
2508 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2509 free(RSTRING_PTR(out));
2510 RSTRING(out)->as.heap.aux.capa = len;
2511 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2512 RSTRING(out)->as.heap.len = len;
2513 #elif defined(RUBY_1_8_x)
2514 VALUE out = rb_str_new2("");
2515 free(RSTRING_PTR(out));
2516 RSTRING(out)->len = len;
2517 RSTRING(out)->aux.capa = len;
2518 RSTRING(out)->ptr = parser->output->ptr;
2520 #error unsupported RUBY_VERSION
2522 parser->output->ptr = NULL; // don't double-free