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)
34 // poor man's object orientation in C:
35 // instead of parsing around multiple parameters between functions in the parser
36 // we pack everything into a struct and pass around only a pointer to that
39 str_t *capture; // capturing to link_target, link_text, or NULL (direct to output, not capturing)
40 str_t *output; // for accumulating output to be returned
41 str_t *link_target; // short term "memory" for parsing links
42 str_t *link_text; // short term "memory" for parsing links
44 str_t *tabulation; // caching buffer for emitting indentation
45 ary_t *scope; // stack for tracking scope
46 ary_t *line; // stack for tracking scope as implied by current line
47 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
48 VALUE external_link_class; // CSS class applied to external links
49 VALUE mailto_class; // CSS class applied to email (mailto) links
50 VALUE img_prefix; // path prepended when emitting img tags
51 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
52 int current_indent; // fluctuates according to currently nested structures
53 int base_heading_level;
56 bool space_to_underscore;
59 const char null_str[] = { 0 };
60 const char escaped_no_wiki_start[] = "<nowiki>";
61 const char escaped_no_wiki_end[] = "</nowiki>";
62 const char literal_strong_em[] = "'''''";
63 const char literal_strong[] = "'''";
64 const char literal_em[] = "''";
65 const char escaped_em_start[] = "<em>";
66 const char escaped_em_end[] = "</em>";
67 const char escaped_strong_start[] = "<strong>";
68 const char escaped_strong_end[] = "</strong>";
69 const char escaped_tt_start[] = "<tt>";
70 const char escaped_tt_end[] = "</tt>";
71 const char literal_h6[] = "======";
72 const char literal_h5[] = "=====";
73 const char literal_h4[] = "====";
74 const char literal_h3[] = "===";
75 const char literal_h2[] = "==";
76 const char literal_h1[] = "=";
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 tt_start[] = "<tt>";
91 const char tt_end[] = "</tt>";
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=\"";
135 // Mark the parser struct designated by ptr as a participant in Ruby's
136 // mark-and-sweep garbage collection scheme. A variable named name is placed on
137 // the C stack to prevent the structure from being prematurely collected.
138 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
140 parser_t *parser_new(void)
142 parser_t *parser = ALLOC_N(parser_t, 1);
143 parser->capture = NULL; // not a real instance, pointer to other member's instance
144 parser->output = str_new();
145 parser->link_target = str_new();
146 parser->link_text = str_new();
147 parser->line_ending = NULL; // caller should set up
148 parser->tabulation = str_new();
149 parser->scope = ary_new();
150 parser->line = ary_new();
151 parser->line_buffer = ary_new();
152 parser->external_link_class = Qnil; // caller should set up
153 parser->mailto_class = Qnil; // caller should set up
154 parser->img_prefix = Qnil; // caller should set up
155 parser->base_indent = 0;
156 parser->current_indent = 0;
157 parser->base_heading_level = 0;
158 parser->pending_crlf = false;
159 parser->autolink = true;
160 parser->space_to_underscore = true;
164 void parser_free(parser_t *parser)
166 // we don't free parser->capture; it's just a redundant pointer
167 if (parser->output) str_free(parser->output);
168 if (parser->link_target) str_free(parser->link_target);
169 if (parser->link_text) str_free(parser->link_text);
170 if (parser->line_ending) str_free(parser->line_ending);
171 if (parser->tabulation) str_free(parser->tabulation);
172 if (parser->scope) ary_free(parser->scope);
173 if (parser->line) ary_free(parser->line);
174 if (parser->line_buffer) ary_free(parser->line_buffer);
178 // for testing and debugging only
179 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
183 string = StringValue(string);
184 VALUE tokens = rb_ary_new();
185 char *p = RSTRING_PTR(string);
186 long len = RSTRING_LEN(string);
189 next_token(&token, NULL, p, pe);
190 rb_ary_push(tokens, _Wikitext_token(&token));
191 while (token.type != END_OF_FILE)
193 next_token(&token, &token, NULL, pe);
194 rb_ary_push(tokens, _Wikitext_token(&token));
199 // for benchmarking raw tokenization speed only
200 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
204 string = StringValue(string);
205 char *p = RSTRING_PTR(string);
206 long len = RSTRING_LEN(string);
209 next_token(&token, NULL, p, pe);
210 while (token.type != END_OF_FILE)
211 next_token(&token, &token, NULL, pe);
215 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
218 VALUE string, options;
219 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
223 string = StringValue(string);
224 VALUE tokens = rb_ary_new();
226 // check instance variables
227 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
229 // process options hash (can override instance variables)
230 if (!NIL_P(options) && TYPE(options) == T_HASH)
232 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
233 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
235 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
240 char *p = RSTRING_PTR(string);
241 long len = RSTRING_LEN(string);
244 token_t *_token = &token;
245 next_token(&token, NULL, p, pe);
246 while (token.type != END_OF_FILE)
253 if (TOKEN_LEN(_token) >= min_len)
254 rb_ary_push(tokens, TOKEN_TEXT(_token));
257 // ignore everything else
260 next_token(&token, &token, NULL, pe);
265 // we downcase "in place", overwriting the original contents of the buffer
266 void _Wikitext_downcase_bang(char *ptr, long len)
268 for (long i = 0; i < len; i++)
270 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
275 // prepare hyperlink and append it to parser->output
276 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
277 // or merely the literal link target
278 // if link_text is Qnil, the link_target is re-used for the link text
279 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, bool check_autolink)
281 if (check_autolink && !parser->autolink)
282 str_append_str(parser->output, link_target);
285 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
286 if (!NIL_P(link_prefix))
287 str_append_string(parser->output, link_prefix);
288 str_append_str(parser->output, link_target);
290 // special handling for mailto URIs
291 const char *mailto = "mailto:";
292 if (NIL_P(link_prefix) &&
293 link_target->len >= (long)sizeof(mailto) &&
294 strncmp(mailto, link_target->ptr, sizeof(mailto)) == 0)
295 link_class = parser->mailto_class; // use mailto_class from parser
296 if (link_class != Qnil)
298 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
299 str_append_string(parser->output, link_class);
301 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
302 if (!link_text || link_text->len == 0) // re-use link_target
303 str_append_str(parser->output, link_target);
305 str_append_str(parser->output, link_text);
306 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
310 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
312 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
313 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
314 str_append_string(parser->output, parser->img_prefix);
315 str_append(parser->output, token_ptr, token_len);
316 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
317 str_append(parser->output, token_ptr, token_len);
318 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
321 // will emit indentation only if we are about to emit any of:
322 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
323 // each time we enter one of those spans must ++ the indentation level
324 void _Wikitext_indent(parser_t *parser)
326 if (parser->base_indent == -1) // indentation disabled
328 int space_count = parser->current_indent + parser->base_indent;
331 char *old_end, *new_end;
332 if (parser->tabulation->len < space_count)
333 str_grow(parser->tabulation, space_count); // reallocates if necessary
334 old_end = parser->tabulation->ptr + parser->tabulation->len;
335 new_end = parser->tabulation->ptr + space_count;
336 while (old_end < new_end)
338 if (space_count > parser->tabulation->len)
339 parser->tabulation->len = space_count;
340 str_append(parser->output, parser->tabulation->ptr, space_count);
342 parser->current_indent += 2;
345 void _Wikitext_dedent(parser_t *parser, bool emit)
347 if (parser->base_indent == -1) // indentation disabled
349 parser->current_indent -= 2;
352 int space_count = parser->current_indent + parser->base_indent;
354 str_append(parser->output, parser->tabulation->ptr, space_count);
357 // Pops a single item off the parser's scope stack.
358 // A corresponding closing tag is written to the target string.
359 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
360 void _Wikitext_pop_from_stack(parser_t *parser, str_t *target)
362 int top = ary_entry(parser->scope, -1);
366 target = parser->output;
368 // for headings, take base_heading_level into account
369 if (top >= H1_START && top <= H6_START)
371 top += parser->base_heading_level;
372 // no need to check for underflow (base_heading_level is never negative)
381 str_append(target, pre_end, sizeof(pre_end) - 1);
382 str_append_str(target, parser->line_ending);
383 _Wikitext_dedent(parser, false);
387 case BLOCKQUOTE_START:
388 _Wikitext_dedent(parser, true);
389 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
390 str_append_str(target, parser->line_ending);
394 // not a real HTML tag; so nothing to pop
399 str_append(target, strong_end, sizeof(strong_end) - 1);
404 str_append(target, em_end, sizeof(em_end) - 1);
409 str_append(target, tt_end, sizeof(tt_end) - 1);
413 _Wikitext_dedent(parser, true);
414 str_append(target, ol_end, sizeof(ol_end) - 1);
415 str_append_str(target, parser->line_ending);
419 _Wikitext_dedent(parser, true);
420 str_append(target, ul_end, sizeof(ul_end) - 1);
421 str_append_str(target, parser->line_ending);
425 // next token to pop will be a LI
426 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
427 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
428 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
429 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
430 _Wikitext_dedent(parser, true); // we really only want to emit the spaces
431 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
435 str_append(target, li_end, sizeof(li_end) - 1);
436 str_append_str(target, parser->line_ending);
437 _Wikitext_dedent(parser, false);
441 str_append(target, h6_end, sizeof(h6_end) - 1);
442 str_append_str(target, parser->line_ending);
443 _Wikitext_dedent(parser, false);
447 str_append(target, h5_end, sizeof(h5_end) - 1);
448 str_append_str(target, parser->line_ending);
449 _Wikitext_dedent(parser, false);
453 str_append(target, h4_end, sizeof(h4_end) - 1);
454 str_append_str(target, parser->line_ending);
455 _Wikitext_dedent(parser, false);
459 str_append(target, h3_end, sizeof(h3_end) - 1);
460 str_append_str(target, parser->line_ending);
461 _Wikitext_dedent(parser, false);
465 str_append(target, h2_end, sizeof(h2_end) - 1);
466 str_append_str(target, parser->line_ending);
467 _Wikitext_dedent(parser, false);
471 str_append(target, h1_end, sizeof(h1_end) - 1);
472 str_append_str(target, parser->line_ending);
473 _Wikitext_dedent(parser, false);
477 // not an HTML tag; so nothing to emit
481 // not an HTML tag; so nothing to emit
485 // not an HTML tag; so nothing to emit
489 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
493 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
497 str_append(target, p_end, sizeof(p_end) - 1);
498 str_append_str(target, parser->line_ending);
499 _Wikitext_dedent(parser, false);
507 // should probably raise an exception here
510 ary_pop(parser->scope);
513 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
514 // If including is true then the item itself is also popped.
515 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
516 void _Wikitext_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
518 int continue_looping = 1;
521 int top = ary_entry(parser->scope, -1);
528 continue_looping = 0;
530 _Wikitext_pop_from_stack(parser, target);
531 } while (continue_looping);
534 void _Wikitext_pop_all_from_stack(parser_t *parser)
536 for (int i = 0, max = parser->scope->count; i < max; i++)
537 _Wikitext_pop_from_stack(parser, NULL);
540 void _Wikitext_start_para_if_necessary(parser_t *parser)
545 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
546 if (parser->scope->count == 0 ||
547 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
548 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
550 _Wikitext_indent(parser);
551 str_append(parser->output, p_start, sizeof(p_start) - 1);
552 ary_push(parser->scope, P);
553 ary_push(parser->line, P);
555 else if (parser->pending_crlf)
558 // already in a paragraph block; convert pending CRLF into a space
559 str_append(parser->output, space, sizeof(space) - 1);
561 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
562 str_append_str(parser->output, parser->line_ending);
564 parser->pending_crlf = false;
567 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
569 if (parser->pending_crlf)
571 str_append_str(parser->output, parser->line_ending);
572 parser->pending_crlf = false;
576 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
577 // For example, given input like:
582 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
583 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
588 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
589 // but not on the line scope:
594 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
595 // on the line scope.
596 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
597 // entering the for loop.
598 void _Wikitext_pop_excess_elements(parser_t *parser)
602 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
604 // special case for last item on scope
607 // don't auto-pop P if it is only item on scope
608 if (ary_entry(parser->scope, -1) == P)
610 // add P to the line scope to prevent us entering the loop at all next time around
611 ary_push(parser->line, P);
615 _Wikitext_pop_from_stack(parser, NULL);
619 // Convert a single UTF-8 codepoint to UTF-32
621 // Expects an input buffer, src, containing a UTF-8 encoded character (which
622 // may be multi-byte). The end of the input buffer, end, is also passed in to
623 // allow the detection of invalidly truncated codepoints. The number of bytes
624 // in the UTF-8 character (between 1 and 4) is returned by reference in
627 // Raises a RangeError if the supplied character is invalid UTF-8.
628 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out)
631 if ((unsigned char)src[0] <= 0x7f)
637 else if ((src[0] & 0xe0) == 0xc0)
639 // byte starts with 110..... : this should be a two-byte sequence
642 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
643 else if (((unsigned char)src[0] == 0xc0) ||
644 ((unsigned char)src[0] == 0xc1))
645 // overlong encoding: lead byte of 110..... but code point <= 127
646 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
647 else if ((src[1] & 0xc0) != 0x80 )
648 // should have second byte starting with 10......
649 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
652 ((uint32_t)(src[0] & 0x1f)) << 6 |
656 else if ((src[0] & 0xf0) == 0xe0)
658 // byte starts with 1110.... : this should be a three-byte sequence
660 // missing second or third byte
661 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
662 else if (((src[1] & 0xc0) != 0x80 ) ||
663 ((src[2] & 0xc0) != 0x80 ))
664 // should have second and third bytes starting with 10......
665 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
668 ((uint32_t)(src[0] & 0x0f)) << 12 |
669 ((uint32_t)(src[1] & 0x3f)) << 6 |
673 else if ((src[0] & 0xf8) == 0xf0)
675 // bytes starts with 11110... : this should be a four-byte sequence
677 // missing second, third, or fourth byte
678 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
679 else if ((unsigned char)src[0] >= 0xf5 &&
680 (unsigned char)src[0] <= 0xf7)
681 // disallowed by RFC 3629 (codepoints above 0x10ffff)
682 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
683 else if (((src[1] & 0xc0) != 0x80 ) ||
684 ((src[2] & 0xc0) != 0x80 ) ||
685 ((src[3] & 0xc0) != 0x80 ))
686 // should have second and third bytes starting with 10......
687 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
690 ((uint32_t)(src[0] & 0x07)) << 18 |
691 ((uint32_t)(src[1] & 0x3f)) << 12 |
692 ((uint32_t)(src[1] & 0x3f)) << 6 |
697 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
701 void _Wikitext_append_entity_from_utf32_char(char *output, uint32_t character)
703 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
704 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
705 char scratch = (character & 0xf000) >> 12;
706 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
707 scratch = (character & 0x0f00) >> 8;
708 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
709 scratch = (character & 0x00f0) >> 4;
710 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
711 scratch = character & 0x000f;
712 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
713 memcpy(output, hex_string, sizeof(hex_string));
716 // trim parser->link_text in place
717 void _Wikitext_trim_link_text(parser_t *parser)
719 char *src = parser->link_text->ptr;
720 char *start = src; // remember this so we can check if we're at the start
722 char *non_space = src; // remember last non-space character output
723 char *end = src + parser->link_text->len;
735 if (left != start || non_space + 1 != end)
737 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
738 parser->link_text->len = (non_space + 1) - left;
739 memmove(parser->link_text->ptr, left, parser->link_text->len);
743 // - non-printable (non-ASCII) characters converted to numeric entities
744 // - QUOT and AMP characters converted to named entities
745 // - if trim is true, leading and trailing whitespace trimmed
746 // - if trim is false, there is no special treatment of spaces
747 void _Wikitext_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
749 char *src = parser->link_target->ptr;
750 char *start = src; // remember this so we can check if we're at the start
751 char *non_space = output->ptr + output->len; // remember last non-space character output
752 char *end = src + parser->link_target->len;
755 // need at most 8 bytes to display each input character (�)
756 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
758 char *old_ptr = output->ptr;
759 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
760 if (old_ptr != output->ptr) // may have moved
761 non_space += output->ptr - old_ptr;
766 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
767 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
769 else if (*src == '&')
771 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
772 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
774 else if (*src == '<' || *src == '>')
775 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
776 else if (*src == ' ' && src == start && trim)
777 start++; // we eat leading space
778 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
780 *(output->ptr + output->len) = *src;
783 else // all others: must convert to entities
786 _Wikitext_append_entity_from_utf32_char(output->ptr + output->len, _Wikitext_utf8_to_utf32(src, end, &width));
789 non_space = output->ptr + output->len;
793 non_space = output->ptr + output->len;
797 // trim trailing space if necessary
798 if (trim && output->ptr + output->len != non_space)
799 output->len -= (output->ptr + output->len) - non_space;
802 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
805 parser.link_target = str_new_from_string(string);
806 GC_WRAP_STR(parser.link_target, link_target_gc);
807 str_t *output = str_new();
808 GC_WRAP_STR(output, output_gc);
809 _Wikitext_append_sanitized_link_target(&parser, output, true);
810 return string_from_str(output);
813 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
815 // Leading and trailing whitespace trimmed. Spaces are converted to
816 // underscores if the parser space_to_underscore member is true.
817 static void _Wikitext_encode_link_target(parser_t *parser)
819 char *src = parser->link_target->ptr;
820 char *start = src; // remember this so we can check if we're at the start
821 long len = parser->link_target->len;
824 char *end = src + len;
825 long dest_len = len * 2;
826 char *dest = ALLOC_N(char, dest_len);
827 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
828 char *non_space = dest; // remember last non-space character output
829 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
830 for (; src < end; src++)
832 // worst case: a single character may grow to 3 characters once encoded
833 if ((dest + 3) > (dest_ptr + dest_len))
835 // outgrowing buffer, must reallocate
836 char *old_dest = dest;
837 char *old_dest_ptr = dest_ptr;
839 dest = realloc(dest_ptr, dest_len);
842 // would have used reallocf, but this has to run on Linux too, not just Darwin
844 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
847 dest = dest_ptr + (old_dest - old_dest_ptr);
848 non_space = dest_ptr + (non_space - old_dest_ptr);
851 // pass through unreserved characters
852 if ((*src >= 'a' && *src <= 'z') ||
853 (*src >= 'A' && *src <= 'Z') ||
854 (*src >= '0' && *src <= '9') ||
863 else if (*src == ' ' && src == start)
864 start++; // we eat leading space
865 else if (*src == ' ' && parser->space_to_underscore)
867 else // everything else gets URL-encoded
870 *dest++ = hex[(unsigned char)(*src) / 16]; // left
871 *dest++ = hex[(unsigned char)(*src) % 16]; // right
877 // trim trailing space if necessary
878 if (non_space > dest_ptr && dest != non_space)
879 dest_len = non_space - dest_ptr;
881 dest_len = dest - dest_ptr;
882 str_clear(parser->link_target);
883 str_append(parser->link_target, dest_ptr, dest_len);
887 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
890 parser.space_to_underscore = false;
891 parser.link_target = str_new_from_string(in);
892 GC_WRAP_STR(parser.link_target, link_target_gc);
893 _Wikitext_encode_link_target(&parser);
894 return string_from_str(parser.link_target);
897 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
898 // returns 0 (false) otherwise
899 bool _Wikitext_blank(str_t *str)
903 for (char *ptr = str->ptr,
904 *end = str->ptr + str->len;
913 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
916 return; // nothing to do!
917 int scope_includes_separator = IN(SEPARATOR);
918 _Wikitext_pop_from_stack_up_to(parser, NULL, LINK_START, true);
919 str_append(parser->output, link_start, sizeof(link_start) - 1);
920 if (parser->link_target->len > 0)
922 _Wikitext_append_sanitized_link_target(parser, parser->output, false);
923 if (scope_includes_separator)
925 str_append(parser->output, separator, sizeof(separator) - 1);
926 if (parser->link_text->len > 0)
927 str_append_str(parser->output, parser->link_text);
930 parser->capture = NULL;
931 str_clear(parser->link_target);
932 str_clear(parser->link_text);
935 void _Wikitext_rollback_failed_external_link(parser_t *parser)
937 if (!IN(EXT_LINK_START))
938 return; // nothing to do!
940 // store a couple of values before popping
941 int scope_includes_space = IN(SPACE);
942 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
943 _Wikitext_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
945 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
946 if (parser->link_target->len > 0)
948 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
949 if (scope_includes_space)
951 str_append(parser->output, space, sizeof(space) - 1);
952 if (parser->link_text->len > 0)
953 str_append_str(parser->output, parser->link_text);
956 parser->capture = NULL;
957 str_clear(parser->link_target);
958 str_clear(parser->link_text);
961 void _Wikitext_rollback_failed_link(parser_t *parser)
963 _Wikitext_rollback_failed_internal_link(parser);
964 _Wikitext_rollback_failed_external_link(parser);
967 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
971 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
975 VALUE autolink = Qtrue;
976 VALUE line_ending = rb_str_new2("\n");
977 VALUE external_link_class = rb_str_new2("external");
978 VALUE mailto_class = rb_str_new2("mailto");
979 VALUE internal_link_prefix = rb_str_new2("/wiki/");
980 VALUE img_prefix = rb_str_new2("/images/");
981 VALUE space_to_underscore = Qtrue;
982 VALUE minimum_fulltext_token_length = INT2NUM(3);
983 VALUE base_heading_level = INT2NUM(0);
985 // process options hash (override defaults)
986 if (!NIL_P(options) && TYPE(options) == T_HASH)
988 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
989 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
990 autolink = OVERRIDE_IF_SET(autolink);
991 line_ending = OVERRIDE_IF_SET(line_ending);
992 external_link_class = OVERRIDE_IF_SET(external_link_class);
993 mailto_class = OVERRIDE_IF_SET(mailto_class);
994 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
995 img_prefix = OVERRIDE_IF_SET(img_prefix);
996 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
997 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
998 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1001 // no need to call super here; rb_call_super()
1002 rb_iv_set(self, "@autolink", autolink);
1003 rb_iv_set(self, "@line_ending", line_ending);
1004 rb_iv_set(self, "@external_link_class", external_link_class);
1005 rb_iv_set(self, "@mailto_class", mailto_class);
1006 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1007 rb_iv_set(self, "@img_prefix", img_prefix);
1008 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1009 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1010 rb_iv_set(self, "@base_heading_level", base_heading_level);
1014 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1016 for (int i = 0; i < 100000; i++)
1017 Wikitext_parser_parse(1, &string, self);
1021 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1023 // process arguments
1024 VALUE string, options;
1025 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1029 string = StringValue(string);
1031 // process options hash
1032 int base_indent = 0;
1033 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1034 if (!NIL_P(options) && TYPE(options) == T_HASH)
1036 // :indent => 0 (or more)
1037 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1039 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1040 if (indent == Qfalse)
1041 base_indent = -1; // indentation disabled
1044 base_indent = NUM2INT(indent);
1045 if (base_indent < 0)
1050 // :base_heading_level => 0/1/2/3/4/5/6
1051 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1052 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1055 // normalize, regardless of whether this came from instance variable or override
1056 if (base_heading_level < 0)
1057 base_heading_level = 0;
1058 if (base_heading_level > 6)
1059 base_heading_level = 6;
1062 char *p = RSTRING_PTR(string);
1063 long len = RSTRING_LEN(string);
1066 // access these once per parse
1067 VALUE line_ending = rb_iv_get(self, "@line_ending");
1068 line_ending = StringValue(line_ending);
1069 VALUE link_class = rb_iv_get(self, "@external_link_class");
1070 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1071 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1072 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1073 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1075 // set up parser struct to make passing parameters a little easier
1076 parser_t *parser = parser_new();
1077 GC_WRAP_PARSER(parser, parser_gc);
1078 parser->external_link_class = link_class;
1079 parser->mailto_class = mailto_class;
1080 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1081 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1082 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1083 parser->line_ending = str_new_from_string(line_ending);
1084 parser->base_indent = base_indent;
1085 parser->base_heading_level = base_heading_level;
1087 // this simple looping design leads to a single enormous function,
1088 // but it's faster than doing actual recursive descent and also secure in the face of
1089 // malicious input that seeks to overflow the stack
1090 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1091 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1092 // than a straightforward looping translator like this one anyway
1094 _token.type = NO_TOKEN;
1095 token_t *token = NULL;
1098 // note that whenever we grab a token we push it into the line buffer
1099 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1100 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1102 // check to see if we have a token hanging around from a previous iteration of this loop
1105 if (_token.type == NO_TOKEN)
1107 // first time here (haven't started scanning yet)
1109 next_token(token, NULL, p, pe);
1110 ary_push(parser->line_buffer, token->type);
1116 int type = token->type;
1118 // can't declare new variables inside a switch statement, so predeclare them here
1119 long remove_strong = -1;
1120 long remove_em = -1;
1122 // general purpose counters, flags and pointers
1126 str_t *output = NULL;
1128 str_t *token_str = &_token_str;
1130 // The following giant switch statement contains cases for all the possible token types.
1131 // In the most basic sense we are emitting the HTML that corresponds to each token,
1132 // but some tokens require context information in order to decide what to output.
1133 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1134 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1136 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1137 // - the line buffer (records tokens seen so far on the current line)
1138 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1140 // Although this is fairly complicated, there is one key simplifying factor:
1141 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1142 // scope stack (up to the current token) is valid; our translator can take this as a given.
1143 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1144 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1148 if (IN(NO_WIKI_START) || IN(PRE_START))
1150 str_append(parser->output, space, sizeof(space) - 1);
1153 else if (IN(BLOCKQUOTE_START))
1155 // this kind of nesting not allowed (to avoid user confusion)
1156 _Wikitext_pop_excess_elements(parser);
1157 _Wikitext_start_para_if_necessary(parser);
1158 output = parser->capture ? parser->capture : parser->output;
1159 str_append(output, space, sizeof(space) - 1);
1163 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1164 ary_push(parser->line, PRE);
1165 i = ary_count(parser->line, BLOCKQUOTE);
1166 j = ary_count(parser->scope, BLOCKQUOTE);
1169 // must pop (reduce nesting level)
1170 for (i = j - i; i > 0; i--)
1171 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1176 parser->pending_crlf = false;
1177 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1178 _Wikitext_indent(parser);
1179 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1180 ary_push(parser->scope, PRE);
1185 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1187 _Wikitext_emit_pending_crlf_if_necessary(parser);
1188 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1190 else if (IN(BLOCKQUOTE_START))
1192 _Wikitext_rollback_failed_link(parser); // if any
1193 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1194 _Wikitext_indent(parser);
1195 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1196 ary_push(parser->scope, PRE_START);
1197 ary_push(parser->line, PRE_START);
1199 else if (IN(BLOCKQUOTE))
1201 if (token->column_start == 1) // only allowed in first column
1203 _Wikitext_rollback_failed_link(parser); // if any
1204 _Wikitext_pop_all_from_stack(parser);
1205 _Wikitext_indent(parser);
1206 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1207 ary_push(parser->scope, PRE_START);
1208 ary_push(parser->line, PRE_START);
1210 else // PRE_START illegal here
1212 output = parser->capture ? parser->capture : parser->output;
1213 _Wikitext_pop_excess_elements(parser);
1214 _Wikitext_start_para_if_necessary(parser);
1215 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1220 _Wikitext_rollback_failed_link(parser); // if any
1221 _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1222 _Wikitext_indent(parser);
1223 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1224 ary_push(parser->scope, PRE_START);
1225 ary_push(parser->line, PRE_START);
1230 if (IN(NO_WIKI_START) || IN(PRE))
1232 _Wikitext_emit_pending_crlf_if_necessary(parser);
1233 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1238 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1241 output = parser->capture ? parser->capture : parser->output;
1242 _Wikitext_pop_excess_elements(parser);
1243 _Wikitext_start_para_if_necessary(parser);
1244 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1250 if (IN(NO_WIKI_START) || IN(PRE_START))
1251 // no need to check for <pre>; can never appear inside it
1252 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1253 else if (IN(BLOCKQUOTE_START))
1255 // this kind of nesting not allowed (to avoid user confusion)
1256 _Wikitext_pop_excess_elements(parser);
1257 _Wikitext_start_para_if_necessary(parser);
1258 output = parser->capture ? parser->capture : parser->output;
1259 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1264 ary_push(parser->line, BLOCKQUOTE);
1266 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1267 i = ary_count(parser->line, BLOCKQUOTE);
1268 j = ary_count(parser->scope, BLOCKQUOTE);
1270 // 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
1271 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1273 ary_push(parser->line, BLOCKQUOTE);
1277 // now decide whether to push, pop or do nothing
1280 // must push (increase nesting level)
1281 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1282 for (i = i - j; i > 0; i--)
1284 _Wikitext_indent(parser);
1285 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1286 str_append_str(parser->output, parser->line_ending);
1287 ary_push(parser->scope, BLOCKQUOTE);
1292 // must pop (reduce nesting level)
1293 for (i = j - i; i > 0; i--)
1294 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1297 // jump to top of the loop to process token we scanned during lookahead
1302 case BLOCKQUOTE_START:
1303 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1305 _Wikitext_emit_pending_crlf_if_necessary(parser);
1306 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1308 else if (IN(BLOCKQUOTE_START))
1310 // nesting is fine here
1311 _Wikitext_rollback_failed_link(parser); // if any
1312 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1313 _Wikitext_indent(parser);
1314 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1315 str_append_str(parser->output, parser->line_ending);
1316 ary_push(parser->scope, BLOCKQUOTE_START);
1317 ary_push(parser->line, BLOCKQUOTE_START);
1319 else if (IN(BLOCKQUOTE))
1321 if (token->column_start == 1) // only allowed in first column
1323 _Wikitext_rollback_failed_link(parser); // if any
1324 _Wikitext_pop_all_from_stack(parser);
1325 _Wikitext_indent(parser);
1326 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1327 str_append_str(parser->output, parser->line_ending);
1328 ary_push(parser->scope, BLOCKQUOTE_START);
1329 ary_push(parser->line, BLOCKQUOTE_START);
1331 else // BLOCKQUOTE_START illegal here
1333 output = parser->capture ? parser->capture : parser->output;
1334 _Wikitext_pop_excess_elements(parser);
1335 _Wikitext_start_para_if_necessary(parser);
1336 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1341 // would be nice to eliminate the repetition here but it's probably the clearest way
1342 _Wikitext_rollback_failed_link(parser); // if any
1343 _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1344 _Wikitext_indent(parser);
1345 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1346 str_append_str(parser->output, parser->line_ending);
1347 ary_push(parser->scope, BLOCKQUOTE_START);
1348 ary_push(parser->line, BLOCKQUOTE_START);
1352 case BLOCKQUOTE_END:
1353 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1355 _Wikitext_emit_pending_crlf_if_necessary(parser);
1356 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1360 if (IN(BLOCKQUOTE_START))
1361 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1364 output = parser->capture ? parser->capture : parser->output;
1365 _Wikitext_pop_excess_elements(parser);
1366 _Wikitext_start_para_if_necessary(parser);
1367 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1373 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1375 _Wikitext_emit_pending_crlf_if_necessary(parser);
1376 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1380 _Wikitext_pop_excess_elements(parser);
1381 _Wikitext_start_para_if_necessary(parser);
1382 ary_push(parser->scope, NO_WIKI_START);
1383 ary_push(parser->line, NO_WIKI_START);
1388 if (IN(NO_WIKI_START))
1389 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1390 _Wikitext_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1393 _Wikitext_pop_excess_elements(parser);
1394 _Wikitext_start_para_if_necessary(parser);
1395 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1400 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1402 _Wikitext_emit_pending_crlf_if_necessary(parser);
1403 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1407 output = parser->capture ? parser->capture : parser->output;
1408 _Wikitext_pop_excess_elements(parser);
1410 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1411 // otherwise, must open them
1414 j = parser->scope->count;
1415 for (j = j - 1; j >= 0; j--)
1417 int val = ary_entry(parser->scope, j);
1418 if (val == STRONG || val == STRONG_START)
1420 str_append(output, strong_end, sizeof(strong_end) - 1);
1423 else if (val == EM || val == EM_START)
1425 str_append(output, em_end, sizeof(em_end) - 1);
1430 if (remove_strong > remove_em) // must remove strong first
1432 ary_pop(parser->scope);
1434 ary_pop(parser->scope);
1435 else // there was no em to remove!, so consider this an opening em tag
1437 str_append(output, em_start, sizeof(em_start) - 1);
1438 ary_push(parser->scope, EM);
1439 ary_push(parser->line, EM);
1442 else if (remove_em > remove_strong) // must remove em first
1444 ary_pop(parser->scope);
1445 if (remove_strong > -1)
1446 ary_pop(parser->scope);
1447 else // there was no strong to remove!, so consider this an opening strong tag
1449 str_append(output, strong_start, sizeof(strong_start) - 1);
1450 ary_push(parser->scope, STRONG);
1451 ary_push(parser->line, STRONG);
1454 else // no strong or em to remove, so this must be a new opening of both
1456 _Wikitext_start_para_if_necessary(parser);
1457 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1458 ary_push(parser->scope, STRONG);
1459 ary_push(parser->line, STRONG);
1460 ary_push(parser->scope, EM);
1461 ary_push(parser->line, EM);
1466 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1468 _Wikitext_emit_pending_crlf_if_necessary(parser);
1469 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1473 output = parser->capture ? parser->capture : parser->output;
1474 if (IN(STRONG_START))
1475 // already in span started with <strong>, no choice but to emit this literally
1476 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1477 else if (IN(STRONG))
1478 // STRONG already seen, this is a closing tag
1479 _Wikitext_pop_from_stack_up_to(parser, output, STRONG, true);
1482 // this is a new opening
1483 _Wikitext_pop_excess_elements(parser);
1484 _Wikitext_start_para_if_necessary(parser);
1485 str_append(output, strong_start, sizeof(strong_start) - 1);
1486 ary_push(parser->scope, STRONG);
1487 ary_push(parser->line, STRONG);
1493 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1495 _Wikitext_emit_pending_crlf_if_necessary(parser);
1496 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1500 output = parser->capture ? parser->capture : parser->output;
1501 if (IN(STRONG_START) || IN(STRONG))
1502 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1505 _Wikitext_pop_excess_elements(parser);
1506 _Wikitext_start_para_if_necessary(parser);
1507 str_append(output, strong_start, sizeof(strong_start) - 1);
1508 ary_push(parser->scope, STRONG_START);
1509 ary_push(parser->line, STRONG_START);
1515 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1517 _Wikitext_emit_pending_crlf_if_necessary(parser);
1518 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1522 output = parser->capture ? parser->capture : parser->output;
1523 if (IN(STRONG_START))
1524 _Wikitext_pop_from_stack_up_to(parser, output, STRONG_START, true);
1527 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1528 _Wikitext_pop_excess_elements(parser);
1529 _Wikitext_start_para_if_necessary(parser);
1530 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1536 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1538 _Wikitext_emit_pending_crlf_if_necessary(parser);
1539 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1543 output = parser->capture ? parser->capture : parser->output;
1545 // already in span started with <em>, no choice but to emit this literally
1546 str_append(output, literal_em, sizeof(literal_em) - 1);
1548 // EM already seen, this is a closing tag
1549 _Wikitext_pop_from_stack_up_to(parser, output, EM, true);
1552 // this is a new opening
1553 _Wikitext_pop_excess_elements(parser);
1554 _Wikitext_start_para_if_necessary(parser);
1555 str_append(output, em_start, sizeof(em_start) - 1);
1556 ary_push(parser->scope, EM);
1557 ary_push(parser->line, EM);
1563 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1565 _Wikitext_emit_pending_crlf_if_necessary(parser);
1566 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1570 output = parser->capture ? parser->capture : parser->output;
1571 if (IN(EM_START) || IN(EM))
1572 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1575 _Wikitext_pop_excess_elements(parser);
1576 _Wikitext_start_para_if_necessary(parser);
1577 str_append(output, em_start, sizeof(em_start) - 1);
1578 ary_push(parser->scope, EM_START);
1579 ary_push(parser->line, EM_START);
1585 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1587 _Wikitext_emit_pending_crlf_if_necessary(parser);
1588 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1592 output = parser->capture ? parser->capture : parser->output;
1594 _Wikitext_pop_from_stack_up_to(parser, output, EM_START, true);
1597 // no EM_START in scope, so must interpret the TT_END without any special meaning
1598 _Wikitext_pop_excess_elements(parser);
1599 _Wikitext_start_para_if_necessary(parser);
1600 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1606 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1608 _Wikitext_emit_pending_crlf_if_necessary(parser);
1609 str_append(parser->output, backtick, sizeof(backtick) - 1);
1613 output = parser->capture ? parser->capture : parser->output;
1615 // already in span started with <tt>, no choice but to emit this literally
1616 str_append(output, backtick, sizeof(backtick) - 1);
1618 // TT (`) already seen, this is a closing tag
1619 _Wikitext_pop_from_stack_up_to(parser, output, TT, true);
1622 // this is a new opening
1623 _Wikitext_pop_excess_elements(parser);
1624 _Wikitext_start_para_if_necessary(parser);
1625 str_append(output, tt_start, sizeof(tt_start) - 1);
1626 ary_push(parser->scope, TT);
1627 ary_push(parser->line, TT);
1633 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1635 _Wikitext_emit_pending_crlf_if_necessary(parser);
1636 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1640 output = parser->capture ? parser->capture : parser->output;
1641 if (IN(TT_START) || IN(TT))
1642 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1645 _Wikitext_pop_excess_elements(parser);
1646 _Wikitext_start_para_if_necessary(parser);
1647 str_append(output, tt_start, sizeof(tt_start) - 1);
1648 ary_push(parser->scope, TT_START);
1649 ary_push(parser->line, TT_START);
1655 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1657 _Wikitext_emit_pending_crlf_if_necessary(parser);
1658 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1662 output = parser->capture ? parser->capture : parser->output;
1664 _Wikitext_pop_from_stack_up_to(parser, output, TT_START, true);
1667 // no TT_START in scope, so must interpret the TT_END without any special meaning
1668 _Wikitext_pop_excess_elements(parser);
1669 _Wikitext_start_para_if_necessary(parser);
1670 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1677 if (IN(NO_WIKI_START) || IN(PRE_START))
1679 // no need to check for PRE; can never appear inside it
1680 str_append(parser->output, token->start, TOKEN_LEN(token));
1684 // count number of tokens in line and scope stacks
1685 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1686 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1687 j = parser->scope->count - bq_count;
1690 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1694 if (type == OL || type == UL)
1697 if (i - k >= 2) // already seen at least one OL or UL
1699 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1704 ary_push(parser->line, type);
1705 ary_push(parser->line, LI);
1707 // want to compare line with scope but can only do so if scope has enough items on it
1710 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1711 ary_entry(parser->scope, i + bq_count - 1) == LI)
1713 // line and scope match at this point: do nothing yet
1717 // item just pushed onto line does not match corresponding slot of scope!
1718 for (; j >= i - 2; j--)
1719 // must pop back before emitting
1720 _Wikitext_pop_from_stack(parser, NULL);
1722 // will emit UL or OL, then LI
1726 else // line stack size now exceeds scope stack size: must increase nesting level
1727 break; // will emit UL or OL, then LI
1731 // not a OL or UL token!
1733 // must close existing LI and re-open new one
1734 _Wikitext_pop_from_stack(parser, NULL);
1737 // item just pushed onto line does not match corresponding slot of scope!
1739 // must pop back before emitting
1740 _Wikitext_pop_from_stack(parser, NULL);
1748 if (type == OL || type == UL)
1750 // if LI is at the top of a stack this is the start of a nested list
1751 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1753 // so we should precede it with a CRLF, and indicate that it's a nested list
1754 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1755 ary_push(parser->scope, NESTED_LIST);
1759 // this is a new list
1760 if (IN(BLOCKQUOTE_START))
1761 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1763 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1767 _Wikitext_indent(parser);
1769 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1770 else if (type == UL)
1771 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1772 ary_push(parser->scope, type);
1773 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1775 else if (type == SPACE)
1776 // silently throw away the optional SPACE token after final list marker
1779 _Wikitext_indent(parser);
1780 str_append(parser->output, li_start, sizeof(li_start) - 1);
1781 ary_push(parser->scope, LI);
1783 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1784 if (type == OL || type == UL)
1787 while (k++, NEXT_TOKEN(), (type = token->type))
1789 if (type == OL || type == UL)
1790 str_append(parser->output, token->start, TOKEN_LEN(token));
1791 else if (type == SPACE && k == 1)
1793 // silently throw away the optional SPACE token after final list marker
1802 // jump to top of the loop to process token we scanned during lookahead
1811 if (IN(NO_WIKI_START) || IN(PRE_START))
1813 // no need to check for PRE; can never appear inside it
1814 str_append(parser->output, token->start, TOKEN_LEN(token));
1818 // pop up to but not including the last BLOCKQUOTE on the scope stack
1819 if (IN(BLOCKQUOTE_START))
1820 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1822 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1824 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1825 ary_push(parser->line, type);
1826 i = ary_count(parser->line, BLOCKQUOTE);
1827 j = ary_count(parser->scope, BLOCKQUOTE);
1829 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1832 // must pop (reduce nesting level)
1833 for (i = j - i; i > 0; i--)
1834 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1837 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1838 while (NEXT_TOKEN(), (token->type == SPACE))
1841 ary_push(parser->scope, type);
1842 _Wikitext_indent(parser);
1844 // take base_heading_level into account
1845 type += base_heading_level;
1846 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1849 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1850 if (type == H6_START)
1851 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1852 else if (type == H5_START)
1853 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1854 else if (type == H4_START)
1855 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1856 else if (type == H3_START)
1857 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1858 else if (type == H2_START)
1859 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1860 else if (type == H1_START)
1861 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1863 // jump to top of the loop to process token we scanned during lookahead
1867 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1869 _Wikitext_emit_pending_crlf_if_necessary(parser);
1870 str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1874 _Wikitext_rollback_failed_external_link(parser); // if any
1877 // literal output only if not in h6 scope (we stay silent in that case)
1878 _Wikitext_start_para_if_necessary(parser);
1879 str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1885 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1887 _Wikitext_emit_pending_crlf_if_necessary(parser);
1888 str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1892 _Wikitext_rollback_failed_external_link(parser); // if any
1895 // literal output only if not in h5 scope (we stay silent in that case)
1896 _Wikitext_start_para_if_necessary(parser);
1897 str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1903 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1905 _Wikitext_emit_pending_crlf_if_necessary(parser);
1906 str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1910 _Wikitext_rollback_failed_external_link(parser); // if any
1913 // literal output only if not in h4 scope (we stay silent in that case)
1914 _Wikitext_start_para_if_necessary(parser);
1915 str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1921 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1923 _Wikitext_emit_pending_crlf_if_necessary(parser);
1924 str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1928 _Wikitext_rollback_failed_external_link(parser); // if any
1931 // literal output only if not in h3 scope (we stay silent in that case)
1932 _Wikitext_start_para_if_necessary(parser);
1933 str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1939 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1941 _Wikitext_emit_pending_crlf_if_necessary(parser);
1942 str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1946 _Wikitext_rollback_failed_external_link(parser); // if any
1949 // literal output only if not in h2 scope (we stay silent in that case)
1950 _Wikitext_start_para_if_necessary(parser);
1951 str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1957 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1959 _Wikitext_emit_pending_crlf_if_necessary(parser);
1960 str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1964 _Wikitext_rollback_failed_external_link(parser); // if any
1967 // literal output only if not in h1 scope (we stay silent in that case)
1968 _Wikitext_start_para_if_necessary(parser);
1969 str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1975 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1977 _Wikitext_emit_pending_crlf_if_necessary(parser);
1978 str_append(parser->output, token->start, TOKEN_LEN(token));
1982 _Wikitext_pop_excess_elements(parser);
1983 _Wikitext_start_para_if_necessary(parser);
1984 token_str->ptr = token->start;
1985 token_str->len = TOKEN_LEN(token);
1986 _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
1991 if (IN(NO_WIKI_START))
1992 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1993 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1994 str_append(parser->output, token->start, TOKEN_LEN(token));
1995 else if (IN(LINK_START))
1997 // if the URI were allowed it would have been handled already in LINK_START
1998 _Wikitext_rollback_failed_internal_link(parser);
1999 token_str->ptr = token->start;
2000 token_str->len = TOKEN_LEN(token);
2001 _Wikitext_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2003 else if (IN(EXT_LINK_START))
2005 if (parser->link_target->len == 0)
2007 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2008 token_str->ptr = token->start;
2009 token_str->len = TOKEN_LEN(token);
2011 if (token->type == SPACE)
2013 ary_push(parser->scope, SPACE);
2014 str_append_str(parser->link_target, token_str);
2015 str_clear(parser->link_text);
2016 parser->capture = parser->link_text;
2017 token = NULL; // silently consume space
2021 // didn't see the space! this must be an error
2022 _Wikitext_pop_from_stack(parser, NULL);
2023 _Wikitext_pop_excess_elements(parser);
2024 _Wikitext_start_para_if_necessary(parser);
2025 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2026 _Wikitext_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2030 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2034 _Wikitext_pop_excess_elements(parser);
2035 _Wikitext_start_para_if_necessary(parser);
2036 token_str->ptr = token->start;
2037 token_str->len = TOKEN_LEN(token);
2038 _Wikitext_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
2043 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2044 str_append(parser->output, token->start, TOKEN_LEN(token));
2045 else if (IN(EXT_LINK_START))
2047 if (parser->link_target->len == 0)
2049 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2050 token_str->ptr = token->start;
2051 token_str->len = TOKEN_LEN(token);
2053 if (token->type == SPACE)
2055 ary_push(parser->scope, PATH);
2056 ary_push(parser->scope, SPACE);
2057 str_append_str(parser->link_target, token_str);
2058 str_clear(parser->link_text);
2059 parser->capture = parser->link_text;
2060 token = NULL; // silently consume space
2064 // didn't see the space! this must be an error
2065 _Wikitext_pop_from_stack(parser, NULL);
2066 _Wikitext_pop_excess_elements(parser);
2067 _Wikitext_start_para_if_necessary(parser);
2068 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2069 str_append_str(parser->output, token_str);
2073 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2077 output = parser->capture ? parser->capture : parser->output;
2078 _Wikitext_pop_excess_elements(parser);
2079 _Wikitext_start_para_if_necessary(parser);
2080 str_append(output, token->start, TOKEN_LEN(token));
2084 // internal links (links to other wiki articles) look like this:
2085 // [[another article]] (would point at, for example, "/wiki/another_article")
2086 // [[the other article|the link text we'll use for it]]
2087 // [[the other article | the link text we'll use for it]]
2088 // MediaWiki has strict requirements about what it will accept as a link target:
2089 // all wikitext markup is disallowed:
2090 // example [[foo ''bar'' baz]]
2091 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2092 // example [[foo <em>bar</em> baz]]
2093 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2094 // example [[foo <nowiki>''</nowiki> baz]]
2095 // renders [[foo '' baz]] (ie. not a link)
2096 // example [[foo <bar> baz]]
2097 // renders [[foo <bar> baz]] (ie. not a link)
2098 // HTML entities and non-ASCII, however, make it through:
2099 // example [[foo €]]
2100 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2101 // example [[foo €]]
2102 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2103 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2104 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2105 // everything else will be rejected
2107 output = parser->capture ? parser->capture : parser->output;
2108 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2110 _Wikitext_emit_pending_crlf_if_necessary(parser);
2111 str_append(output, link_start, sizeof(link_start) - 1);
2113 else if (IN(EXT_LINK_START))
2114 // already in external link scope! (and in fact, must be capturing link_text right now)
2115 str_append(output, link_start, sizeof(link_start) - 1);
2116 else if (IN(LINK_START))
2118 // already in internal link scope! this is a syntax error
2119 _Wikitext_rollback_failed_internal_link(parser);
2120 str_append(parser->output, link_start, sizeof(link_start) - 1);
2122 else if (IN(SEPARATOR))
2124 // scanning internal link text
2126 else // not in internal link scope yet
2128 // will either emit a link, or the rollback of a failed link, so start the para now
2129 _Wikitext_pop_excess_elements(parser);
2130 _Wikitext_start_para_if_necessary(parser);
2131 ary_push(parser->scope, LINK_START);
2133 // look ahead and try to gobble up link target
2134 while (NEXT_TOKEN(), (type = token->type))
2136 if (type == SPACE ||
2137 type == SPECIAL_URI_CHARS ||
2139 type == PRINTABLE ||
2143 type == QUOT_ENTITY ||
2145 type == AMP_ENTITY ||
2146 type == IMG_START ||
2148 type == LEFT_CURLY ||
2149 type == RIGHT_CURLY)
2151 // accumulate these tokens into link_target
2152 if (parser->link_target->len == 0)
2154 str_clear(parser->link_target);
2155 parser->capture = parser->link_target;
2157 if (type == QUOT_ENTITY)
2158 // don't insert the entity, insert the literal quote
2159 str_append(parser->link_target, quote, sizeof(quote) - 1);
2160 else if (type == AMP_ENTITY)
2161 // don't insert the entity, insert the literal ampersand
2162 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2164 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2166 else if (type == LINK_END)
2168 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2169 _Wikitext_rollback_failed_internal_link(parser);
2170 break; // jump back to top of loop (will handle this in LINK_END case below)
2172 else if (type == SEPARATOR)
2174 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2175 _Wikitext_rollback_failed_internal_link(parser);
2178 ary_push(parser->scope, SEPARATOR);
2179 str_clear(parser->link_text);
2180 parser->capture = parser->link_text;
2185 else // unexpected token (syntax error)
2187 _Wikitext_rollback_failed_internal_link(parser);
2188 break; // jump back to top of loop to handle unexpected token
2192 // jump to top of the loop to process token we scanned during lookahead (if any)
2198 output = parser->capture ? parser->capture : parser->output;
2199 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2201 _Wikitext_emit_pending_crlf_if_necessary(parser);
2202 str_append(output, link_end, sizeof(link_end) - 1);
2204 else if (IN(EXT_LINK_START))
2205 // already in external link scope! (and in fact, must be capturing link_text right now)
2206 str_append(output, link_end, sizeof(link_end) - 1);
2207 else if (IN(LINK_START)) // in internal link scope!
2209 if (_Wikitext_blank(parser->link_target))
2211 // special case for inputs like "[[ ]]"
2212 _Wikitext_rollback_failed_internal_link(parser);
2213 str_append(parser->output, link_end, sizeof(link_end) - 1);
2216 if (parser->link_text->len == 0 ||
2217 _Wikitext_blank(parser->link_text))
2219 // use link target as link text
2220 str_clear(parser->link_text);
2221 _Wikitext_append_sanitized_link_target(parser, parser->link_text, true);
2224 _Wikitext_trim_link_text(parser);
2225 _Wikitext_encode_link_target(parser);
2226 _Wikitext_pop_from_stack_up_to(parser, output, LINK_START, true);
2227 parser->capture = NULL;
2228 _Wikitext_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, false);
2229 str_clear(parser->link_target);
2230 str_clear(parser->link_text);
2232 else // wasn't in internal link scope
2234 _Wikitext_pop_excess_elements(parser);
2235 _Wikitext_start_para_if_necessary(parser);
2236 str_append(output, link_end, sizeof(link_end) - 1);
2240 // external links look like this:
2241 // [http://google.com/ the link text]
2242 // [/other/page/on/site see this page]
2243 // strings in square brackets which don't match this syntax get passed through literally; eg:
2244 // he was very angery [sic] about the turn of events
2245 case EXT_LINK_START:
2246 output = parser->capture ? parser->capture : parser->output;
2247 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2249 _Wikitext_emit_pending_crlf_if_necessary(parser);
2250 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2252 else if (IN(EXT_LINK_START))
2253 // already in external link scope! (and in fact, must be capturing link_text right now)
2254 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2255 else if (IN(LINK_START))
2257 // already in internal link scope!
2258 if (parser->link_target->len == 0 || !IN(SPACE))
2259 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2260 else // link target has already been scanned
2261 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2263 else // not in external link scope yet
2265 // will either emit a link, or the rollback of a failed link, so start the para now
2266 _Wikitext_pop_excess_elements(parser);
2267 _Wikitext_start_para_if_necessary(parser);
2269 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2271 if (token->type == URI || token->type == PATH)
2272 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2274 // only get here if there was a syntax error (missing URI)
2275 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2276 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2281 output = parser->capture ? parser->capture : parser->output;
2282 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2284 _Wikitext_emit_pending_crlf_if_necessary(parser);
2285 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2287 else if (IN(EXT_LINK_START))
2289 if (parser->link_text->len == 0)
2290 // syntax error: external link with no link text
2291 _Wikitext_rollback_failed_external_link(parser);
2295 j = IN(PATH) ? Qnil : parser->external_link_class;
2296 _Wikitext_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2297 parser->capture = NULL;
2298 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2300 str_clear(parser->link_target);
2301 str_clear(parser->link_text);
2305 _Wikitext_pop_excess_elements(parser);
2306 _Wikitext_start_para_if_necessary(parser);
2307 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2312 output = parser->capture ? parser->capture : parser->output;
2313 _Wikitext_pop_excess_elements(parser);
2314 _Wikitext_start_para_if_necessary(parser);
2315 str_append(output, separator, sizeof(separator) - 1);
2319 output = parser->capture ? parser->capture : parser->output;
2320 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2322 _Wikitext_emit_pending_crlf_if_necessary(parser);
2323 str_append(output, token->start, TOKEN_LEN(token));
2327 // peek ahead to see next token
2328 char *token_ptr = token->start;
2329 int token_len = TOKEN_LEN(token);
2332 if (((type == H6_END) && IN(H6_START)) ||
2333 ((type == H5_END) && IN(H5_START)) ||
2334 ((type == H4_END) && IN(H4_START)) ||
2335 ((type == H3_END) && IN(H3_START)) ||
2336 ((type == H2_END) && IN(H2_START)) ||
2337 ((type == H1_END) && IN(H1_START)))
2339 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2344 _Wikitext_pop_excess_elements(parser);
2345 _Wikitext_start_para_if_necessary(parser);
2346 str_append(output, token_ptr, token_len);
2349 // jump to top of the loop to process token we scanned during lookahead
2357 case DECIMAL_ENTITY:
2358 // pass these through unaltered as they are case sensitive
2359 output = parser->capture ? parser->capture : parser->output;
2360 _Wikitext_pop_excess_elements(parser);
2361 _Wikitext_start_para_if_necessary(parser);
2362 str_append(output, token->start, TOKEN_LEN(token));
2366 // normalize hex entities (downcase them)
2367 output = parser->capture ? parser->capture : parser->output;
2368 _Wikitext_pop_excess_elements(parser);
2369 _Wikitext_start_para_if_necessary(parser);
2370 str_append(output, token->start, TOKEN_LEN(token));
2371 _Wikitext_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2375 output = parser->capture ? parser->capture : parser->output;
2376 _Wikitext_pop_excess_elements(parser);
2377 _Wikitext_start_para_if_necessary(parser);
2378 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2382 output = parser->capture ? parser->capture : parser->output;
2383 _Wikitext_pop_excess_elements(parser);
2384 _Wikitext_start_para_if_necessary(parser);
2385 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2389 output = parser->capture ? parser->capture : parser->output;
2390 _Wikitext_pop_excess_elements(parser);
2391 _Wikitext_start_para_if_necessary(parser);
2392 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2396 output = parser->capture ? parser->capture : parser->output;
2397 _Wikitext_pop_excess_elements(parser);
2398 _Wikitext_start_para_if_necessary(parser);
2399 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2403 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2405 _Wikitext_emit_pending_crlf_if_necessary(parser);
2406 str_append(parser->output, token->start, TOKEN_LEN(token));
2408 else if (parser->capture)
2409 str_append(parser->capture, token->start, TOKEN_LEN(token));
2412 // not currently capturing: will be emitting something on success or failure, so get ready
2413 _Wikitext_pop_excess_elements(parser);
2414 _Wikitext_start_para_if_necessary(parser);
2416 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2417 // will cheat here and abuse the link_target capture buffer to accumulate text
2418 while (NEXT_TOKEN(), (type = token->type))
2420 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2421 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2422 else if (type == IMG_END && parser->link_target->len > 0)
2425 _Wikitext_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2429 else // unexpected token or zero-length target (syntax error)
2432 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2433 if (parser->link_target->len > 0)
2434 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2439 // jump to top of the loop to process token we scanned during lookahead
2440 str_clear(parser->link_target);
2446 i = parser->pending_crlf;
2447 parser->pending_crlf = false;
2448 _Wikitext_rollback_failed_link(parser); // if any
2449 if (IN(NO_WIKI_START) || IN(PRE_START))
2451 ary_clear(parser->line_buffer);
2452 str_append_str(parser->output, parser->line_ending);
2457 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2458 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2459 // don't emit in this case
2460 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2463 if (ary_entry(parser->line_buffer, -2) == PRE)
2465 // only thing on line is the PRE: emit pending line ending (if we had one)
2467 str_append_str(parser->output, parser->line_ending);
2470 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2471 ary_clear(parser->line);
2472 ary_clear(parser->line_buffer);
2474 // peek ahead to see if this is definitely the end of the PRE block
2477 if (type != BLOCKQUOTE && type != PRE)
2478 // this is definitely the end of the block, so don't emit
2479 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2481 // potentially will emit
2482 parser->pending_crlf = true;
2484 continue; // jump back to top of loop to handle token grabbed via lookahead
2489 parser->pending_crlf = true;
2491 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2492 // as a side effect, this handles any open span-level elements and unclosed blocks
2493 // (with special handling for P blocks and LI elements)
2494 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2495 for (j = parser->scope->count; j > i; j--)
2497 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2499 parser->pending_crlf = false;
2503 // special handling on last iteration through the loop if the top item on the scope is a P block
2504 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2506 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2507 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2508 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2509 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2510 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2512 parser->pending_crlf = false;
2514 // not a paragraph break!
2517 _Wikitext_pop_from_stack(parser, NULL);
2521 // delete the entire contents of the line scope stack and buffer
2522 ary_clear(parser->line);
2523 ary_clear(parser->line_buffer);
2526 case SPECIAL_URI_CHARS:
2532 output = parser->capture ? parser->capture : parser->output;
2533 _Wikitext_pop_excess_elements(parser);
2534 _Wikitext_start_para_if_necessary(parser);
2535 str_append(output, token->start, TOKEN_LEN(token));
2539 output = parser->capture ? parser->capture : parser->output;
2540 _Wikitext_pop_excess_elements(parser);
2541 _Wikitext_start_para_if_necessary(parser);
2542 //str_append_string(output, _Wikitext_utf32_char_to_entity(token->code_point)); // convert to entity
2543 // TODO: replace this with a different append function
2544 str_grow(output, output->len + 8);
2545 _Wikitext_append_entity_from_utf32_char(output->ptr + output->len, token->code_point);
2550 // special case for input like " foo\n " (see pre_spec.rb)
2552 ary_entry(parser->line_buffer, -2) == PRE &&
2553 parser->pending_crlf)
2554 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2556 // close any open scopes on hitting EOF
2557 _Wikitext_rollback_failed_link(parser); // if any
2558 _Wikitext_pop_all_from_stack(parser);
2559 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2565 // reset current token; forcing lexer to return another token at the top of the loop
2569 // nasty hack to avoid re-allocating our return value
2570 str_append(parser->output, null_str, 1); // null-terminate
2571 len = parser->output->len - 1; // don't count null termination
2573 #if defined(RUBY_1_9_x)
2574 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2575 free(RSTRING_PTR(out));
2576 RSTRING(out)->as.heap.aux.capa = len;
2577 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2578 RSTRING(out)->as.heap.len = len;
2579 #elif defined(RUBY_1_8_x)
2580 VALUE out = rb_str_new2("");
2581 free(RSTRING_PTR(out));
2582 RSTRING(out)->len = len;
2583 RSTRING(out)->aux.capa = len;
2584 RSTRING(out)->ptr = parser->output->ptr;
2586 #error unsupported RUBY_VERSION
2588 parser->output->ptr = NULL; // don't double-free