1 // Copyright 2007-2010 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 mailto_class; // CSS class applied to email (mailto) links
55 VALUE img_prefix; // path prepended when emitting img tags
56 int output_style; // HTML_OUTPUT (default) or XML_OUTPUT
57 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
58 int current_indent; // fluctuates according to currently nested structures
59 int base_heading_level;
62 bool space_to_underscore;
65 const char null_str[] = { 0 };
66 const char escaped_no_wiki_start[] = "<nowiki>";
67 const char escaped_no_wiki_end[] = "</nowiki>";
68 const char literal_strong_em[] = "'''''";
69 const char literal_strong[] = "'''";
70 const char literal_em[] = "''";
71 const char escaped_em_start[] = "<em>";
72 const char escaped_em_end[] = "</em>";
73 const char escaped_strong_start[] = "<strong>";
74 const char escaped_strong_end[] = "</strong>";
75 const char escaped_tt_start[] = "<tt>";
76 const char escaped_tt_end[] = "</tt>";
77 const char pre_start[] = "<pre>";
78 const char pre_end[] = "</pre>";
79 const char escaped_pre_start[] = "<pre>";
80 const char escaped_pre_end[] = "</pre>";
81 const char blockquote_start[] = "<blockquote>";
82 const char blockquote_end[] = "</blockquote>";
83 const char escaped_blockquote_start[] = "<blockquote>";
84 const char escaped_blockquote_end[] = "</blockquote>";
85 const char strong_em_start[] = "<strong><em>";
86 const char strong_start[] = "<strong>";
87 const char strong_end[] = "</strong>";
88 const char em_start[] = "<em>";
89 const char em_end[] = "</em>";
90 const char code_start[] = "<code>";
91 const char code_end[] = "</code>";
92 const char ol_start[] = "<ol>";
93 const char ol_end[] = "</ol>";
94 const char ul_start[] = "<ul>";
95 const char ul_end[] = "</ul>";
96 const char li_start[] = "<li>";
97 const char li_end[] = "</li>";
98 const char h6_start[] = "<h6>";
99 const char h6_end[] = "</h6>";
100 const char h5_start[] = "<h5>";
101 const char h5_end[] = "</h5>";
102 const char h4_start[] = "<h4>";
103 const char h4_end[] = "</h4>";
104 const char h3_start[] = "<h3>";
105 const char h3_end[] = "</h3>";
106 const char h2_start[] = "<h2>";
107 const char h2_end[] = "</h2>";
108 const char h1_start[] = "<h1>";
109 const char h1_end[] = "</h1>";
110 const char p_start[] = "<p>";
111 const char p_end[] = "</p>";
112 const char space[] = " ";
113 const char a_start[] = "<a href=\"";
114 const char a_class[] = "\" class=\"";
115 const char a_start_close[] = "\">";
116 const char a_end[] = "</a>";
117 const char link_start[] = "[[";
118 const char link_end[] = "]]";
119 const char separator[] = "|";
120 const char ext_link_start[] = "[";
121 const char backtick[] = "`";
122 const char quote[] = "\"";
123 const char ampersand[] = "&";
124 const char quot_entity[] = """;
125 const char amp_entity[] = "&";
126 const char lt_entity[] = "<";
127 const char gt_entity[] = ">";
128 const char escaped_blockquote[] = "> ";
129 const char ext_link_end[] = "]";
130 const char literal_img_start[] = "{{";
131 const char img_start[] = "<img src=\"";
132 const char img_end[] = "\" />";
133 const char img_alt[] = "\" alt=\"";
134 const char pre_class_start[] = "<pre class=\"";
135 const char pre_class_end[] = "-syntax\">";
137 // Mark the parser struct designated by ptr as a participant in Ruby's
138 // mark-and-sweep garbage collection scheme. A variable named name is placed on
139 // the C stack to prevent the structure from being prematurely collected.
140 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
142 parser_t *parser_new(void)
144 parser_t *parser = ALLOC_N(parser_t, 1);
145 parser->capture = NULL; // not a real instance, pointer to other member's instance
146 parser->output = str_new();
147 parser->link_target = str_new();
148 parser->link_text = str_new();
149 parser->line_ending = NULL; // caller should set up
150 parser->tabulation = str_new();
151 parser->scope = ary_new();
152 parser->line = ary_new();
153 parser->line_buffer = ary_new();
154 parser->external_link_class = Qnil; // caller should set up
155 parser->mailto_class = Qnil; // caller should set up
156 parser->img_prefix = Qnil; // caller should set up
157 parser->output_style = HTML_OUTPUT;
158 parser->base_indent = 0;
159 parser->current_indent = 0;
160 parser->base_heading_level = 0;
161 parser->pending_crlf = false;
162 parser->autolink = true;
163 parser->space_to_underscore = true;
167 void parser_free(parser_t *parser)
169 // we don't free parser->capture; it's just a redundant pointer
170 if (parser->output) str_free(parser->output);
171 if (parser->link_target) str_free(parser->link_target);
172 if (parser->link_text) str_free(parser->link_text);
173 if (parser->line_ending) str_free(parser->line_ending);
174 if (parser->tabulation) str_free(parser->tabulation);
175 if (parser->scope) ary_free(parser->scope);
176 if (parser->line) ary_free(parser->line);
177 if (parser->line_buffer) ary_free(parser->line_buffer);
181 // for testing and debugging only
182 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
186 string = StringValue(string);
187 VALUE tokens = rb_ary_new();
188 char *p = RSTRING_PTR(string);
189 long len = RSTRING_LEN(string);
192 next_token(&token, NULL, p, pe);
193 rb_ary_push(tokens, wiki_token(&token));
194 while (token.type != END_OF_FILE)
196 next_token(&token, &token, NULL, pe);
197 rb_ary_push(tokens, wiki_token(&token));
202 // for benchmarking raw tokenization speed only
203 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
207 string = StringValue(string);
208 char *p = RSTRING_PTR(string);
209 long len = RSTRING_LEN(string);
212 next_token(&token, NULL, p, pe);
213 while (token.type != END_OF_FILE)
214 next_token(&token, &token, NULL, pe);
218 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
221 VALUE string, options;
222 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
226 string = StringValue(string);
227 VALUE tokens = rb_ary_new();
229 // check instance variables
230 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
232 // process options hash (can override instance variables)
233 if (!NIL_P(options) && TYPE(options) == T_HASH)
235 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
236 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
238 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
243 char *p = RSTRING_PTR(string);
244 long len = RSTRING_LEN(string);
247 token_t *_token = &token;
248 next_token(&token, NULL, p, pe);
249 while (token.type != END_OF_FILE)
256 if (TOKEN_LEN(_token) >= min_len)
257 rb_ary_push(tokens, TOKEN_TEXT(_token));
260 // ignore everything else
263 next_token(&token, &token, NULL, pe);
268 // we downcase "in place", overwriting the original contents of the buffer
269 void wiki_downcase_bang(char *ptr, long len)
271 for (long i = 0; i < len; i++)
273 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
278 // prepare hyperlink and append it to parser->output
279 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
280 // or merely the literal link target
281 // if link_text is Qnil, the link_target is re-used for the link text
282 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, bool check_autolink)
284 if (check_autolink && !parser->autolink)
285 str_append_str(parser->output, link_target);
288 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
289 if (!NIL_P(link_prefix))
290 str_append_string(parser->output, link_prefix);
291 str_append_str(parser->output, link_target);
293 // special handling for mailto URIs
294 const char *mailto = "mailto:";
295 long mailto_len = (long)sizeof(mailto) - 1; // don't count NUL byte
296 if ((link_target->len >= mailto_len &&
297 strncmp(mailto, link_target->ptr, mailto_len) == 0) ||
298 (!NIL_P(link_prefix) &&
299 RSTRING_LEN(link_prefix) >= mailto_len &&
300 strncmp(mailto, RSTRING_PTR(link_prefix), mailto_len) == 0))
301 link_class = parser->mailto_class; // use mailto_class from parser
302 if (link_class != Qnil)
304 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
305 str_append_string(parser->output, link_class);
307 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
308 if (!link_text || link_text->len == 0) // re-use link_target
309 str_append_str(parser->output, link_target);
311 str_append_str(parser->output, link_text);
312 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
316 void wiki_append_img(parser_t *parser, char *token_ptr, int token_len)
318 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
319 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
320 str_append_string(parser->output, parser->img_prefix);
321 str_append(parser->output, token_ptr, token_len);
322 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
323 str_append(parser->output, token_ptr, token_len);
324 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
327 // will emit indentation only if we are about to emit any of:
328 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
329 // each time we enter one of those spans must ++ the indentation level
330 void wiki_indent(parser_t *parser)
332 if (parser->base_indent == -1) // indentation disabled
334 int space_count = parser->current_indent + parser->base_indent;
337 char *old_end, *new_end;
338 if (parser->tabulation->len < space_count)
339 str_grow(parser->tabulation, space_count); // reallocates if necessary
340 old_end = parser->tabulation->ptr + parser->tabulation->len;
341 new_end = parser->tabulation->ptr + space_count;
342 while (old_end < new_end)
344 if (space_count > parser->tabulation->len)
345 parser->tabulation->len = space_count;
346 str_append(parser->output, parser->tabulation->ptr, space_count);
348 parser->current_indent += 2;
351 void wiki_append_pre_start(parser_t *parser, token_t *token)
354 if ((size_t)TOKEN_LEN(token) > sizeof(pre_start) - 1)
356 str_append(parser->output, pre_class_start, sizeof(pre_class_start) - 1); // <pre class="
357 str_append(parser->output, token->start + 11, TOKEN_LEN(token) - 13); // (the "lang" substring)
358 str_append(parser->output, pre_class_end, sizeof(pre_class_end) - 1); // -syntax">
361 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
362 ary_push(parser->scope, PRE_START);
363 ary_push(parser->line, PRE_START);
366 void wiki_dedent(parser_t *parser, bool emit)
368 if (parser->base_indent == -1) // indentation disabled
370 parser->current_indent -= 2;
373 int space_count = parser->current_indent + parser->base_indent;
375 str_append(parser->output, parser->tabulation->ptr, space_count);
378 // Pops a single item off the parser's scope stack.
379 // A corresponding closing tag is written to the target string.
380 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
381 void wiki_pop_from_stack(parser_t *parser, str_t *target)
383 int top = ary_entry(parser->scope, -1);
387 target = parser->output;
389 // for headings, take base_heading_level into account
390 if (top >= H1_START && top <= H6_START)
392 top += parser->base_heading_level;
393 // no need to check for underflow (base_heading_level is never negative)
402 str_append(target, pre_end, sizeof(pre_end) - 1);
403 str_append_str(target, parser->line_ending);
404 wiki_dedent(parser, false);
408 case BLOCKQUOTE_START:
409 wiki_dedent(parser, true);
410 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
411 str_append_str(target, parser->line_ending);
415 // not a real HTML tag; so nothing to pop
420 str_append(target, strong_end, sizeof(strong_end) - 1);
425 str_append(target, em_end, sizeof(em_end) - 1);
430 str_append(target, code_end, sizeof(code_end) - 1);
434 wiki_dedent(parser, true);
435 str_append(target, ol_end, sizeof(ol_end) - 1);
436 str_append_str(target, parser->line_ending);
440 wiki_dedent(parser, true);
441 str_append(target, ul_end, sizeof(ul_end) - 1);
442 str_append_str(target, parser->line_ending);
446 // next token to pop will be a LI
447 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
448 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
449 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
450 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
451 wiki_dedent(parser, true); // we really only want to emit the spaces
452 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
456 str_append(target, li_end, sizeof(li_end) - 1);
457 str_append_str(target, parser->line_ending);
458 wiki_dedent(parser, false);
462 str_append(target, h6_end, sizeof(h6_end) - 1);
463 str_append_str(target, parser->line_ending);
464 wiki_dedent(parser, false);
468 str_append(target, h5_end, sizeof(h5_end) - 1);
469 str_append_str(target, parser->line_ending);
470 wiki_dedent(parser, false);
474 str_append(target, h4_end, sizeof(h4_end) - 1);
475 str_append_str(target, parser->line_ending);
476 wiki_dedent(parser, false);
480 str_append(target, h3_end, sizeof(h3_end) - 1);
481 str_append_str(target, parser->line_ending);
482 wiki_dedent(parser, false);
486 str_append(target, h2_end, sizeof(h2_end) - 1);
487 str_append_str(target, parser->line_ending);
488 wiki_dedent(parser, false);
492 str_append(target, h1_end, sizeof(h1_end) - 1);
493 str_append_str(target, parser->line_ending);
494 wiki_dedent(parser, false);
498 // not an HTML tag; so nothing to emit
502 // not an HTML tag; so nothing to emit
506 // not an HTML tag; so nothing to emit
510 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
514 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
518 str_append(target, p_end, sizeof(p_end) - 1);
519 str_append_str(target, parser->line_ending);
520 wiki_dedent(parser, false);
528 // should probably raise an exception here
531 ary_pop(parser->scope);
534 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
535 // If including is true then the item itself is also popped.
536 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
537 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
539 int continue_looping = 1;
542 int top = ary_entry(parser->scope, -1);
549 continue_looping = 0;
551 wiki_pop_from_stack(parser, target);
552 } while (continue_looping);
555 void wiki_pop_all_from_stack(parser_t *parser)
557 for (int i = 0, max = parser->scope->count; i < max; i++)
558 wiki_pop_from_stack(parser, NULL);
561 void wiki_start_para_if_necessary(parser_t *parser)
566 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
567 if (parser->scope->count == 0 ||
568 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
569 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
572 str_append(parser->output, p_start, sizeof(p_start) - 1);
573 ary_push(parser->scope, P);
574 ary_push(parser->line, P);
576 else if (parser->pending_crlf)
579 // already in a paragraph block; convert pending CRLF into a space
580 str_append(parser->output, space, sizeof(space) - 1);
582 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
583 str_append_str(parser->output, parser->line_ending);
585 parser->pending_crlf = false;
588 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
590 if (parser->pending_crlf)
592 str_append_str(parser->output, parser->line_ending);
593 parser->pending_crlf = false;
597 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
598 // For example, given input like:
603 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
604 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
609 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
610 // but not on the line scope:
615 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
616 // on the line scope.
617 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
618 // entering the for loop.
619 void wiki_pop_excess_elements(parser_t *parser)
623 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
625 // special case for last item on scope
628 // don't auto-pop P if it is only item on scope
629 if (ary_entry(parser->scope, -1) == P)
631 // add P to the line scope to prevent us entering the loop at all next time around
632 ary_push(parser->line, P);
636 wiki_pop_from_stack(parser, NULL);
640 // Convert a single UTF-8 codepoint to UTF-32
642 // Expects an input buffer, src, containing a UTF-8 encoded character (which
643 // may be multi-byte). The end of the input buffer, end, is also passed in to
644 // allow the detection of invalidly truncated codepoints. The number of bytes
645 // in the UTF-8 character (between 1 and 4) is returned by reference in
648 // Raises a RangeError if the supplied character is invalid UTF-8.
649 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
652 if ((unsigned char)src[0] <= 0x7f)
658 else if ((src[0] & 0xe0) == 0xc0)
660 // byte starts with 110..... : this should be a two-byte sequence
663 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
664 else if (((unsigned char)src[0] == 0xc0) ||
665 ((unsigned char)src[0] == 0xc1))
666 // overlong encoding: lead byte of 110..... but code point <= 127
667 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
668 else if ((src[1] & 0xc0) != 0x80 )
669 // should have second byte starting with 10......
670 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
673 ((uint32_t)(src[0] & 0x1f)) << 6 |
677 else if ((src[0] & 0xf0) == 0xe0)
679 // byte starts with 1110.... : this should be a three-byte sequence
681 // missing second or third byte
682 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
683 else if (((src[1] & 0xc0) != 0x80 ) ||
684 ((src[2] & 0xc0) != 0x80 ))
685 // should have second and third bytes starting with 10......
686 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
689 ((uint32_t)(src[0] & 0x0f)) << 12 |
690 ((uint32_t)(src[1] & 0x3f)) << 6 |
694 else if ((src[0] & 0xf8) == 0xf0)
696 // bytes starts with 11110... : this should be a four-byte sequence
698 // missing second, third, or fourth byte
699 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
700 else if ((unsigned char)src[0] >= 0xf5 &&
701 (unsigned char)src[0] <= 0xf7)
702 // disallowed by RFC 3629 (codepoints above 0x10ffff)
703 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
704 else if (((src[1] & 0xc0) != 0x80 ) ||
705 ((src[2] & 0xc0) != 0x80 ) ||
706 ((src[3] & 0xc0) != 0x80 ))
707 // should have second and third bytes starting with 10......
708 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
711 ((uint32_t)(src[0] & 0x07)) << 18 |
712 ((uint32_t)(src[1] & 0x3f)) << 12 |
713 ((uint32_t)(src[1] & 0x3f)) << 6 |
718 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
722 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
724 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
725 char scratch = (character & 0xf000) >> 12;
726 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
727 scratch = (character & 0x0f00) >> 8;
728 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
729 scratch = (character & 0x00f0) >> 4;
730 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
731 scratch = character & 0x000f;
732 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
733 str_append(output, hex_string, sizeof(hex_string));
736 // trim parser->link_text in place
737 void wiki_trim_link_text(parser_t *parser)
739 char *src = parser->link_text->ptr;
740 char *start = src; // remember this so we can check if we're at the start
742 char *non_space = src; // remember last non-space character output
743 char *end = src + parser->link_text->len;
755 if (left != start || non_space + 1 != end)
757 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
758 parser->link_text->len = (non_space + 1) - left;
759 memmove(parser->link_text->ptr, left, parser->link_text->len);
763 // - non-printable (non-ASCII) characters converted to numeric entities
764 // - QUOT and AMP characters converted to named entities
765 // - if trim is true, leading and trailing whitespace trimmed
766 // - if trim is false, there is no special treatment of spaces
767 void wiki_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
769 char *src = parser->link_target->ptr;
770 char *start = src; // remember this so we can check if we're at the start
771 char *non_space = output->ptr + output->len; // remember last non-space character output
772 char *end = src + parser->link_target->len;
775 // need at most 8 bytes to display each input character (�)
776 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
778 char *old_ptr = output->ptr;
779 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
780 if (old_ptr != output->ptr) // may have moved
781 non_space += output->ptr - old_ptr;
786 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
787 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
789 else if (*src == '&')
791 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
792 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
794 else if (*src == '<' || *src == '>')
795 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
796 else if (*src == ' ' && src == start && trim)
797 start++; // we eat leading space
798 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
800 *(output->ptr + output->len) = *src;
803 else // all others: must convert to entities
806 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
808 non_space = output->ptr + output->len;
812 non_space = output->ptr + output->len;
816 // trim trailing space if necessary
817 if (trim && output->ptr + output->len != non_space)
818 output->len -= (output->ptr + output->len) - non_space;
821 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
824 parser.link_target = str_new_from_string(string);
825 GC_WRAP_STR(parser.link_target, link_target_gc);
826 str_t *output = str_new();
827 GC_WRAP_STR(output, output_gc);
828 wiki_append_sanitized_link_target(&parser, output, true);
829 return string_from_str(output);
832 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
834 // Leading and trailing whitespace trimmed. Spaces are converted to
835 // underscores if the parser space_to_underscore member is true.
836 static void wiki_encode_link_target(parser_t *parser)
838 char *src = parser->link_target->ptr;
839 char *start = src; // remember this so we can check if we're at the start
840 long len = parser->link_target->len;
843 char *end = src + len;
844 long dest_len = len * 2;
845 char *dest = ALLOC_N(char, dest_len);
846 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
847 char *non_space = dest; // remember last non-space character output
848 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
849 for (; src < end; src++)
851 // worst case: a single character may grow to 3 characters once encoded
852 if ((dest + 3) > (dest_ptr + dest_len))
854 // outgrowing buffer, must reallocate
855 char *old_dest = dest;
856 char *old_dest_ptr = dest_ptr;
858 dest = realloc(dest_ptr, dest_len);
861 // would have used reallocf, but this has to run on Linux too, not just Darwin
863 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
866 dest = dest_ptr + (old_dest - old_dest_ptr);
867 non_space = dest_ptr + (non_space - old_dest_ptr);
870 // pass through unreserved characters
871 if ((*src >= 'a' && *src <= 'z') ||
872 (*src >= 'A' && *src <= 'Z') ||
873 (*src >= '0' && *src <= '9') ||
882 else if (*src == ' ' && src == start)
883 start++; // we eat leading space
884 else if (*src == ' ' && parser->space_to_underscore)
886 else // everything else gets URL-encoded
889 *dest++ = hex[(unsigned char)(*src) / 16]; // left
890 *dest++ = hex[(unsigned char)(*src) % 16]; // right
896 // trim trailing space if necessary
897 if (non_space > dest_ptr && dest != non_space)
898 dest_len = non_space - dest_ptr;
900 dest_len = dest - dest_ptr;
901 str_clear(parser->link_target);
902 str_append(parser->link_target, dest_ptr, dest_len);
906 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
909 parser.space_to_underscore = false;
910 parser.link_target = str_new_from_string(in);
911 GC_WRAP_STR(parser.link_target, link_target_gc);
912 wiki_encode_link_target(&parser);
913 return string_from_str(parser.link_target);
916 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
917 // returns 0 (false) otherwise
918 bool wiki_blank(str_t *str)
922 for (char *ptr = str->ptr,
923 *end = str->ptr + str->len;
932 void wiki_rollback_failed_internal_link(parser_t *parser)
935 return; // nothing to do!
936 int scope_includes_separator = IN(SEPARATOR);
937 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
938 str_append(parser->output, link_start, sizeof(link_start) - 1);
939 if (parser->link_target->len > 0)
941 wiki_append_sanitized_link_target(parser, parser->output, false);
942 if (scope_includes_separator)
944 str_append(parser->output, separator, sizeof(separator) - 1);
945 if (parser->link_text->len > 0)
946 str_append_str(parser->output, parser->link_text);
949 parser->capture = NULL;
950 str_clear(parser->link_target);
951 str_clear(parser->link_text);
954 void wiki_rollback_failed_external_link(parser_t *parser)
956 if (!IN(EXT_LINK_START))
957 return; // nothing to do!
959 // store a couple of values before popping
960 int scope_includes_space = IN(SPACE);
961 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
962 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
964 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
965 if (parser->link_target->len > 0)
967 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
968 if (scope_includes_space)
970 str_append(parser->output, space, sizeof(space) - 1);
971 if (parser->link_text->len > 0)
972 str_append_str(parser->output, parser->link_text);
975 parser->capture = NULL;
976 str_clear(parser->link_target);
977 str_clear(parser->link_text);
980 void wiki_rollback_failed_link(parser_t *parser)
982 wiki_rollback_failed_internal_link(parser);
983 wiki_rollback_failed_external_link(parser);
986 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
990 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
994 VALUE autolink = Qtrue;
995 VALUE line_ending = rb_str_new2("\n");
996 VALUE external_link_class = rb_str_new2("external");
997 VALUE mailto_class = rb_str_new2("mailto");
998 VALUE internal_link_prefix = rb_str_new2("/wiki/");
999 VALUE img_prefix = rb_str_new2("/images/");
1000 VALUE output_style = ID2SYM(rb_intern("html"));
1001 VALUE space_to_underscore = Qtrue;
1002 VALUE minimum_fulltext_token_length = INT2NUM(3);
1003 VALUE base_heading_level = INT2NUM(0);
1005 // process options hash (override defaults)
1006 if (!NIL_P(options) && TYPE(options) == T_HASH)
1008 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1009 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1010 autolink = OVERRIDE_IF_SET(autolink);
1011 line_ending = OVERRIDE_IF_SET(line_ending);
1012 external_link_class = OVERRIDE_IF_SET(external_link_class);
1013 mailto_class = OVERRIDE_IF_SET(mailto_class);
1014 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1015 img_prefix = OVERRIDE_IF_SET(img_prefix);
1016 output_style = OVERRIDE_IF_SET(output_style);
1017 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1018 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1019 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1022 // no need to call super here; rb_call_super()
1023 rb_iv_set(self, "@autolink", autolink);
1024 rb_iv_set(self, "@line_ending", line_ending);
1025 rb_iv_set(self, "@external_link_class", external_link_class);
1026 rb_iv_set(self, "@mailto_class", mailto_class);
1027 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1028 rb_iv_set(self, "@img_prefix", img_prefix);
1029 rb_iv_set(self, "@output_style", output_style);
1030 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1031 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1032 rb_iv_set(self, "@base_heading_level", base_heading_level);
1036 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1038 for (int i = 0; i < 100000; i++)
1039 Wikitext_parser_parse(1, &string, self);
1043 // convert a Ruby object (:xml, :html etc) into an int output style
1044 int Wikitext_output_style(VALUE output)
1046 if (TYPE(output) == T_SYMBOL)
1048 if (SYM2ID(output) == rb_intern("xml"))
1051 return HTML_OUTPUT; // fall back to default
1054 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1056 // process arguments
1057 VALUE string, options;
1058 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1062 string = StringValue(string);
1064 // access these once per parse
1065 VALUE line_ending = rb_iv_get(self, "@line_ending");
1066 line_ending = StringValue(line_ending);
1067 VALUE link_class = rb_iv_get(self, "@external_link_class");
1068 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1069 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1070 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1071 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1072 int output_style = Wikitext_output_style(rb_iv_get(self, "@output_style"));
1074 // process options hash
1075 int base_indent = 0;
1076 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1077 VALUE link_proc = Qnil;
1078 if (!NIL_P(options) && TYPE(options) == T_HASH)
1080 // :indent => 0 (or more)
1081 ID has_key = rb_intern("has_key?");
1082 ID id = ID2SYM(rb_intern("indent"));
1083 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1085 VALUE indent = rb_hash_aref(options, id);
1086 if (indent == Qfalse)
1087 base_indent = -1; // indentation disabled
1090 base_indent = NUM2INT(indent);
1091 if (base_indent < 0)
1096 // :base_heading_level => 0/1/2/3/4/5/6
1097 id = ID2SYM(rb_intern("base_heading_level"));
1098 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1099 base_heading_level = NUM2INT(rb_hash_aref(options, id));
1101 // :output_style => :html/:xml
1102 id = ID2SYM(rb_intern("output_style"));
1103 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1104 output_style = Wikitext_output_style(rb_hash_aref(options, id));
1106 // :link_proc => lambda { |link_target| ... }
1107 id = ID2SYM(rb_intern("link_proc"));
1108 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1109 link_proc = rb_hash_aref(options, id);
1112 // normalize, regardless of whether this came from instance variable or override
1113 if (base_heading_level < 0)
1114 base_heading_level = 0;
1115 if (base_heading_level > 6)
1116 base_heading_level = 6;
1119 char *p = RSTRING_PTR(string);
1120 long len = RSTRING_LEN(string);
1123 // set up parser struct to make passing parameters a little easier
1124 parser_t *parser = parser_new();
1125 GC_WRAP_PARSER(parser, parser_gc);
1126 parser->external_link_class = link_class;
1127 parser->mailto_class = mailto_class;
1128 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1129 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1130 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1131 parser->line_ending = str_new_from_string(line_ending);
1132 parser->base_indent = base_indent;
1133 parser->base_heading_level = base_heading_level;
1134 parser->output_style = output_style;
1136 // this simple looping design leads to a single enormous function,
1137 // but it's faster than doing actual recursive descent and also secure in the face of
1138 // malicious input that seeks to overflow the stack
1139 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1140 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1141 // than a straightforward looping translator like this one anyway
1143 _token.type = NO_TOKEN;
1144 token_t *token = NULL;
1147 // note that whenever we grab a token we push it into the line buffer
1148 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1149 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1151 // check to see if we have a token hanging around from a previous iteration of this loop
1154 if (_token.type == NO_TOKEN)
1156 // first time here (haven't started scanning yet)
1158 next_token(token, NULL, p, pe);
1159 ary_push(parser->line_buffer, token->type);
1165 int type = token->type;
1167 // can't declare new variables inside a switch statement, so predeclare them here
1168 long remove_strong = -1;
1169 long remove_em = -1;
1171 // general purpose counters, flags and pointers
1175 str_t *output = NULL;
1177 str_t *token_str = &_token_str;
1179 // The following giant switch statement contains cases for all the possible token types.
1180 // In the most basic sense we are emitting the HTML that corresponds to each token,
1181 // but some tokens require context information in order to decide what to output.
1182 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1183 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1185 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1186 // - the line buffer (records tokens seen so far on the current line)
1187 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1189 // Although this is fairly complicated, there is one key simplifying factor:
1190 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1191 // scope stack (up to the current token) is valid; our translator can take this as a given.
1192 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1193 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1197 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1199 str_append(parser->output, space, sizeof(space) - 1);
1202 else if (IN(BLOCKQUOTE_START))
1204 // this kind of nesting not allowed (to avoid user confusion)
1205 wiki_pop_excess_elements(parser);
1206 wiki_start_para_if_necessary(parser);
1207 output = parser->capture ? parser->capture : parser->output;
1208 str_append(output, space, sizeof(space) - 1);
1212 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1213 ary_push(parser->line, PRE);
1214 i = ary_count(parser->line, BLOCKQUOTE);
1215 j = ary_count(parser->scope, BLOCKQUOTE);
1218 // must pop (reduce nesting level)
1219 for (i = j - i; i > 0; i--)
1220 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1225 parser->pending_crlf = false;
1226 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1227 wiki_indent(parser);
1228 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1229 ary_push(parser->scope, PRE);
1234 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1236 wiki_emit_pending_crlf_if_necessary(parser);
1237 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1239 else if (IN(BLOCKQUOTE_START))
1241 wiki_rollback_failed_link(parser); // if any
1242 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1243 wiki_append_pre_start(parser, token);
1245 else if (IN(BLOCKQUOTE))
1247 if (token->column_start == 1) // only allowed in first column
1249 wiki_rollback_failed_link(parser); // if any
1250 wiki_pop_all_from_stack(parser);
1251 wiki_append_pre_start(parser, token);
1253 else // PRE_START illegal here
1255 output = parser->capture ? parser->capture : parser->output;
1256 wiki_pop_excess_elements(parser);
1257 wiki_start_para_if_necessary(parser);
1258 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1263 wiki_rollback_failed_link(parser); // if any
1264 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1265 wiki_append_pre_start(parser, token);
1270 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1272 wiki_emit_pending_crlf_if_necessary(parser);
1273 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1278 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1281 output = parser->capture ? parser->capture : parser->output;
1282 wiki_pop_excess_elements(parser);
1283 wiki_start_para_if_necessary(parser);
1284 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1290 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1291 // no need to check for <pre>; can never appear inside it
1292 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1293 else if (IN(BLOCKQUOTE_START))
1295 // this kind of nesting not allowed (to avoid user confusion)
1296 wiki_pop_excess_elements(parser);
1297 wiki_start_para_if_necessary(parser);
1298 output = parser->capture ? parser->capture : parser->output;
1299 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1304 ary_push(parser->line, BLOCKQUOTE);
1306 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1307 i = ary_count(parser->line, BLOCKQUOTE);
1308 j = ary_count(parser->scope, BLOCKQUOTE);
1310 // 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
1311 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1313 ary_push(parser->line, BLOCKQUOTE);
1317 // now decide whether to push, pop or do nothing
1320 // must push (increase nesting level)
1321 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1322 for (i = i - j; i > 0; i--)
1324 wiki_indent(parser);
1325 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1326 str_append_str(parser->output, parser->line_ending);
1327 ary_push(parser->scope, BLOCKQUOTE);
1332 // must pop (reduce nesting level)
1333 for (i = j - i; i > 0; i--)
1334 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1337 // jump to top of the loop to process token we scanned during lookahead
1342 case BLOCKQUOTE_START:
1343 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1345 wiki_emit_pending_crlf_if_necessary(parser);
1346 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1348 else if (IN(BLOCKQUOTE_START))
1350 // nesting is fine here
1351 wiki_rollback_failed_link(parser); // if any
1352 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1353 wiki_indent(parser);
1354 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1355 str_append_str(parser->output, parser->line_ending);
1356 ary_push(parser->scope, BLOCKQUOTE_START);
1357 ary_push(parser->line, BLOCKQUOTE_START);
1359 else if (IN(BLOCKQUOTE))
1361 if (token->column_start == 1) // only allowed in first column
1363 wiki_rollback_failed_link(parser); // if any
1364 wiki_pop_all_from_stack(parser);
1365 wiki_indent(parser);
1366 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1367 str_append_str(parser->output, parser->line_ending);
1368 ary_push(parser->scope, BLOCKQUOTE_START);
1369 ary_push(parser->line, BLOCKQUOTE_START);
1371 else // BLOCKQUOTE_START illegal here
1373 output = parser->capture ? parser->capture : parser->output;
1374 wiki_pop_excess_elements(parser);
1375 wiki_start_para_if_necessary(parser);
1376 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1381 // would be nice to eliminate the repetition here but it's probably the clearest way
1382 wiki_rollback_failed_link(parser); // if any
1383 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1384 wiki_indent(parser);
1385 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1386 str_append_str(parser->output, parser->line_ending);
1387 ary_push(parser->scope, BLOCKQUOTE_START);
1388 ary_push(parser->line, BLOCKQUOTE_START);
1392 case BLOCKQUOTE_END:
1393 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1395 wiki_emit_pending_crlf_if_necessary(parser);
1396 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1400 if (IN(BLOCKQUOTE_START))
1401 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1404 output = parser->capture ? parser->capture : parser->output;
1405 wiki_pop_excess_elements(parser);
1406 wiki_start_para_if_necessary(parser);
1407 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1413 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1415 wiki_emit_pending_crlf_if_necessary(parser);
1416 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1420 wiki_pop_excess_elements(parser);
1421 wiki_start_para_if_necessary(parser);
1422 ary_push(parser->scope, NO_WIKI_START);
1423 ary_push(parser->line, NO_WIKI_START);
1428 if (IN(NO_WIKI_START))
1429 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1430 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1433 wiki_pop_excess_elements(parser);
1434 wiki_start_para_if_necessary(parser);
1435 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_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, literal_strong_em, sizeof(literal_strong_em) - 1);
1447 output = parser->capture ? parser->capture : parser->output;
1448 wiki_pop_excess_elements(parser);
1450 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1451 // otherwise, must open them
1454 j = parser->scope->count;
1455 for (j = j - 1; j >= 0; j--)
1457 int val = ary_entry(parser->scope, j);
1458 if (val == STRONG || val == STRONG_START)
1460 str_append(output, strong_end, sizeof(strong_end) - 1);
1463 else if (val == EM || val == EM_START)
1465 str_append(output, em_end, sizeof(em_end) - 1);
1470 if (remove_strong > remove_em) // must remove strong first
1472 ary_pop(parser->scope);
1474 ary_pop(parser->scope);
1475 else // there was no em to remove!, so consider this an opening em tag
1477 str_append(output, em_start, sizeof(em_start) - 1);
1478 ary_push(parser->scope, EM);
1479 ary_push(parser->line, EM);
1482 else if (remove_em > remove_strong) // must remove em first
1484 ary_pop(parser->scope);
1485 if (remove_strong > -1)
1486 ary_pop(parser->scope);
1487 else // there was no strong to remove!, so consider this an opening strong tag
1489 str_append(output, strong_start, sizeof(strong_start) - 1);
1490 ary_push(parser->scope, STRONG);
1491 ary_push(parser->line, STRONG);
1494 else // no strong or em to remove, so this must be a new opening of both
1496 wiki_start_para_if_necessary(parser);
1497 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1498 ary_push(parser->scope, STRONG);
1499 ary_push(parser->line, STRONG);
1500 ary_push(parser->scope, EM);
1501 ary_push(parser->line, EM);
1506 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1508 wiki_emit_pending_crlf_if_necessary(parser);
1509 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1513 output = parser->capture ? parser->capture : parser->output;
1514 if (IN(STRONG_START))
1515 // already in span started with <strong>, no choice but to emit this literally
1516 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1517 else if (IN(STRONG))
1518 // STRONG already seen, this is a closing tag
1519 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1522 // this is a new opening
1523 wiki_pop_excess_elements(parser);
1524 wiki_start_para_if_necessary(parser);
1525 str_append(output, strong_start, sizeof(strong_start) - 1);
1526 ary_push(parser->scope, STRONG);
1527 ary_push(parser->line, STRONG);
1533 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1535 wiki_emit_pending_crlf_if_necessary(parser);
1536 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1540 output = parser->capture ? parser->capture : parser->output;
1541 if (IN_EITHER_OF(STRONG_START, STRONG))
1542 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1545 wiki_pop_excess_elements(parser);
1546 wiki_start_para_if_necessary(parser);
1547 str_append(output, strong_start, sizeof(strong_start) - 1);
1548 ary_push(parser->scope, STRONG_START);
1549 ary_push(parser->line, STRONG_START);
1555 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1557 wiki_emit_pending_crlf_if_necessary(parser);
1558 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1562 output = parser->capture ? parser->capture : parser->output;
1563 if (IN(STRONG_START))
1564 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1567 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1568 wiki_pop_excess_elements(parser);
1569 wiki_start_para_if_necessary(parser);
1570 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1576 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1578 wiki_emit_pending_crlf_if_necessary(parser);
1579 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1583 output = parser->capture ? parser->capture : parser->output;
1585 // already in span started with <em>, no choice but to emit this literally
1586 str_append(output, literal_em, sizeof(literal_em) - 1);
1588 // EM already seen, this is a closing tag
1589 wiki_pop_from_stack_up_to(parser, output, EM, true);
1592 // this is a new opening
1593 wiki_pop_excess_elements(parser);
1594 wiki_start_para_if_necessary(parser);
1595 str_append(output, em_start, sizeof(em_start) - 1);
1596 ary_push(parser->scope, EM);
1597 ary_push(parser->line, EM);
1603 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1605 wiki_emit_pending_crlf_if_necessary(parser);
1606 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1610 output = parser->capture ? parser->capture : parser->output;
1611 if (IN_EITHER_OF(EM_START, EM))
1612 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1615 wiki_pop_excess_elements(parser);
1616 wiki_start_para_if_necessary(parser);
1617 str_append(output, em_start, sizeof(em_start) - 1);
1618 ary_push(parser->scope, EM_START);
1619 ary_push(parser->line, EM_START);
1625 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1627 wiki_emit_pending_crlf_if_necessary(parser);
1628 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1632 output = parser->capture ? parser->capture : parser->output;
1634 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1637 // no EM_START in scope, so must interpret the EM_END without any special meaning
1638 wiki_pop_excess_elements(parser);
1639 wiki_start_para_if_necessary(parser);
1640 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1646 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1648 wiki_emit_pending_crlf_if_necessary(parser);
1649 str_append(parser->output, backtick, sizeof(backtick) - 1);
1653 output = parser->capture ? parser->capture : parser->output;
1655 // already in span started with <tt>, no choice but to emit this literally
1656 str_append(output, backtick, sizeof(backtick) - 1);
1658 // TT (`) already seen, this is a closing tag
1659 wiki_pop_from_stack_up_to(parser, output, TT, true);
1662 // this is a new opening
1663 wiki_pop_excess_elements(parser);
1664 wiki_start_para_if_necessary(parser);
1665 str_append(output, code_start, sizeof(code_start) - 1);
1666 ary_push(parser->scope, TT);
1667 ary_push(parser->line, TT);
1673 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1675 wiki_emit_pending_crlf_if_necessary(parser);
1676 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1680 output = parser->capture ? parser->capture : parser->output;
1681 if (IN_EITHER_OF(TT_START, TT))
1682 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1685 wiki_pop_excess_elements(parser);
1686 wiki_start_para_if_necessary(parser);
1687 str_append(output, code_start, sizeof(code_start) - 1);
1688 ary_push(parser->scope, TT_START);
1689 ary_push(parser->line, TT_START);
1695 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1697 wiki_emit_pending_crlf_if_necessary(parser);
1698 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1702 output = parser->capture ? parser->capture : parser->output;
1704 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1707 // no TT_START in scope, so must interpret the TT_END without any special meaning
1708 wiki_pop_excess_elements(parser);
1709 wiki_start_para_if_necessary(parser);
1710 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1717 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1719 // no need to check for PRE; can never appear inside it
1720 str_append(parser->output, token->start, TOKEN_LEN(token));
1724 // count number of tokens in line and scope stacks
1725 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1726 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1727 j = parser->scope->count - bq_count;
1730 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1734 if (type == OL || type == UL)
1737 if (i - k >= 2) // already seen at least one OL or UL
1739 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1744 ary_push(parser->line, type);
1745 ary_push(parser->line, LI);
1747 // want to compare line with scope but can only do so if scope has enough items on it
1750 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1751 ary_entry(parser->scope, i + bq_count - 1) == LI)
1753 // line and scope match at this point: do nothing yet
1757 // item just pushed onto line does not match corresponding slot of scope!
1758 for (; j >= i - 2; j--)
1759 // must pop back before emitting
1760 wiki_pop_from_stack(parser, NULL);
1762 // will emit UL or OL, then LI
1766 else // line stack size now exceeds scope stack size: must increase nesting level
1767 break; // will emit UL or OL, then LI
1771 // not a OL or UL token!
1773 // must close existing LI and re-open new one
1774 wiki_pop_from_stack(parser, NULL);
1777 // item just pushed onto line does not match corresponding slot of scope!
1779 // must pop back before emitting
1780 wiki_pop_from_stack(parser, NULL);
1788 if (type == OL || type == UL)
1790 // if LI is at the top of a stack this is the start of a nested list
1791 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1793 // so we should precede it with a CRLF, and indicate that it's a nested list
1794 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1795 ary_push(parser->scope, NESTED_LIST);
1799 // this is a new list
1800 if (IN(BLOCKQUOTE_START))
1801 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1803 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1807 wiki_indent(parser);
1809 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1810 else if (type == UL)
1811 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1812 ary_push(parser->scope, type);
1813 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1815 else if (type == SPACE)
1816 // silently throw away the optional SPACE token after final list marker
1819 wiki_indent(parser);
1820 str_append(parser->output, li_start, sizeof(li_start) - 1);
1821 ary_push(parser->scope, LI);
1823 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1824 if (type == OL || type == UL)
1827 while (k++, NEXT_TOKEN(), (type = token->type))
1829 if (type == OL || type == UL)
1830 str_append(parser->output, token->start, TOKEN_LEN(token));
1831 else if (type == SPACE && k == 1)
1833 // silently throw away the optional SPACE token after final list marker
1842 // jump to top of the loop to process token we scanned during lookahead
1851 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1853 // no need to check for PRE; can never appear inside it
1854 str_append(parser->output, token->start, TOKEN_LEN(token));
1858 // pop up to but not including the last BLOCKQUOTE on the scope stack
1859 if (IN(BLOCKQUOTE_START))
1860 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1862 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1864 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1865 ary_push(parser->line, type);
1866 i = ary_count(parser->line, BLOCKQUOTE);
1867 j = ary_count(parser->scope, BLOCKQUOTE);
1869 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1872 // must pop (reduce nesting level)
1873 for (i = j - i; i > 0; i--)
1874 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1877 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1878 while (NEXT_TOKEN(), (token->type == SPACE))
1881 ary_push(parser->scope, type);
1882 wiki_indent(parser);
1884 // take base_heading_level into account
1885 type += base_heading_level;
1886 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1889 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1890 if (type == H6_START)
1891 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1892 else if (type == H5_START)
1893 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1894 else if (type == H4_START)
1895 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1896 else if (type == H3_START)
1897 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1898 else if (type == H2_START)
1899 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1900 else if (type == H1_START)
1901 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1903 // jump to top of the loop to process token we scanned during lookahead
1912 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1914 wiki_emit_pending_crlf_if_necessary(parser);
1915 str_append(parser->output, token->start, TOKEN_LEN(token));
1919 wiki_rollback_failed_external_link(parser); // if any
1920 if ((type == H6_END && !IN(H6_START)) ||
1921 (type == H5_END && !IN(H5_START)) ||
1922 (type == H4_END && !IN(H4_START)) ||
1923 (type == H3_END && !IN(H3_START)) ||
1924 (type == H2_END && !IN(H2_START)) ||
1925 (type == H1_END && !IN(H1_START)))
1927 // literal output only if not in appropriate scope (we stay silent in that case)
1928 wiki_start_para_if_necessary(parser);
1929 str_append(parser->output, token->start, TOKEN_LEN(token));
1935 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1937 wiki_emit_pending_crlf_if_necessary(parser);
1938 str_append(parser->output, token->start, TOKEN_LEN(token));
1942 wiki_pop_excess_elements(parser);
1943 wiki_start_para_if_necessary(parser);
1944 token_str->ptr = token->start;
1945 token_str->len = TOKEN_LEN(token);
1946 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
1951 if (IN(NO_WIKI_START))
1952 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1953 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1954 str_append(parser->output, token->start, TOKEN_LEN(token));
1955 else if (IN(LINK_START))
1957 // if the URI were allowed it would have been handled already in LINK_START
1958 wiki_rollback_failed_internal_link(parser);
1959 token_str->ptr = token->start;
1960 token_str->len = TOKEN_LEN(token);
1961 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1963 else if (IN(EXT_LINK_START))
1965 if (parser->link_target->len == 0)
1967 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1968 token_str->ptr = token->start;
1969 token_str->len = TOKEN_LEN(token);
1971 if (token->type == SPACE)
1973 ary_push(parser->scope, SPACE);
1974 str_append_str(parser->link_target, token_str);
1975 str_clear(parser->link_text);
1976 parser->capture = parser->link_text;
1977 token = NULL; // silently consume space
1981 // didn't see the space! this must be an error
1982 wiki_pop_from_stack(parser, NULL);
1983 wiki_pop_excess_elements(parser);
1984 wiki_start_para_if_necessary(parser);
1985 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1986 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1990 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1994 wiki_pop_excess_elements(parser);
1995 wiki_start_para_if_necessary(parser);
1996 token_str->ptr = token->start;
1997 token_str->len = TOKEN_LEN(token);
1998 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2003 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2004 str_append(parser->output, token->start, TOKEN_LEN(token));
2005 else if (IN(EXT_LINK_START))
2007 if (parser->link_target->len == 0)
2009 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2010 token_str->ptr = token->start;
2011 token_str->len = TOKEN_LEN(token);
2013 if (token->type == SPACE)
2015 ary_push(parser->scope, PATH);
2016 ary_push(parser->scope, SPACE);
2017 str_append_str(parser->link_target, token_str);
2018 str_clear(parser->link_text);
2019 parser->capture = parser->link_text;
2020 token = NULL; // silently consume space
2024 // didn't see the space! this must be an error
2025 wiki_pop_from_stack(parser, NULL);
2026 wiki_pop_excess_elements(parser);
2027 wiki_start_para_if_necessary(parser);
2028 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2029 str_append_str(parser->output, token_str);
2033 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2037 output = parser->capture ? parser->capture : parser->output;
2038 wiki_pop_excess_elements(parser);
2039 wiki_start_para_if_necessary(parser);
2040 str_append(output, token->start, TOKEN_LEN(token));
2044 // internal links (links to other wiki articles) look like this:
2045 // [[another article]] (would point at, for example, "/wiki/another_article")
2046 // [[the other article|the link text we'll use for it]]
2047 // [[the other article | the link text we'll use for it]]
2048 // MediaWiki has strict requirements about what it will accept as a link target:
2049 // all wikitext markup is disallowed:
2050 // example [[foo ''bar'' baz]]
2051 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2052 // example [[foo <em>bar</em> baz]]
2053 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2054 // example [[foo <nowiki>''</nowiki> baz]]
2055 // renders [[foo '' baz]] (ie. not a link)
2056 // example [[foo <bar> baz]]
2057 // renders [[foo <bar> baz]] (ie. not a link)
2058 // HTML entities and non-ASCII, however, make it through:
2059 // example [[foo €]]
2060 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2061 // example [[foo €]]
2062 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2063 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2064 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2065 // everything else will be rejected
2067 output = parser->capture ? parser->capture : parser->output;
2068 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2070 wiki_emit_pending_crlf_if_necessary(parser);
2071 str_append(output, link_start, sizeof(link_start) - 1);
2073 else if (IN(EXT_LINK_START))
2074 // already in external link scope! (and in fact, must be capturing link_text right now)
2075 str_append(output, link_start, sizeof(link_start) - 1);
2076 else if (IN(LINK_START))
2078 // already in internal link scope! this is a syntax error
2079 wiki_rollback_failed_internal_link(parser);
2080 str_append(parser->output, link_start, sizeof(link_start) - 1);
2082 else if (IN(SEPARATOR))
2084 // scanning internal link text
2086 else // not in internal link scope yet
2088 // will either emit a link, or the rollback of a failed link, so start the para now
2089 wiki_pop_excess_elements(parser);
2090 wiki_start_para_if_necessary(parser);
2091 ary_push(parser->scope, LINK_START);
2093 // look ahead and try to gobble up link target
2094 while (NEXT_TOKEN(), (type = token->type))
2096 if (type == SPACE ||
2097 type == SPECIAL_URI_CHARS ||
2099 type == PRINTABLE ||
2103 type == QUOT_ENTITY ||
2105 type == AMP_ENTITY ||
2106 type == IMG_START ||
2108 type == LEFT_CURLY ||
2109 type == RIGHT_CURLY)
2111 // accumulate these tokens into link_target
2112 if (parser->link_target->len == 0)
2114 str_clear(parser->link_target);
2115 parser->capture = parser->link_target;
2117 if (type == QUOT_ENTITY)
2118 // don't insert the entity, insert the literal quote
2119 str_append(parser->link_target, quote, sizeof(quote) - 1);
2120 else if (type == AMP_ENTITY)
2121 // don't insert the entity, insert the literal ampersand
2122 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2124 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2126 else if (type == LINK_END)
2128 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2129 wiki_rollback_failed_internal_link(parser);
2130 break; // jump back to top of loop (will handle this in LINK_END case below)
2132 else if (type == SEPARATOR)
2134 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2135 wiki_rollback_failed_internal_link(parser);
2138 ary_push(parser->scope, SEPARATOR);
2139 str_clear(parser->link_text);
2140 parser->capture = parser->link_text;
2145 else // unexpected token (syntax error)
2147 wiki_rollback_failed_internal_link(parser);
2148 break; // jump back to top of loop to handle unexpected token
2152 // jump to top of the loop to process token we scanned during lookahead (if any)
2158 output = parser->capture ? parser->capture : parser->output;
2159 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2161 wiki_emit_pending_crlf_if_necessary(parser);
2162 str_append(output, link_end, sizeof(link_end) - 1);
2164 else if (IN(EXT_LINK_START))
2165 // already in external link scope! (and in fact, must be capturing link_text right now)
2166 str_append(output, link_end, sizeof(link_end) - 1);
2167 else if (IN(LINK_START)) // in internal link scope!
2169 if (wiki_blank(parser->link_target))
2171 // special case for inputs like "[[ ]]"
2172 wiki_rollback_failed_internal_link(parser);
2173 str_append(parser->output, link_end, sizeof(link_end) - 1);
2176 if (parser->link_text->len == 0 ||
2177 wiki_blank(parser->link_text))
2179 // use link target as link text
2180 str_clear(parser->link_text);
2181 wiki_append_sanitized_link_target(parser, parser->link_text, true);
2184 wiki_trim_link_text(parser);
2186 // perform "redlink" check before manipulating link_target
2187 if (NIL_P(link_proc))
2191 j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
2194 VALUE l = j; // can't cast inside StringValue macro
2198 wiki_encode_link_target(parser);
2199 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2200 parser->capture = NULL;
2201 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, false);
2202 str_clear(parser->link_target);
2203 str_clear(parser->link_text);
2205 else // wasn't in internal link scope
2207 wiki_pop_excess_elements(parser);
2208 wiki_start_para_if_necessary(parser);
2209 str_append(output, link_end, sizeof(link_end) - 1);
2213 // external links look like this:
2214 // [http://google.com/ the link text]
2215 // [/other/page/on/site see this page]
2216 // strings in square brackets which don't match this syntax get passed through literally; eg:
2217 // he was very angery [sic] about the turn of events
2218 case EXT_LINK_START:
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_start, sizeof(ext_link_start) - 1);
2225 else if (IN(EXT_LINK_START))
2226 // already in external link scope! (and in fact, must be capturing link_text right now)
2227 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2228 else if (IN(LINK_START))
2230 // already in internal link scope!
2231 if (parser->link_target->len == 0 || !IN(SPACE))
2232 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2233 else // link target has already been scanned
2234 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2236 else // not in external link scope yet
2238 // will either emit a link, or the rollback of a failed link, so start the para now
2239 wiki_pop_excess_elements(parser);
2240 wiki_start_para_if_necessary(parser);
2242 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2244 if (token->type == URI || token->type == PATH)
2245 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2247 // only get here if there was a syntax error (missing URI)
2248 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2249 continue; // jump back to top of loop to handle token (either URI or whatever it is)
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_end, sizeof(ext_link_end) - 1);
2260 else if (IN(EXT_LINK_START))
2262 if (parser->link_text->len == 0)
2263 // syntax error: external link with no link text
2264 wiki_rollback_failed_external_link(parser);
2268 j = IN(PATH) ? Qnil : parser->external_link_class;
2269 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2270 parser->capture = NULL;
2271 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2273 str_clear(parser->link_target);
2274 str_clear(parser->link_text);
2278 wiki_pop_excess_elements(parser);
2279 wiki_start_para_if_necessary(parser);
2280 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2285 output = parser->capture ? parser->capture : parser->output;
2286 wiki_pop_excess_elements(parser);
2287 wiki_start_para_if_necessary(parser);
2288 str_append(output, separator, sizeof(separator) - 1);
2292 output = parser->capture ? parser->capture : parser->output;
2293 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2295 wiki_emit_pending_crlf_if_necessary(parser);
2296 str_append(output, token->start, TOKEN_LEN(token));
2300 // peek ahead to see next token
2301 char *token_ptr = token->start;
2302 int token_len = TOKEN_LEN(token);
2305 if ((type == H6_END && IN(H6_START)) ||
2306 (type == H5_END && IN(H5_START)) ||
2307 (type == H4_END && IN(H4_START)) ||
2308 (type == H3_END && IN(H3_START)) ||
2309 (type == H2_END && IN(H2_START)) ||
2310 (type == H1_END && IN(H1_START)))
2312 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2317 wiki_pop_excess_elements(parser);
2318 wiki_start_para_if_necessary(parser);
2319 str_append(output, token_ptr, token_len);
2322 // jump to top of the loop to process token we scanned during lookahead
2330 case DECIMAL_ENTITY:
2331 // pass these through unaltered as they are case sensitive
2332 output = parser->capture ? parser->capture : parser->output;
2333 wiki_pop_excess_elements(parser);
2334 wiki_start_para_if_necessary(parser);
2335 str_append(output, token->start, TOKEN_LEN(token));
2339 // normalize hex entities (downcase them)
2340 output = parser->capture ? parser->capture : parser->output;
2341 wiki_pop_excess_elements(parser);
2342 wiki_start_para_if_necessary(parser);
2343 str_append(output, token->start, TOKEN_LEN(token));
2344 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2348 output = parser->capture ? parser->capture : parser->output;
2349 wiki_pop_excess_elements(parser);
2350 wiki_start_para_if_necessary(parser);
2351 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2355 output = parser->capture ? parser->capture : parser->output;
2356 wiki_pop_excess_elements(parser);
2357 wiki_start_para_if_necessary(parser);
2358 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2362 output = parser->capture ? parser->capture : parser->output;
2363 wiki_pop_excess_elements(parser);
2364 wiki_start_para_if_necessary(parser);
2365 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2369 output = parser->capture ? parser->capture : parser->output;
2370 wiki_pop_excess_elements(parser);
2371 wiki_start_para_if_necessary(parser);
2372 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2376 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2378 wiki_emit_pending_crlf_if_necessary(parser);
2379 str_append(parser->output, token->start, TOKEN_LEN(token));
2381 else if (parser->capture)
2382 str_append(parser->capture, token->start, TOKEN_LEN(token));
2385 // not currently capturing: will be emitting something on success or failure, so get ready
2386 wiki_pop_excess_elements(parser);
2387 wiki_start_para_if_necessary(parser);
2389 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2390 // will cheat here and abuse the link_target capture buffer to accumulate text
2391 while (NEXT_TOKEN(), (type = token->type))
2393 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2394 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2395 else if (type == IMG_END && parser->link_target->len > 0)
2398 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2402 else // unexpected token or zero-length target (syntax error)
2405 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2406 if (parser->link_target->len > 0)
2407 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2412 // jump to top of the loop to process token we scanned during lookahead
2413 str_clear(parser->link_target);
2419 i = parser->pending_crlf;
2420 parser->pending_crlf = false;
2421 wiki_rollback_failed_link(parser); // if any
2422 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2424 ary_clear(parser->line_buffer);
2425 str_append_str(parser->output, parser->line_ending);
2430 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2431 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2432 // don't emit in this case
2433 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2436 if (ary_entry(parser->line_buffer, -2) == PRE)
2438 // only thing on line is the PRE: emit pending line ending (if we had one)
2440 str_append_str(parser->output, parser->line_ending);
2443 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2444 ary_clear(parser->line);
2445 ary_clear(parser->line_buffer);
2447 // peek ahead to see if this is definitely the end of the PRE block
2450 if (type != BLOCKQUOTE && type != PRE)
2451 // this is definitely the end of the block, so don't emit
2452 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2454 // potentially will emit
2455 parser->pending_crlf = true;
2457 continue; // jump back to top of loop to handle token grabbed via lookahead
2462 parser->pending_crlf = true;
2464 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2465 // as a side effect, this handles any open span-level elements and unclosed blocks
2466 // (with special handling for P blocks and LI elements)
2467 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2468 for (j = parser->scope->count; j > i; j--)
2470 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2472 parser->pending_crlf = false;
2476 // special handling on last iteration through the loop if the top item on the scope is a P block
2477 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2479 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2480 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2481 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2482 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2483 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2485 parser->pending_crlf = false;
2487 // not a paragraph break!
2490 wiki_pop_from_stack(parser, NULL);
2494 // delete the entire contents of the line scope stack and buffer
2495 ary_clear(parser->line);
2496 ary_clear(parser->line_buffer);
2499 case SPECIAL_URI_CHARS:
2505 output = parser->capture ? parser->capture : parser->output;
2506 wiki_pop_excess_elements(parser);
2507 wiki_start_para_if_necessary(parser);
2508 str_append(output, token->start, TOKEN_LEN(token));
2512 output = parser->capture ? parser->capture : parser->output;
2513 wiki_pop_excess_elements(parser);
2514 wiki_start_para_if_necessary(parser);
2515 wiki_append_entity_from_utf32_char(output, token->code_point);
2519 // special case for input like " foo\n " (see pre_spec.rb)
2521 ary_entry(parser->line_buffer, -2) == PRE &&
2522 parser->pending_crlf)
2523 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2525 // close any open scopes on hitting EOF
2526 wiki_rollback_failed_link(parser); // if any
2527 wiki_pop_all_from_stack(parser);
2528 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2534 // reset current token; forcing lexer to return another token at the top of the loop
2538 // nasty hack to avoid re-allocating our return value
2539 str_append(parser->output, null_str, 1); // null-terminate
2540 len = parser->output->len - 1; // don't count null termination
2542 #if defined(RUBY_1_9_x)
2543 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2544 free(RSTRING_PTR(out));
2545 RSTRING(out)->as.heap.aux.capa = len;
2546 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2547 RSTRING(out)->as.heap.len = len;
2548 #elif defined(RUBY_1_8_x)
2549 VALUE out = rb_str_new2("");
2550 free(RSTRING_PTR(out));
2551 RSTRING(out)->len = len;
2552 RSTRING(out)->aux.capa = len;
2553 RSTRING(out)->ptr = parser->output->ptr;
2555 #error unsupported RUBY_VERSION
2557 parser->output->ptr = NULL; // don't double-free