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 escaped_no_wiki_start[] = "<nowiki>";
60 const char escaped_no_wiki_end[] = "</nowiki>";
61 const char literal_strong_em[] = "'''''";
62 const char literal_strong[] = "'''";
63 const char literal_em[] = "''";
64 const char escaped_em_start[] = "<em>";
65 const char escaped_em_end[] = "</em>";
66 const char escaped_strong_start[] = "<strong>";
67 const char escaped_strong_end[] = "</strong>";
68 const char escaped_tt_start[] = "<tt>";
69 const char escaped_tt_end[] = "</tt>";
70 const char literal_h6[] = "======";
71 const char literal_h5[] = "=====";
72 const char literal_h4[] = "====";
73 const char literal_h3[] = "===";
74 const char literal_h2[] = "==";
75 const char literal_h1[] = "=";
76 const char pre_start[] = "<pre>";
77 const char pre_end[] = "</pre>";
78 const char escaped_pre_start[] = "<pre>";
79 const char escaped_pre_end[] = "</pre>";
80 const char blockquote_start[] = "<blockquote>";
81 const char blockquote_end[] = "</blockquote>";
82 const char escaped_blockquote_start[] = "<blockquote>";
83 const char escaped_blockquote_end[] = "</blockquote>";
84 const char strong_em_start[] = "<strong><em>";
85 const char strong_start[] = "<strong>";
86 const char strong_end[] = "</strong>";
87 const char em_start[] = "<em>";
88 const char em_end[] = "</em>";
89 const char tt_start[] = "<tt>";
90 const char tt_end[] = "</tt>";
91 const char ol_start[] = "<ol>";
92 const char ol_end[] = "</ol>";
93 const char ul_start[] = "<ul>";
94 const char ul_end[] = "</ul>";
95 const char li_start[] = "<li>";
96 const char li_end[] = "</li>";
97 const char h6_start[] = "<h6>";
98 const char h6_end[] = "</h6>";
99 const char h5_start[] = "<h5>";
100 const char h5_end[] = "</h5>";
101 const char h4_start[] = "<h4>";
102 const char h4_end[] = "</h4>";
103 const char h3_start[] = "<h3>";
104 const char h3_end[] = "</h3>";
105 const char h2_start[] = "<h2>";
106 const char h2_end[] = "</h2>";
107 const char h1_start[] = "<h1>";
108 const char h1_end[] = "</h1>";
109 const char p_start[] = "<p>";
110 const char p_end[] = "</p>";
111 const char space[] = " ";
112 const char a_start[] = "<a href=\"";
113 const char a_class[] = "\" class=\"";
114 const char a_start_close[] = "\">";
115 const char a_end[] = "</a>";
116 const char link_start[] = "[[";
117 const char link_end[] = "]]";
118 const char separator[] = "|";
119 const char ext_link_start[] = "[";
120 const char backtick[] = "`";
121 const char quote[] = "\"";
122 const char ampersand[] = "&";
123 const char quot_entity[] = """;
124 const char amp_entity[] = "&";
125 const char lt_entity[] = "<";
126 const char gt_entity[] = ">";
127 const char escaped_blockquote[] = "> ";
128 const char ext_link_end[] = "]";
129 const char literal_img_start[] = "{{";
130 const char img_start[] = "<img src=\"";
131 const char img_end[] = "\" />";
132 const char img_alt[] = "\" alt=\"";
134 // Mark the parser struct designated by ptr as a participant in Ruby's
135 // mark-and-sweep garbage collection scheme. A variable named name is placed on
136 // the C stack to prevent the structure from being prematurely collected.
137 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
139 parser_t *parser_new(void)
141 parser_t *parser = ALLOC_N(parser_t, 1);
142 parser->capture = NULL; // not a real instance, pointer to other member's instance
143 parser->output = str_new();
144 parser->link_target = str_new();
145 parser->link_text = str_new();
146 parser->line_ending = NULL; // caller should set up
147 parser->tabulation = str_new();
148 parser->scope = ary_new();
149 parser->line = ary_new();
150 parser->line_buffer = ary_new();
151 parser->external_link_class = Qnil; // caller should set up
152 parser->mailto_class = Qnil; // caller should set up
153 parser->img_prefix = Qnil; // caller should set up
154 parser->base_indent = 0;
155 parser->current_indent = 0;
156 parser->base_heading_level = 0;
157 parser->pending_crlf = false;
158 parser->autolink = true;
159 parser->space_to_underscore = true;
163 void parser_free(parser_t *parser)
165 // we don't free parser->capture; it's just a redundant pointer
166 if (parser->output) str_free(parser->output);
167 if (parser->link_target) str_free(parser->link_target);
168 if (parser->link_text) str_free(parser->link_text);
169 if (parser->line_ending) str_free(parser->line_ending);
170 if (parser->tabulation) str_free(parser->tabulation);
171 if (parser->scope) ary_free(parser->scope);
172 if (parser->line) ary_free(parser->line);
173 if (parser->line_buffer) ary_free(parser->line_buffer);
177 // for testing and debugging only
178 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
182 string = StringValue(string);
183 VALUE tokens = rb_ary_new();
184 char *p = RSTRING_PTR(string);
185 long len = RSTRING_LEN(string);
188 next_token(&token, NULL, p, pe);
189 rb_ary_push(tokens, _Wikitext_token(&token));
190 while (token.type != END_OF_FILE)
192 next_token(&token, &token, NULL, pe);
193 rb_ary_push(tokens, _Wikitext_token(&token));
198 // for benchmarking raw tokenization speed only
199 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
203 string = StringValue(string);
204 char *p = RSTRING_PTR(string);
205 long len = RSTRING_LEN(string);
208 next_token(&token, NULL, p, pe);
209 while (token.type != END_OF_FILE)
210 next_token(&token, &token, NULL, pe);
214 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
217 VALUE string, options;
218 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
222 string = StringValue(string);
223 VALUE tokens = rb_ary_new();
225 // check instance variables
226 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
228 // process options hash (can override instance variables)
229 if (!NIL_P(options) && TYPE(options) == T_HASH)
231 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
232 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
234 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
239 char *p = RSTRING_PTR(string);
240 long len = RSTRING_LEN(string);
243 token_t *_token = &token;
244 next_token(&token, NULL, p, pe);
245 while (token.type != END_OF_FILE)
252 if (TOKEN_LEN(_token) >= min_len)
253 rb_ary_push(tokens, TOKEN_TEXT(_token));
256 // ignore everything else
259 next_token(&token, &token, NULL, pe);
264 // we downcase "in place", overwriting the original contents of the buffer
265 void _Wikitext_downcase_bang(char *ptr, long len)
267 for (long i = 0; i < len; i++)
269 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
274 // prepare hyperlink and append it to parser->output
275 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
276 // or merely the literal link target
277 // if link_text is Qnil, the link_target is re-used for the link text
278 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class, bool check_autolink)
280 if (check_autolink && !parser->autolink)
281 str_append_string(parser->output, link_target);
284 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
285 if (!NIL_P(link_prefix))
286 str_append_string(parser->output, link_prefix);
287 str_append_string(parser->output, link_target);
289 // special handling for mailto URIs
290 const char *mailto = "mailto:";
291 if (NIL_P(link_prefix) &&
292 RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
293 strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
294 link_class = parser->mailto_class; // use mailto_class from parser
295 if (link_class != Qnil)
297 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
298 str_append_string(parser->output, link_class);
300 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
301 if (NIL_P(link_text)) // re-use link_target
302 str_append_string(parser->output, link_target);
304 str_append_string(parser->output, link_text);
305 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
309 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
311 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
312 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
313 str_append_string(parser->output, parser->img_prefix);
314 str_append(parser->output, token_ptr, token_len);
315 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
316 str_append(parser->output, token_ptr, token_len);
317 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
320 // will emit indentation only if we are about to emit any of:
321 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
322 // each time we enter one of those spans must ++ the indentation level
323 void _Wikitext_indent(parser_t *parser)
325 if (parser->base_indent == -1) // indentation disabled
327 int space_count = parser->current_indent + parser->base_indent;
330 char *old_end, *new_end;
331 if (parser->tabulation->len < space_count)
332 str_grow(parser->tabulation, space_count); // reallocates if necessary
333 old_end = parser->tabulation->ptr + parser->tabulation->len;
334 new_end = parser->tabulation->ptr + space_count;
335 while (old_end < new_end)
337 if (space_count > parser->tabulation->len)
338 parser->tabulation->len = space_count;
339 str_append(parser->output, parser->tabulation->ptr, space_count);
341 parser->current_indent += 2;
344 void _Wikitext_dedent(parser_t *parser, VALUE emit)
346 if (parser->base_indent == -1) // indentation disabled
348 parser->current_indent -= 2;
351 int space_count = parser->current_indent + parser->base_indent;
353 str_append(parser->output, parser->tabulation->ptr, space_count);
356 // Pops a single item off the parser's scope stack.
357 // A corresponding closing tag is written to the target string.
358 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
359 void _Wikitext_pop_from_stack(parser_t *parser, str_t *target)
361 int top = ary_entry(parser->scope, -1);
365 target = parser->output;
367 // for headings, take base_heading_level into account
368 if (top >= H1_START && top <= H6_START)
370 top += parser->base_heading_level;
371 // no need to check for underflow (base_heading_level is never negative)
380 str_append(target, pre_end, sizeof(pre_end) - 1);
381 str_append_str(target, parser->line_ending);
382 _Wikitext_dedent(parser, Qfalse);
386 case BLOCKQUOTE_START:
387 _Wikitext_dedent(parser, Qtrue);
388 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
389 str_append_str(target, parser->line_ending);
393 // not a real HTML tag; so nothing to pop
398 str_append(target, strong_end, sizeof(strong_end) - 1);
403 str_append(target, em_end, sizeof(em_end) - 1);
408 str_append(target, tt_end, sizeof(tt_end) - 1);
412 _Wikitext_dedent(parser, Qtrue);
413 str_append(target, ol_end, sizeof(ol_end) - 1);
414 str_append_str(target, parser->line_ending);
418 _Wikitext_dedent(parser, Qtrue);
419 str_append(target, ul_end, sizeof(ul_end) - 1);
420 str_append_str(target, parser->line_ending);
424 // next token to pop will be a LI
425 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
426 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
427 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
428 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
429 _Wikitext_dedent(parser, Qtrue); // we really only want to emit the spaces
430 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
434 str_append(target, li_end, sizeof(li_end) - 1);
435 str_append_str(target, parser->line_ending);
436 _Wikitext_dedent(parser, Qfalse);
440 str_append(target, h6_end, sizeof(h6_end) - 1);
441 str_append_str(target, parser->line_ending);
442 _Wikitext_dedent(parser, Qfalse);
446 str_append(target, h5_end, sizeof(h5_end) - 1);
447 str_append_str(target, parser->line_ending);
448 _Wikitext_dedent(parser, Qfalse);
452 str_append(target, h4_end, sizeof(h4_end) - 1);
453 str_append_str(target, parser->line_ending);
454 _Wikitext_dedent(parser, Qfalse);
458 str_append(target, h3_end, sizeof(h3_end) - 1);
459 str_append_str(target, parser->line_ending);
460 _Wikitext_dedent(parser, Qfalse);
464 str_append(target, h2_end, sizeof(h2_end) - 1);
465 str_append_str(target, parser->line_ending);
466 _Wikitext_dedent(parser, Qfalse);
470 str_append(target, h1_end, sizeof(h1_end) - 1);
471 str_append_str(target, parser->line_ending);
472 _Wikitext_dedent(parser, Qfalse);
476 // not an HTML tag; so nothing to emit
480 // not an HTML tag; so nothing to emit
484 // not an HTML tag; so nothing to emit
488 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
492 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
496 str_append(target, p_end, sizeof(p_end) - 1);
497 str_append_str(target, parser->line_ending);
498 _Wikitext_dedent(parser, Qfalse);
506 // should probably raise an exception here
509 ary_pop(parser->scope);
512 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
513 // If including is true then the item itself is also popped.
514 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
515 void _Wikitext_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
517 int continue_looping = 1;
520 int top = ary_entry(parser->scope, -1);
527 continue_looping = 0;
529 _Wikitext_pop_from_stack(parser, target);
530 } while (continue_looping);
533 void _Wikitext_pop_all_from_stack(parser_t *parser)
535 for (int i = 0, max = parser->scope->count; i < max; i++)
536 _Wikitext_pop_from_stack(parser, NULL);
539 void _Wikitext_start_para_if_necessary(parser_t *parser)
544 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
545 if (parser->scope->count == 0 ||
546 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
547 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
549 _Wikitext_indent(parser);
550 str_append(parser->output, p_start, sizeof(p_start) - 1);
551 ary_push(parser->scope, P);
552 ary_push(parser->line, P);
554 else if (parser->pending_crlf)
557 // already in a paragraph block; convert pending CRLF into a space
558 str_append(parser->output, space, sizeof(space) - 1);
560 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
561 str_append_str(parser->output, parser->line_ending);
563 parser->pending_crlf = false;
566 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
568 if (parser->pending_crlf)
570 str_append_str(parser->output, parser->line_ending);
571 parser->pending_crlf = false;
575 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
576 // For example, given input like:
581 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
582 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
587 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
588 // but not on the line scope:
593 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
594 // on the line scope.
595 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
596 // entering the for loop.
597 void _Wikitext_pop_excess_elements(parser_t *parser)
601 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
603 // special case for last item on scope
606 // don't auto-pop P if it is only item on scope
607 if (ary_entry(parser->scope, -1) == P)
609 // add P to the line scope to prevent us entering the loop at all next time around
610 ary_push(parser->line, P);
614 _Wikitext_pop_from_stack(parser, NULL);
618 #define INVALID_ENCODING(msg) do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
620 // convert a single UTF-8 codepoint to UTF-32
621 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
622 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
623 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
624 // raises a RangeError if the supplied character is invalid UTF-8
625 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
626 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
629 if ((unsigned char)src[0] <= 0x7f) // ASCII
634 else if ((src[0] & 0xe0) == 0xc0) // byte starts with 110..... : this should be a two-byte sequence
637 INVALID_ENCODING("truncated byte sequence"); // no second byte
638 else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
639 INVALID_ENCODING("overlong encoding"); // overlong encoding: lead byte of 110..... but code point <= 127
640 else if ((src[1] & 0xc0) != 0x80 )
641 INVALID_ENCODING("malformed byte sequence"); // should have second byte starting with 10......
642 dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
645 else if ((src[0] & 0xf0) == 0xe0) // byte starts with 1110.... : this should be a three-byte sequence
648 INVALID_ENCODING("truncated byte sequence"); // missing second or third byte
649 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
650 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
651 dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
654 else if ((src[0] & 0xf8) == 0xf0) // bytes starts with 11110... : this should be a four-byte sequence
657 INVALID_ENCODING("truncated byte sequence"); // missing second, third, or fourth byte
658 else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
659 INVALID_ENCODING("overlong encoding"); // disallowed by RFC 3629 (codepoints above 0x10ffff)
660 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
661 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
662 dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
665 else // invalid input
666 INVALID_ENCODING("unexpected byte");
670 VALUE _Wikitext_utf32_char_to_entity(uint32_t character)
672 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
673 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
674 char scratch = (character & 0xf000) >> 12;
675 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
676 scratch = (character & 0x0f00) >> 8;
677 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
678 scratch = (character & 0x00f0) >> 4;
679 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
680 scratch = character & 0x000f;
681 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
682 return rb_str_new((const char *)hex_string, sizeof(hex_string));
685 // trim parser->link_text in place
686 void _Wikitext_parser_trim_link_text(parser_t *parser)
688 char *src = parser->link_text->ptr;
689 char *start = src; // remember this so we can check if we're at the start
691 char *non_space = src; // remember last non-space character output
692 long len = parser->link_text->len;
693 char *end = src + len;
705 if (left != start || non_space + 1 != end)
707 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
708 parser->link_text->len = (non_space + 1) - left;
709 memmove(parser->link_text->ptr, left, parser->link_text->len);
713 // - non-printable (non-ASCII) characters converted to numeric entities
714 // - QUOT and AMP characters converted to named entities
715 // - if rollback is true, there is no special treatment of spaces
716 // - if rollback is false, leading and trailing whitespace trimmed
717 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, bool rollback)
719 VALUE string = string_from_str(parser->link_target);
720 char *src = RSTRING_PTR(string);
721 char *start = src; // remember this so we can check if we're at the start
722 long len = RSTRING_LEN(string);
723 char *end = src + len;
725 // start with a destination buffer twice the size of the source, will realloc if necessary
726 // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
727 // this efficiently handles the most common case (where the size of the buffer doesn't change much)
728 char *dest = ALLOC_N(char, len * 2);
729 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
730 char *non_space = dest; // remember last non-space character output
733 // need at most 8 characters (8 bytes) to display each character
734 if (dest + 8 > dest_ptr + len) // outgrowing buffer, must reallocate
736 char *old_dest = dest;
737 char *old_dest_ptr = dest_ptr;
738 len = len + (end - src) * 8; // allocate enough for worst case
739 dest = realloc(dest_ptr, len); // will never have to realloc more than once
742 // would have used reallocf, but this has to run on Linux too, not just Darwin
744 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
747 dest = dest_ptr + (old_dest - old_dest_ptr);
748 non_space = dest_ptr + (non_space - old_dest_ptr);
751 if (*src == '"') // QUOT
753 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
754 memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
755 dest += sizeof(quot_entity_literal);
757 else if (*src == '&') // AMP
759 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
760 memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
761 dest += sizeof(amp_entity_literal);
763 else if (*src == '<') // LESS_THAN
766 rb_raise(rb_eRangeError, "invalid link text (\"<\" may not appear in link text)");
768 else if (*src == '>') // GREATER_THAN
771 rb_raise(rb_eRangeError, "invalid link text (\">\" may not appear in link text)");
773 else if (*src == ' ' && src == start && !rollback)
774 start++; // we eat leading space
775 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
780 else // all others: must convert to entities
783 VALUE entity = _Wikitext_utf32_char_to_entity(_Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
784 char *entity_src = RSTRING_PTR(entity);
785 long entity_len = RSTRING_LEN(entity); // should always be 8 characters (8 bytes)
786 memcpy(dest, entity_src, entity_len);
797 // trim trailing space if necessary
798 if (!rollback && non_space > dest_ptr && dest != non_space)
799 len = non_space - dest_ptr;
801 len = dest - dest_ptr;
802 VALUE out = rb_str_new(dest_ptr, len);
807 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
810 parser.link_target = str_new_from_string(string);
811 GC_WRAP_STR(parser.link_target, link_target_gc);
812 return _Wikitext_parser_sanitize_link_target(&parser, false);
815 // encodes the input string according to RFCs 2396 and 2718
816 // leading and trailing whitespace trimmed
817 // note that the first character of the target link is not case-sensitive
818 // (this is a recommended application-level constraint; it is not imposed at this level)
819 // this is to allow links like:
820 // ...the [[foo]] is...
821 // to be equivalent to:
822 // thing. [[Foo]] was...
823 static void _Wikitext_parser_encode_link_target(parser_t *parser)
825 VALUE in = string_from_str(parser->link_target);
826 char *input = RSTRING_PTR(in);
827 char *start = input; // remember this so we can check if we're at the start
828 long len = RSTRING_LEN(in);
831 char *end = input + len;
832 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
834 // to avoid most reallocations start with a destination buffer twice the size of the source
835 // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
836 // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
837 // the worst case is where _every_ byte must be written out using 3 bytes
838 long dest_len = len * 2;
839 char *dest = ALLOC_N(char, dest_len);
840 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
841 char *non_space = dest; // remember last non-space character output
842 for (; input < end; input++)
844 if ((dest + 3) > (dest_ptr + dest_len)) // worst case: a single character may grow to 3 characters once encoded
846 // outgrowing buffer, must reallocate
847 char *old_dest = dest;
848 char *old_dest_ptr = dest_ptr;
850 dest = realloc(dest_ptr, dest_len);
853 // would have used reallocf, but this has to run on Linux too, not just Darwin
855 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
858 dest = dest_ptr + (old_dest - old_dest_ptr);
859 non_space = dest_ptr + (non_space - old_dest_ptr);
862 // pass through unreserved characters
863 if (((*input >= 'a') && (*input <= 'z')) ||
864 ((*input >= 'A') && (*input <= 'Z')) ||
865 ((*input >= '0') && (*input <= '9')) ||
874 else if (*input == ' ' && input == start)
875 start++; // we eat leading space
876 else if (*input == ' ' && parser->space_to_underscore)
878 else // everything else gets URL-encoded
881 *dest++ = hex[(unsigned char)(*input) / 16]; // left
882 *dest++ = hex[(unsigned char)(*input) % 16]; // right
888 // trim trailing space if necessary
889 if (non_space > dest_ptr && dest != non_space)
890 dest_len = non_space - dest_ptr;
892 dest_len = dest - dest_ptr;
894 // TOOD: try to avoid this copy by working directly inside link_target buffer
895 str_clear(parser->link_target);
896 str_append(parser->link_target, dest_ptr, dest_len);
900 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
903 parser.space_to_underscore = false;
904 parser.link_target = str_new_from_string(in);
905 GC_WRAP_STR(parser.link_target, link_target_gc);
906 _Wikitext_parser_encode_link_target(&parser);
907 return string_from_str(parser.link_target);
910 // this method exposed for testing only
911 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
914 parser.space_to_underscore = false;
915 parser.link_target = str_new_from_string(in);
916 GC_WRAP_STR(parser.link_target, link_target_gc);
917 _Wikitext_parser_encode_link_target(&parser);
918 return string_from_str(parser.link_target);
921 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
922 // returns 0 (false) otherwise
923 bool _Wikitext_blank(str_t *str)
927 for (char *ptr = str->ptr,
928 *end = str->ptr + str->len;
937 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
940 return; // nothing to do!
941 int scope_includes_separator = IN(SEPARATOR);
942 _Wikitext_pop_from_stack_up_to(parser, NULL, LINK_START, true);
943 str_append(parser->output, link_start, sizeof(link_start) - 1);
944 if (parser->link_target->len > 0)
946 // TODO: make _Wikitext_parser_sanitize_link_target return something else? or append directly to buffer would be much better
947 VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, true);
948 str_append_string(parser->output, sanitized);
949 if (scope_includes_separator)
951 str_append(parser->output, separator, sizeof(separator) - 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_external_link(parser_t *parser)
963 if (!IN(EXT_LINK_START))
964 return; // nothing to do!
966 // store a couple of values before popping
967 int scope_includes_space = IN(SPACE);
968 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
969 _Wikitext_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
971 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
972 if (parser->link_target->len > 0)
974 _Wikitext_append_hyperlink(parser, Qnil, string_from_str(parser->link_target), Qnil, link_class, true);
975 if (scope_includes_space)
977 str_append(parser->output, space, sizeof(space) - 1);
978 if (parser->link_text->len > 0)
979 str_append_str(parser->output, parser->link_text);
982 parser->capture = NULL;
983 str_clear(parser->link_target);
984 str_clear(parser->link_text);
987 void _Wikitext_rollback_failed_link(parser_t *parser)
989 _Wikitext_rollback_failed_internal_link(parser);
990 _Wikitext_rollback_failed_external_link(parser);
993 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
997 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
1001 VALUE autolink = Qtrue;
1002 VALUE line_ending = rb_str_new2("\n");
1003 VALUE external_link_class = rb_str_new2("external");
1004 VALUE mailto_class = rb_str_new2("mailto");
1005 VALUE internal_link_prefix = rb_str_new2("/wiki/");
1006 VALUE img_prefix = rb_str_new2("/images/");
1007 VALUE space_to_underscore = Qtrue;
1008 VALUE minimum_fulltext_token_length = INT2NUM(3);
1009 VALUE base_heading_level = INT2NUM(0);
1011 // process options hash (override defaults)
1012 if (!NIL_P(options) && TYPE(options) == T_HASH)
1014 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1015 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1016 autolink = OVERRIDE_IF_SET(autolink);
1017 line_ending = OVERRIDE_IF_SET(line_ending);
1018 external_link_class = OVERRIDE_IF_SET(external_link_class);
1019 mailto_class = OVERRIDE_IF_SET(mailto_class);
1020 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1021 img_prefix = OVERRIDE_IF_SET(img_prefix);
1022 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1023 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1024 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1027 // no need to call super here; rb_call_super()
1028 rb_iv_set(self, "@autolink", autolink);
1029 rb_iv_set(self, "@line_ending", line_ending);
1030 rb_iv_set(self, "@external_link_class", external_link_class);
1031 rb_iv_set(self, "@mailto_class", mailto_class);
1032 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1033 rb_iv_set(self, "@img_prefix", img_prefix);
1034 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1035 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1036 rb_iv_set(self, "@base_heading_level", base_heading_level);
1040 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1042 for (int i = 0; i < 100000; i++)
1043 Wikitext_parser_parse(1, &string, self);
1047 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1049 // process arguments
1050 VALUE string, options;
1051 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1055 string = StringValue(string);
1057 // process options hash
1058 int base_indent = 0;
1059 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1060 if (!NIL_P(options) && TYPE(options) == T_HASH)
1062 // :indent => 0 (or more)
1063 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1065 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1066 if (indent == Qfalse)
1067 base_indent = -1; // indentation disabled
1070 base_indent = NUM2INT(indent);
1071 if (base_indent < 0)
1076 // :base_heading_level => 0/1/2/3/4/5/6
1077 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1078 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1081 // normalize, regardless of whether this came from instance variable or override
1082 if (base_heading_level < 0)
1083 base_heading_level = 0;
1084 if (base_heading_level > 6)
1085 base_heading_level = 6;
1088 char *p = RSTRING_PTR(string);
1089 long len = RSTRING_LEN(string);
1092 // access these once per parse
1093 VALUE line_ending = rb_iv_get(self, "@line_ending");
1094 line_ending = StringValue(line_ending);
1095 VALUE link_class = rb_iv_get(self, "@external_link_class");
1096 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1097 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1098 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1099 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1101 // set up parser struct to make passing parameters a little easier
1102 parser_t *parser = parser_new();
1103 GC_WRAP_PARSER(parser, parser_gc);
1104 parser->external_link_class = link_class;
1105 parser->mailto_class = mailto_class;
1106 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1107 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1108 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1109 parser->line_ending = str_new_from_string(line_ending);
1110 parser->base_indent = base_indent;
1111 parser->base_heading_level = base_heading_level;
1113 // this simple looping design leads to a single enormous function,
1114 // but it's faster than doing actual recursive descent and also secure in the face of
1115 // malicious input that seeks to overflow the stack
1116 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1117 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1118 // than a straightforward looping translator like this one anyway
1120 _token.type = NO_TOKEN;
1121 token_t *token = NULL;
1124 // note that whenever we grab a token we push it into the line buffer
1125 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1126 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1128 // check to see if we have a token hanging around from a previous iteration of this loop
1131 if (_token.type == NO_TOKEN)
1133 // first time here (haven't started scanning yet)
1135 next_token(token, NULL, p, pe);
1136 ary_push(parser->line_buffer, token->type);
1142 int type = token->type;
1144 // can't declare new variables inside a switch statement, so predeclare them here
1145 long remove_strong = -1;
1146 long remove_em = -1;
1148 // general purpose counters, flags and pointers
1152 str_t *output = NULL;
1154 // The following giant switch statement contains cases for all the possible token types.
1155 // In the most basic sense we are emitting the HTML that corresponds to each token,
1156 // but some tokens require context information in order to decide what to output.
1157 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1158 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1160 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1161 // - the line buffer (records tokens seen so far on the current line)
1162 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1164 // Although this is fairly complicated, there is one key simplifying factor:
1165 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1166 // scope stack (up to the current token) is valid; our translator can take this as a given.
1167 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1168 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1172 if (IN(NO_WIKI_START) || IN(PRE_START))
1174 str_append(parser->output, space, sizeof(space) - 1);
1177 else if (IN(BLOCKQUOTE_START))
1179 // this kind of nesting not allowed (to avoid user confusion)
1180 _Wikitext_pop_excess_elements(parser);
1181 _Wikitext_start_para_if_necessary(parser);
1182 output = parser->capture ? parser->capture : parser->output;
1183 str_append(output, space, sizeof(space) - 1);
1187 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1188 ary_push(parser->line, PRE);
1189 i = ary_count(parser->line, BLOCKQUOTE);
1190 j = ary_count(parser->scope, BLOCKQUOTE);
1193 // must pop (reduce nesting level)
1194 for (i = j - i; i > 0; i--)
1195 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1200 parser->pending_crlf = false;
1201 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1202 _Wikitext_indent(parser);
1203 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1204 ary_push(parser->scope, PRE);
1209 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1211 _Wikitext_emit_pending_crlf_if_necessary(parser);
1212 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1214 else if (IN(BLOCKQUOTE_START))
1216 _Wikitext_rollback_failed_link(parser); // if any
1217 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1218 _Wikitext_indent(parser);
1219 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1220 ary_push(parser->scope, PRE_START);
1221 ary_push(parser->line, PRE_START);
1223 else if (IN(BLOCKQUOTE))
1225 if (token->column_start == 1) // only allowed in first column
1227 _Wikitext_rollback_failed_link(parser); // if any
1228 _Wikitext_pop_all_from_stack(parser);
1229 _Wikitext_indent(parser);
1230 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1231 ary_push(parser->scope, PRE_START);
1232 ary_push(parser->line, PRE_START);
1234 else // PRE_START illegal here
1236 output = parser->capture ? parser->capture : parser->output;
1237 _Wikitext_pop_excess_elements(parser);
1238 _Wikitext_start_para_if_necessary(parser);
1239 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1244 _Wikitext_rollback_failed_link(parser); // if any
1245 _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1246 _Wikitext_indent(parser);
1247 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1248 ary_push(parser->scope, PRE_START);
1249 ary_push(parser->line, PRE_START);
1254 if (IN(NO_WIKI_START) || IN(PRE))
1256 _Wikitext_emit_pending_crlf_if_necessary(parser);
1257 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1262 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1265 output = parser->capture ? parser->capture : parser->output;
1266 _Wikitext_pop_excess_elements(parser);
1267 _Wikitext_start_para_if_necessary(parser);
1268 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1274 if (IN(NO_WIKI_START) || IN(PRE_START))
1275 // no need to check for <pre>; can never appear inside it
1276 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1277 else if (IN(BLOCKQUOTE_START))
1279 // this kind of nesting not allowed (to avoid user confusion)
1280 _Wikitext_pop_excess_elements(parser);
1281 _Wikitext_start_para_if_necessary(parser);
1282 output = parser->capture ? parser->capture : parser->output;
1283 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1288 ary_push(parser->line, BLOCKQUOTE);
1290 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1291 i = ary_count(parser->line, BLOCKQUOTE);
1292 j = ary_count(parser->scope, BLOCKQUOTE);
1294 // 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
1295 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1297 ary_push(parser->line, BLOCKQUOTE);
1301 // now decide whether to push, pop or do nothing
1304 // must push (increase nesting level)
1305 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1306 for (i = i - j; i > 0; i--)
1308 _Wikitext_indent(parser);
1309 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1310 str_append_str(parser->output, parser->line_ending);
1311 ary_push(parser->scope, BLOCKQUOTE);
1316 // must pop (reduce nesting level)
1317 for (i = j - i; i > 0; i--)
1318 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1321 // jump to top of the loop to process token we scanned during lookahead
1326 case BLOCKQUOTE_START:
1327 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1329 _Wikitext_emit_pending_crlf_if_necessary(parser);
1330 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1332 else if (IN(BLOCKQUOTE_START))
1334 // nesting is fine here
1335 _Wikitext_rollback_failed_link(parser); // if any
1336 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1337 _Wikitext_indent(parser);
1338 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1339 str_append_str(parser->output, parser->line_ending);
1340 ary_push(parser->scope, BLOCKQUOTE_START);
1341 ary_push(parser->line, BLOCKQUOTE_START);
1343 else if (IN(BLOCKQUOTE))
1345 if (token->column_start == 1) // only allowed in first column
1347 _Wikitext_rollback_failed_link(parser); // if any
1348 _Wikitext_pop_all_from_stack(parser);
1349 _Wikitext_indent(parser);
1350 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1351 str_append_str(parser->output, parser->line_ending);
1352 ary_push(parser->scope, BLOCKQUOTE_START);
1353 ary_push(parser->line, BLOCKQUOTE_START);
1355 else // BLOCKQUOTE_START illegal here
1357 output = parser->capture ? parser->capture : parser->output;
1358 _Wikitext_pop_excess_elements(parser);
1359 _Wikitext_start_para_if_necessary(parser);
1360 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1365 // would be nice to eliminate the repetition here but it's probably the clearest way
1366 _Wikitext_rollback_failed_link(parser); // if any
1367 _Wikitext_pop_from_stack_up_to(parser, NULL, P, true);
1368 _Wikitext_indent(parser);
1369 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1370 str_append_str(parser->output, parser->line_ending);
1371 ary_push(parser->scope, BLOCKQUOTE_START);
1372 ary_push(parser->line, BLOCKQUOTE_START);
1376 case BLOCKQUOTE_END:
1377 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1379 _Wikitext_emit_pending_crlf_if_necessary(parser);
1380 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1384 if (IN(BLOCKQUOTE_START))
1385 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1388 output = parser->capture ? parser->capture : parser->output;
1389 _Wikitext_pop_excess_elements(parser);
1390 _Wikitext_start_para_if_necessary(parser);
1391 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1397 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1399 _Wikitext_emit_pending_crlf_if_necessary(parser);
1400 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1404 _Wikitext_pop_excess_elements(parser);
1405 _Wikitext_start_para_if_necessary(parser);
1406 ary_push(parser->scope, NO_WIKI_START);
1407 ary_push(parser->line, NO_WIKI_START);
1412 if (IN(NO_WIKI_START))
1413 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1414 _Wikitext_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1417 _Wikitext_pop_excess_elements(parser);
1418 _Wikitext_start_para_if_necessary(parser);
1419 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1424 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1426 _Wikitext_emit_pending_crlf_if_necessary(parser);
1427 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1431 output = parser->capture ? parser->capture : parser->output;
1432 _Wikitext_pop_excess_elements(parser);
1434 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1435 // otherwise, must open them
1438 j = parser->scope->count;
1439 for (j = j - 1; j >= 0; j--)
1441 int val = ary_entry(parser->scope, j);
1442 if (val == STRONG || val == STRONG_START)
1444 str_append(output, strong_end, sizeof(strong_end) - 1);
1447 else if (val == EM || val == EM_START)
1449 str_append(output, em_end, sizeof(em_end) - 1);
1454 if (remove_strong > remove_em) // must remove strong first
1456 ary_pop(parser->scope);
1458 ary_pop(parser->scope);
1459 else // there was no em to remove!, so consider this an opening em tag
1461 str_append(output, em_start, sizeof(em_start) - 1);
1462 ary_push(parser->scope, EM);
1463 ary_push(parser->line, EM);
1466 else if (remove_em > remove_strong) // must remove em first
1468 ary_pop(parser->scope);
1469 if (remove_strong > -1)
1470 ary_pop(parser->scope);
1471 else // there was no strong to remove!, so consider this an opening strong tag
1473 str_append(output, strong_start, sizeof(strong_start) - 1);
1474 ary_push(parser->scope, STRONG);
1475 ary_push(parser->line, STRONG);
1478 else // no strong or em to remove, so this must be a new opening of both
1480 _Wikitext_start_para_if_necessary(parser);
1481 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1482 ary_push(parser->scope, STRONG);
1483 ary_push(parser->line, STRONG);
1484 ary_push(parser->scope, EM);
1485 ary_push(parser->line, EM);
1490 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1492 _Wikitext_emit_pending_crlf_if_necessary(parser);
1493 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1497 output = parser->capture ? parser->capture : parser->output;
1498 if (IN(STRONG_START))
1499 // already in span started with <strong>, no choice but to emit this literally
1500 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1501 else if (IN(STRONG))
1502 // STRONG already seen, this is a closing tag
1503 _Wikitext_pop_from_stack_up_to(parser, output, STRONG, true);
1506 // this is a new opening
1507 _Wikitext_pop_excess_elements(parser);
1508 _Wikitext_start_para_if_necessary(parser);
1509 str_append(output, strong_start, sizeof(strong_start) - 1);
1510 ary_push(parser->scope, STRONG);
1511 ary_push(parser->line, STRONG);
1517 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1519 _Wikitext_emit_pending_crlf_if_necessary(parser);
1520 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1524 output = parser->capture ? parser->capture : parser->output;
1525 if (IN(STRONG_START) || IN(STRONG))
1526 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1529 _Wikitext_pop_excess_elements(parser);
1530 _Wikitext_start_para_if_necessary(parser);
1531 str_append(output, strong_start, sizeof(strong_start) - 1);
1532 ary_push(parser->scope, STRONG_START);
1533 ary_push(parser->line, STRONG_START);
1539 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1541 _Wikitext_emit_pending_crlf_if_necessary(parser);
1542 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1546 output = parser->capture ? parser->capture : parser->output;
1547 if (IN(STRONG_START))
1548 _Wikitext_pop_from_stack_up_to(parser, output, STRONG_START, true);
1551 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1552 _Wikitext_pop_excess_elements(parser);
1553 _Wikitext_start_para_if_necessary(parser);
1554 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1560 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1562 _Wikitext_emit_pending_crlf_if_necessary(parser);
1563 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1567 output = parser->capture ? parser->capture : parser->output;
1569 // already in span started with <em>, no choice but to emit this literally
1570 str_append(output, literal_em, sizeof(literal_em) - 1);
1572 // EM already seen, this is a closing tag
1573 _Wikitext_pop_from_stack_up_to(parser, output, EM, true);
1576 // this is a new opening
1577 _Wikitext_pop_excess_elements(parser);
1578 _Wikitext_start_para_if_necessary(parser);
1579 str_append(output, em_start, sizeof(em_start) - 1);
1580 ary_push(parser->scope, EM);
1581 ary_push(parser->line, EM);
1587 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1589 _Wikitext_emit_pending_crlf_if_necessary(parser);
1590 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1594 output = parser->capture ? parser->capture : parser->output;
1595 if (IN(EM_START) || IN(EM))
1596 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1599 _Wikitext_pop_excess_elements(parser);
1600 _Wikitext_start_para_if_necessary(parser);
1601 str_append(output, em_start, sizeof(em_start) - 1);
1602 ary_push(parser->scope, EM_START);
1603 ary_push(parser->line, EM_START);
1609 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1611 _Wikitext_emit_pending_crlf_if_necessary(parser);
1612 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1616 output = parser->capture ? parser->capture : parser->output;
1618 _Wikitext_pop_from_stack_up_to(parser, output, EM_START, true);
1621 // no EM_START in scope, so must interpret the TT_END without any special meaning
1622 _Wikitext_pop_excess_elements(parser);
1623 _Wikitext_start_para_if_necessary(parser);
1624 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1630 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1632 _Wikitext_emit_pending_crlf_if_necessary(parser);
1633 str_append(parser->output, backtick, sizeof(backtick) - 1);
1637 output = parser->capture ? parser->capture : parser->output;
1639 // already in span started with <tt>, no choice but to emit this literally
1640 str_append(output, backtick, sizeof(backtick) - 1);
1642 // TT (`) already seen, this is a closing tag
1643 _Wikitext_pop_from_stack_up_to(parser, output, TT, true);
1646 // this is a new opening
1647 _Wikitext_pop_excess_elements(parser);
1648 _Wikitext_start_para_if_necessary(parser);
1649 str_append(output, tt_start, sizeof(tt_start) - 1);
1650 ary_push(parser->scope, TT);
1651 ary_push(parser->line, TT);
1657 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1659 _Wikitext_emit_pending_crlf_if_necessary(parser);
1660 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1664 output = parser->capture ? parser->capture : parser->output;
1665 if (IN(TT_START) || IN(TT))
1666 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1669 _Wikitext_pop_excess_elements(parser);
1670 _Wikitext_start_para_if_necessary(parser);
1671 str_append(output, tt_start, sizeof(tt_start) - 1);
1672 ary_push(parser->scope, TT_START);
1673 ary_push(parser->line, TT_START);
1679 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1681 _Wikitext_emit_pending_crlf_if_necessary(parser);
1682 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1686 output = parser->capture ? parser->capture : parser->output;
1688 _Wikitext_pop_from_stack_up_to(parser, output, TT_START, true);
1691 // no TT_START in scope, so must interpret the TT_END without any special meaning
1692 _Wikitext_pop_excess_elements(parser);
1693 _Wikitext_start_para_if_necessary(parser);
1694 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1701 if (IN(NO_WIKI_START) || IN(PRE_START))
1703 // no need to check for PRE; can never appear inside it
1704 str_append(parser->output, token->start, TOKEN_LEN(token));
1708 // count number of tokens in line and scope stacks
1709 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1710 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1711 j = parser->scope->count - bq_count;
1714 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1718 if (type == OL || type == UL)
1721 if (i - k >= 2) // already seen at least one OL or UL
1723 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1728 ary_push(parser->line, type);
1729 ary_push(parser->line, LI);
1731 // want to compare line with scope but can only do so if scope has enough items on it
1734 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1735 ary_entry(parser->scope, i + bq_count - 1) == LI)
1737 // line and scope match at this point: do nothing yet
1741 // item just pushed onto line does not match corresponding slot of scope!
1742 for (; j >= i - 2; j--)
1743 // must pop back before emitting
1744 _Wikitext_pop_from_stack(parser, NULL);
1746 // will emit UL or OL, then LI
1750 else // line stack size now exceeds scope stack size: must increase nesting level
1751 break; // will emit UL or OL, then LI
1755 // not a OL or UL token!
1757 // must close existing LI and re-open new one
1758 _Wikitext_pop_from_stack(parser, NULL);
1761 // item just pushed onto line does not match corresponding slot of scope!
1763 // must pop back before emitting
1764 _Wikitext_pop_from_stack(parser, NULL);
1772 if (type == OL || type == UL)
1774 // if LI is at the top of a stack this is the start of a nested list
1775 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1777 // so we should precede it with a CRLF, and indicate that it's a nested list
1778 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1779 ary_push(parser->scope, NESTED_LIST);
1783 // this is a new list
1784 if (IN(BLOCKQUOTE_START))
1785 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1787 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1791 _Wikitext_indent(parser);
1793 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1794 else if (type == UL)
1795 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1796 ary_push(parser->scope, type);
1797 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1799 else if (type == SPACE)
1800 // silently throw away the optional SPACE token after final list marker
1803 _Wikitext_indent(parser);
1804 str_append(parser->output, li_start, sizeof(li_start) - 1);
1805 ary_push(parser->scope, LI);
1807 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1808 if (type == OL || type == UL)
1811 while (k++, NEXT_TOKEN(), (type = token->type))
1813 if (type == OL || type == UL)
1814 str_append(parser->output, token->start, TOKEN_LEN(token));
1815 else if (type == SPACE && k == 1)
1817 // silently throw away the optional SPACE token after final list marker
1826 // jump to top of the loop to process token we scanned during lookahead
1835 if (IN(NO_WIKI_START) || IN(PRE_START))
1837 // no need to check for PRE; can never appear inside it
1838 str_append(parser->output, token->start, TOKEN_LEN(token));
1842 // pop up to but not including the last BLOCKQUOTE on the scope stack
1843 if (IN(BLOCKQUOTE_START))
1844 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1846 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1848 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1849 ary_push(parser->line, type);
1850 i = ary_count(parser->line, BLOCKQUOTE);
1851 j = ary_count(parser->scope, BLOCKQUOTE);
1853 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1856 // must pop (reduce nesting level)
1857 for (i = j - i; i > 0; i--)
1858 _Wikitext_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1861 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1862 while (NEXT_TOKEN(), (token->type == SPACE))
1865 ary_push(parser->scope, type);
1866 _Wikitext_indent(parser);
1868 // take base_heading_level into account
1869 type += base_heading_level;
1870 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1873 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1874 if (type == H6_START)
1875 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1876 else if (type == H5_START)
1877 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1878 else if (type == H4_START)
1879 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1880 else if (type == H3_START)
1881 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1882 else if (type == H2_START)
1883 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1884 else if (type == H1_START)
1885 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1887 // jump to top of the loop to process token we scanned during lookahead
1891 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1893 _Wikitext_emit_pending_crlf_if_necessary(parser);
1894 str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1898 _Wikitext_rollback_failed_external_link(parser); // if any
1901 // literal output only if not in h6 scope (we stay silent in that case)
1902 _Wikitext_start_para_if_necessary(parser);
1903 str_append(parser->output, literal_h6, sizeof(literal_h6) - 1);
1909 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1911 _Wikitext_emit_pending_crlf_if_necessary(parser);
1912 str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1916 _Wikitext_rollback_failed_external_link(parser); // if any
1919 // literal output only if not in h5 scope (we stay silent in that case)
1920 _Wikitext_start_para_if_necessary(parser);
1921 str_append(parser->output, literal_h5, sizeof(literal_h5) - 1);
1927 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1929 _Wikitext_emit_pending_crlf_if_necessary(parser);
1930 str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1934 _Wikitext_rollback_failed_external_link(parser); // if any
1937 // literal output only if not in h4 scope (we stay silent in that case)
1938 _Wikitext_start_para_if_necessary(parser);
1939 str_append(parser->output, literal_h4, sizeof(literal_h4) - 1);
1945 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1947 _Wikitext_emit_pending_crlf_if_necessary(parser);
1948 str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1952 _Wikitext_rollback_failed_external_link(parser); // if any
1955 // literal output only if not in h3 scope (we stay silent in that case)
1956 _Wikitext_start_para_if_necessary(parser);
1957 str_append(parser->output, literal_h3, sizeof(literal_h3) - 1);
1963 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1965 _Wikitext_emit_pending_crlf_if_necessary(parser);
1966 str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1970 _Wikitext_rollback_failed_external_link(parser); // if any
1973 // literal output only if not in h2 scope (we stay silent in that case)
1974 _Wikitext_start_para_if_necessary(parser);
1975 str_append(parser->output, literal_h2, sizeof(literal_h2) - 1);
1981 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1983 _Wikitext_emit_pending_crlf_if_necessary(parser);
1984 str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1988 _Wikitext_rollback_failed_external_link(parser); // if any
1991 // literal output only if not in h1 scope (we stay silent in that case)
1992 _Wikitext_start_para_if_necessary(parser);
1993 str_append(parser->output, literal_h1, sizeof(literal_h1) - 1);
1999 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2001 _Wikitext_emit_pending_crlf_if_necessary(parser);
2002 str_append(parser->output, token->start, TOKEN_LEN(token));
2006 _Wikitext_pop_excess_elements(parser);
2007 _Wikitext_start_para_if_necessary(parser);
2008 _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), TOKEN_TEXT(token), Qnil, mailto_class, true);
2013 if (IN(NO_WIKI_START))
2014 // user can temporarily suppress autolinking by using <nowiki></nowiki>
2015 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
2016 str_append(parser->output, token->start, TOKEN_LEN(token));
2017 else if (IN(LINK_START))
2019 // if the URI were allowed it would have been handled already in LINK_START
2020 _Wikitext_rollback_failed_internal_link(parser);
2021 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, true);
2023 else if (IN(EXT_LINK_START))
2025 if (parser->link_target->len == 0)
2027 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2028 i = TOKEN_TEXT(token);
2030 if (token->type == SPACE)
2032 ary_push(parser->scope, SPACE);
2033 str_append_string(parser->link_target, i);
2034 str_clear(parser->link_text);
2035 parser->capture = parser->link_text;
2036 token = NULL; // silently consume space
2040 // didn't see the space! this must be an error
2041 _Wikitext_pop_from_stack(parser, NULL);
2042 _Wikitext_pop_excess_elements(parser);
2043 _Wikitext_start_para_if_necessary(parser);
2044 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2045 _Wikitext_append_hyperlink(parser, Qnil, i, Qnil, parser->external_link_class, true);
2049 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2053 _Wikitext_pop_excess_elements(parser);
2054 _Wikitext_start_para_if_necessary(parser);
2055 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, true);
2060 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2061 str_append(parser->output, token->start, TOKEN_LEN(token));
2062 else if (IN(EXT_LINK_START))
2064 if (parser->link_target->len == 0)
2066 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2067 i = TOKEN_TEXT(token);
2069 if (token->type == SPACE)
2071 ary_push(parser->scope, PATH);
2072 ary_push(parser->scope, SPACE);
2073 str_append_string(parser->link_target, i);
2074 str_clear(parser->link_text);
2075 parser->capture = parser->link_text;
2076 token = NULL; // silently consume space
2080 // didn't see the space! this must be an error
2081 _Wikitext_pop_from_stack(parser, NULL);
2082 _Wikitext_pop_excess_elements(parser);
2083 _Wikitext_start_para_if_necessary(parser);
2084 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2085 str_append_string(parser->output, i);
2089 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2093 output = parser->capture ? parser->capture : parser->output;
2094 _Wikitext_pop_excess_elements(parser);
2095 _Wikitext_start_para_if_necessary(parser);
2096 str_append(output, token->start, TOKEN_LEN(token));
2100 // internal links (links to other wiki articles) look like this:
2101 // [[another article]] (would point at, for example, "/wiki/another_article")
2102 // [[the other article|the link text we'll use for it]]
2103 // [[the other article | the link text we'll use for it]]
2104 // MediaWiki has strict requirements about what it will accept as a link target:
2105 // all wikitext markup is disallowed:
2106 // example [[foo ''bar'' baz]]
2107 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2108 // example [[foo <em>bar</em> baz]]
2109 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2110 // example [[foo <nowiki>''</nowiki> baz]]
2111 // renders [[foo '' baz]] (ie. not a link)
2112 // example [[foo <bar> baz]]
2113 // renders [[foo <bar> baz]] (ie. not a link)
2114 // HTML entities and non-ASCII, however, make it through:
2115 // example [[foo €]]
2116 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2117 // example [[foo €]]
2118 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2119 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2120 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2121 // everything else will be rejected
2123 output = parser->capture ? parser->capture : parser->output;
2124 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2126 _Wikitext_emit_pending_crlf_if_necessary(parser);
2127 str_append(output, link_start, sizeof(link_start) - 1);
2129 else if (IN(EXT_LINK_START))
2130 // already in external link scope! (and in fact, must be capturing link_text right now)
2131 str_append(output, link_start, sizeof(link_start) - 1);
2132 else if (IN(LINK_START))
2134 // already in internal link scope! this is a syntax error
2135 _Wikitext_rollback_failed_internal_link(parser);
2136 str_append(parser->output, link_start, sizeof(link_start) - 1);
2138 else if (IN(SEPARATOR))
2140 // scanning internal link text
2142 else // not in internal link scope yet
2144 // will either emit a link, or the rollback of a failed link, so start the para now
2145 _Wikitext_pop_excess_elements(parser);
2146 _Wikitext_start_para_if_necessary(parser);
2147 ary_push(parser->scope, LINK_START);
2149 // look ahead and try to gobble up link target
2150 while (NEXT_TOKEN(), (type = token->type))
2152 if (type == SPACE ||
2153 type == SPECIAL_URI_CHARS ||
2155 type == PRINTABLE ||
2159 type == QUOT_ENTITY ||
2161 type == AMP_ENTITY ||
2162 type == IMG_START ||
2164 type == LEFT_CURLY ||
2165 type == RIGHT_CURLY)
2167 // accumulate these tokens into link_target
2168 if (parser->link_target->len == 0)
2170 str_clear(parser->link_target);
2171 parser->capture = parser->link_target;
2173 if (type == QUOT_ENTITY)
2174 // don't insert the entity, insert the literal quote
2175 str_append(parser->link_target, quote, sizeof(quote) - 1);
2176 else if (type == AMP_ENTITY)
2177 // don't insert the entity, insert the literal ampersand
2178 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2180 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2182 else if (type == LINK_END)
2184 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2185 _Wikitext_rollback_failed_internal_link(parser);
2186 break; // jump back to top of loop (will handle this in LINK_END case below)
2188 else if (type == SEPARATOR)
2190 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2191 _Wikitext_rollback_failed_internal_link(parser);
2194 ary_push(parser->scope, SEPARATOR);
2195 str_clear(parser->link_text);
2196 parser->capture = parser->link_text;
2201 else // unexpected token (syntax error)
2203 _Wikitext_rollback_failed_internal_link(parser);
2204 break; // jump back to top of loop to handle unexpected token
2208 // jump to top of the loop to process token we scanned during lookahead (if any)
2214 output = parser->capture ? parser->capture : parser->output;
2215 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2217 _Wikitext_emit_pending_crlf_if_necessary(parser);
2218 str_append(output, link_end, sizeof(link_end) - 1);
2220 else if (IN(EXT_LINK_START))
2221 // already in external link scope! (and in fact, must be capturing link_text right now)
2222 str_append(output, link_end, sizeof(link_end) - 1);
2223 else if (IN(LINK_START)) // in internal link scope!
2225 if (_Wikitext_blank(parser->link_target))
2227 // special case for inputs like "[[ ]]"
2228 _Wikitext_rollback_failed_internal_link(parser);
2229 str_append(parser->output, link_end, sizeof(link_end) - 1);
2232 if (parser->link_text->len == 0 ||
2233 _Wikitext_blank(parser->link_text))
2235 // use link target as link text
2236 str_clear(parser->link_text);
2237 str_append_string(parser->link_text, _Wikitext_parser_sanitize_link_target(parser, false));
2240 _Wikitext_parser_trim_link_text(parser);
2241 _Wikitext_parser_encode_link_target(parser);
2242 _Wikitext_pop_from_stack_up_to(parser, output, LINK_START, true);
2243 parser->capture = NULL;
2244 _Wikitext_append_hyperlink(parser, prefix, string_from_str(parser->link_target), string_from_str(parser->link_text), Qnil, false);
2245 str_clear(parser->link_target);
2246 str_clear(parser->link_text);
2248 else // wasn't in internal link scope
2250 _Wikitext_pop_excess_elements(parser);
2251 _Wikitext_start_para_if_necessary(parser);
2252 str_append(output, link_end, sizeof(link_end) - 1);
2256 // external links look like this:
2257 // [http://google.com/ the link text]
2258 // [/other/page/on/site see this page]
2259 // strings in square brackets which don't match this syntax get passed through literally; eg:
2260 // he was very angery [sic] about the turn of events
2261 case EXT_LINK_START:
2262 output = parser->capture ? parser->capture : parser->output;
2263 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2265 _Wikitext_emit_pending_crlf_if_necessary(parser);
2266 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2268 else if (IN(EXT_LINK_START))
2269 // already in external link scope! (and in fact, must be capturing link_text right now)
2270 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2271 else if (IN(LINK_START))
2273 // already in internal link scope!
2274 if (parser->link_target->len == 0)
2275 // this must be the first character of our link target
2276 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2278 // link target has already been scanned
2279 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2281 // TODO: possibly roll this condition into the above
2282 // add to existing link target
2283 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2285 else // not in external link scope yet
2287 // will either emit a link, or the rollback of a failed link, so start the para now
2288 _Wikitext_pop_excess_elements(parser);
2289 _Wikitext_start_para_if_necessary(parser);
2291 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2293 if (token->type == URI || token->type == PATH)
2294 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2296 // only get here if there was a syntax error (missing URI)
2297 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2298 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2303 output = parser->capture ? parser->capture : parser->output;
2304 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2306 _Wikitext_emit_pending_crlf_if_necessary(parser);
2307 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2309 else if (IN(EXT_LINK_START))
2311 if (parser->link_text->len == 0)
2312 // syntax error: external link with no link text
2313 _Wikitext_rollback_failed_external_link(parser);
2317 j = IN(PATH) ? Qnil : parser->external_link_class;
2318 _Wikitext_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2319 parser->capture = NULL;
2320 _Wikitext_append_hyperlink(parser, Qnil, string_from_str(parser->link_target), string_from_str(parser->link_text), j, false);
2322 str_clear(parser->link_target);
2323 str_clear(parser->link_text);
2327 _Wikitext_pop_excess_elements(parser);
2328 _Wikitext_start_para_if_necessary(parser);
2329 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2334 output = parser->capture ? parser->capture : parser->output;
2335 _Wikitext_pop_excess_elements(parser);
2336 _Wikitext_start_para_if_necessary(parser);
2337 str_append(output, separator, sizeof(separator) - 1);
2341 output = parser->capture ? parser->capture : parser->output;
2342 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2344 _Wikitext_emit_pending_crlf_if_necessary(parser);
2345 str_append(output, token->start, TOKEN_LEN(token));
2349 // peek ahead to see next token
2350 char *token_ptr = token->start;
2351 int token_len = TOKEN_LEN(token);
2354 if (((type == H6_END) && IN(H6_START)) ||
2355 ((type == H5_END) && IN(H5_START)) ||
2356 ((type == H4_END) && IN(H4_START)) ||
2357 ((type == H3_END) && IN(H3_START)) ||
2358 ((type == H2_END) && IN(H2_START)) ||
2359 ((type == H1_END) && IN(H1_START)))
2361 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2366 _Wikitext_pop_excess_elements(parser);
2367 _Wikitext_start_para_if_necessary(parser);
2368 str_append(output, token_ptr, token_len);
2371 // jump to top of the loop to process token we scanned during lookahead
2379 case DECIMAL_ENTITY:
2380 // pass these through unaltered as they are case sensitive
2381 output = parser->capture ? parser->capture : parser->output;
2382 _Wikitext_pop_excess_elements(parser);
2383 _Wikitext_start_para_if_necessary(parser);
2384 str_append(output, token->start, TOKEN_LEN(token));
2388 // normalize hex entities (downcase them)
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, token->start, TOKEN_LEN(token));
2393 _Wikitext_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2397 output = parser->capture ? parser->capture : parser->output;
2398 _Wikitext_pop_excess_elements(parser);
2399 _Wikitext_start_para_if_necessary(parser);
2400 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2404 output = parser->capture ? parser->capture : parser->output;
2405 _Wikitext_pop_excess_elements(parser);
2406 _Wikitext_start_para_if_necessary(parser);
2407 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2411 output = parser->capture ? parser->capture : parser->output;
2412 _Wikitext_pop_excess_elements(parser);
2413 _Wikitext_start_para_if_necessary(parser);
2414 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2418 output = parser->capture ? parser->capture : parser->output;
2419 _Wikitext_pop_excess_elements(parser);
2420 _Wikitext_start_para_if_necessary(parser);
2421 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2425 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2427 _Wikitext_emit_pending_crlf_if_necessary(parser);
2428 str_append(parser->output, token->start, TOKEN_LEN(token));
2430 else if (parser->capture)
2431 str_append(parser->capture, token->start, TOKEN_LEN(token));
2434 // not currently capturing: will be emitting something on success or failure, so get ready
2435 _Wikitext_pop_excess_elements(parser);
2436 _Wikitext_start_para_if_necessary(parser);
2438 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2439 // will cheat here and abuse the link_target capture buffer to accumulate text
2440 while (NEXT_TOKEN(), (type = token->type))
2442 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2443 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2444 else if (type == IMG_END && parser->link_target->len > 0)
2447 _Wikitext_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2451 else // unexpected token or zero-length target (syntax error)
2454 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2455 if (parser->link_target->len > 0)
2456 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2461 // jump to top of the loop to process token we scanned during lookahead
2462 str_clear(parser->link_target);
2468 i = parser->pending_crlf;
2469 parser->pending_crlf = false;
2470 _Wikitext_rollback_failed_link(parser); // if any
2471 if (IN(NO_WIKI_START) || IN(PRE_START))
2473 ary_clear(parser->line_buffer);
2474 str_append_str(parser->output, parser->line_ending);
2479 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2480 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2481 // don't emit in this case
2482 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2485 if (ary_entry(parser->line_buffer, -2) == PRE)
2487 // only thing on line is the PRE: emit pending line ending (if we had one)
2489 str_append_str(parser->output, parser->line_ending);
2492 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2493 ary_clear(parser->line);
2494 ary_clear(parser->line_buffer);
2496 // peek ahead to see if this is definitely the end of the PRE block
2499 if (type != BLOCKQUOTE && type != PRE)
2500 // this is definitely the end of the block, so don't emit
2501 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, true);
2503 // potentially will emit
2504 parser->pending_crlf = true;
2506 continue; // jump back to top of loop to handle token grabbed via lookahead
2511 parser->pending_crlf = true;
2513 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2514 // as a side effect, this handles any open span-level elements and unclosed blocks
2515 // (with special handling for P blocks and LI elements)
2516 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2517 for (j = parser->scope->count; j > i; j--)
2519 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2521 parser->pending_crlf = false;
2525 // special handling on last iteration through the loop if the top item on the scope is a P block
2526 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2528 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2529 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2530 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2531 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2532 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2534 parser->pending_crlf = false;
2536 // not a paragraph break!
2539 _Wikitext_pop_from_stack(parser, NULL);
2543 // delete the entire contents of the line scope stack and buffer
2544 ary_clear(parser->line);
2545 ary_clear(parser->line_buffer);
2548 case SPECIAL_URI_CHARS:
2554 output = parser->capture ? parser->capture : parser->output;
2555 _Wikitext_pop_excess_elements(parser);
2556 _Wikitext_start_para_if_necessary(parser);
2557 str_append(output, token->start, TOKEN_LEN(token));
2561 output = parser->capture ? parser->capture : parser->output;
2562 _Wikitext_pop_excess_elements(parser);
2563 _Wikitext_start_para_if_necessary(parser);
2564 str_append_string(output, _Wikitext_utf32_char_to_entity(token->code_point)); // convert to entity
2568 // special case for input like " foo\n " (see pre_spec.rb)
2570 ary_entry(parser->line_buffer, -2) == PRE &&
2571 parser->pending_crlf)
2572 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2574 // close any open scopes on hitting EOF
2575 _Wikitext_rollback_failed_link(parser); // if any
2576 _Wikitext_pop_all_from_stack(parser);
2577 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2583 // reset current token; forcing lexer to return another token at the top of the loop
2587 // TODO: make this fast
2588 return string_from_str(parser->output);