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
37 // TODO: consider changing some of the VALUE members (eg link_target) to the more efficient str_t type
40 VALUE output; // for accumulating output to be returned
41 VALUE capture; // for capturing substrings
42 VALUE link_target; // short term "memory" for parsing links
43 VALUE link_text; // short term "memory" for parsing links
44 VALUE external_link_class; // CSS class applied to external links
45 VALUE mailto_class; // CSS class applied to email (mailto) links
46 VALUE img_prefix; // path prepended when emitting img tags
48 str_t *tabulation; // caching buffer for emitting indentation
49 ary_t *scope; // stack for tracking scope
50 ary_t *line; // stack for tracking scope as implied by current line
51 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
52 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
53 int current_indent; // fluctuates according to currently nested structures
54 int base_heading_level;
58 bool space_to_underscore;
61 const char escaped_no_wiki_start[] = "<nowiki>";
62 const char escaped_no_wiki_end[] = "</nowiki>";
63 const char literal_strong_em[] = "'''''";
64 const char literal_strong[] = "'''";
65 const char literal_em[] = "''";
66 const char escaped_em_start[] = "<em>";
67 const char escaped_em_end[] = "</em>";
68 const char escaped_strong_start[] = "<strong>";
69 const char escaped_strong_end[] = "</strong>";
70 const char escaped_tt_start[] = "<tt>";
71 const char escaped_tt_end[] = "</tt>";
72 const char literal_h6[] = "======";
73 const char literal_h5[] = "=====";
74 const char literal_h4[] = "====";
75 const char literal_h3[] = "===";
76 const char literal_h2[] = "==";
77 const char literal_h1[] = "=";
78 const char pre_start[] = "<pre>";
79 const char pre_end[] = "</pre>";
80 const char escaped_pre_start[] = "<pre>";
81 const char escaped_pre_end[] = "</pre>";
82 const char blockquote_start[] = "<blockquote>";
83 const char blockquote_end[] = "</blockquote>";
84 const char escaped_blockquote_start[] = "<blockquote>";
85 const char escaped_blockquote_end[] = "</blockquote>";
86 const char strong_em_start[] = "<strong><em>";
87 const char strong_start[] = "<strong>";
88 const char strong_end[] = "</strong>";
89 const char em_start[] = "<em>";
90 const char em_end[] = "</em>";
91 const char tt_start[] = "<tt>";
92 const char tt_end[] = "</tt>";
93 const char ol_start[] = "<ol>";
94 const char ol_end[] = "</ol>";
95 const char ul_start[] = "<ul>";
96 const char ul_end[] = "</ul>";
97 const char li_start[] = "<li>";
98 const char li_end[] = "</li>";
99 const char h6_start[] = "<h6>";
100 const char h6_end[] = "</h6>";
101 const char h5_start[] = "<h5>";
102 const char h5_end[] = "</h5>";
103 const char h4_start[] = "<h4>";
104 const char h4_end[] = "</h4>";
105 const char h3_start[] = "<h3>";
106 const char h3_end[] = "</h3>";
107 const char h2_start[] = "<h2>";
108 const char h2_end[] = "</h2>";
109 const char h1_start[] = "<h1>";
110 const char h1_end[] = "</h1>";
111 const char p_start[] = "<p>";
112 const char p_end[] = "</p>";
113 const char space[] = " ";
114 const char a_start[] = "<a href=\"";
115 const char a_class[] = "\" class=\"";
116 const char a_start_close[] = "\">";
117 const char a_end[] = "</a>";
118 const char link_start[] = "[[";
119 const char link_end[] = "]]";
120 const char separator[] = "|";
121 const char ext_link_start[] = "[";
122 const char backtick[] = "`";
123 const char quote[] = "\"";
124 const char ampersand[] = "&";
125 const char quot_entity[] = """;
126 const char amp_entity[] = "&";
127 const char lt_entity[] = "<";
128 const char gt_entity[] = ">";
129 const char escaped_blockquote[] = "> ";
130 const char ext_link_end[] = "]";
131 const char literal_img_start[] = "{{";
132 const char img_start[] = "<img src=\"";
133 const char img_end[] = "\" />";
134 const char img_alt[] = "\" alt=\"";
136 // for testing and debugging only
137 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
141 string = StringValue(string);
142 VALUE tokens = rb_ary_new();
143 char *p = RSTRING_PTR(string);
144 long len = RSTRING_LEN(string);
147 next_token(&token, NULL, p, pe);
148 rb_ary_push(tokens, _Wikitext_token(&token));
149 while (token.type != END_OF_FILE)
151 next_token(&token, &token, NULL, pe);
152 rb_ary_push(tokens, _Wikitext_token(&token));
157 // for benchmarking raw tokenization speed only
158 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
162 string = StringValue(string);
163 char *p = RSTRING_PTR(string);
164 long len = RSTRING_LEN(string);
167 next_token(&token, NULL, p, pe);
168 while (token.type != END_OF_FILE)
169 next_token(&token, &token, NULL, pe);
173 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
176 VALUE string, options;
177 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
181 string = StringValue(string);
182 VALUE tokens = rb_ary_new();
184 // check instance variables
185 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
187 // process options hash (can override instance variables)
188 if (!NIL_P(options) && TYPE(options) == T_HASH)
190 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
191 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
193 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
198 char *p = RSTRING_PTR(string);
199 long len = RSTRING_LEN(string);
202 token_t *_token = &token;
203 next_token(&token, NULL, p, pe);
204 while (token.type != END_OF_FILE)
211 if (TOKEN_LEN(_token) >= min_len)
212 rb_ary_push(tokens, TOKEN_TEXT(_token));
215 // ignore everything else
218 next_token(&token, &token, NULL, pe);
223 // we downcase "in place", overwriting the original contents of the buffer and returning the same string
224 VALUE _Wikitext_downcase_bang(VALUE string)
226 char *ptr = RSTRING_PTR(string);
227 long len = RSTRING_LEN(string);
228 for (long i = 0; i < len; i++)
230 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
236 // prepare hyperlink and append it to parser->output
237 // if check_autolink is Qtrue, checks parser->autolink to decide whether to emit a real hyperlink
238 // or merely the literal link target
239 // if link_text is Qnil, the link_target is re-used for the link text
240 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class, VALUE check_autolink)
242 if (check_autolink == Qtrue && !parser->autolink)
243 rb_str_append(parser->output, link_target);
246 rb_str_cat(parser->output, a_start, sizeof(a_start) - 1); // <a href="
247 if (!NIL_P(link_prefix))
248 rb_str_append(parser->output, link_prefix);
249 rb_str_append(parser->output, link_target);
251 // special handling for mailto URIs
252 const char *mailto = "mailto:";
253 if (NIL_P(link_prefix) &&
254 RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
255 strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
256 link_class = parser->mailto_class; // use mailto_class from parser
257 if (link_class != Qnil)
259 rb_str_cat(parser->output, a_class, sizeof(a_class) - 1); // " class="
260 rb_str_append(parser->output, link_class);
262 rb_str_cat(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
263 if (NIL_P(link_text)) // re-use link_target
264 rb_str_append(parser->output, link_target);
266 rb_str_append(parser->output, link_text);
267 rb_str_cat(parser->output, a_end, sizeof(a_end) - 1); // </a>
271 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
273 rb_str_cat(parser->output, img_start, sizeof(img_start) - 1); // <img src="
274 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
275 rb_str_append(parser->output, parser->img_prefix);
276 rb_str_cat(parser->output, token_ptr, token_len);
277 rb_str_cat(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
278 rb_str_cat(parser->output, token_ptr, token_len);
279 rb_str_cat(parser->output, img_end, sizeof(img_end) - 1); // " />
282 // will emit indentation only if we are about to emit any of:
283 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
284 // each time we enter one of those spans must ++ the indentation level
285 void _Wikitext_indent(parser_t *parser)
287 if (parser->base_indent == -1) // indentation disabled
289 int space_count = parser->current_indent + parser->base_indent;
292 char *old_end, *new_end;
293 if (parser->tabulation->len < space_count)
294 str_grow(parser->tabulation, space_count); // reallocates if necessary
295 old_end = parser->tabulation->ptr + parser->tabulation->len;
296 new_end = parser->tabulation->ptr + space_count;
297 while (old_end < new_end)
299 if (space_count > parser->tabulation->len)
300 parser->tabulation->len = space_count;
301 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
303 parser->current_indent += 2;
306 void _Wikitext_dedent(parser_t *parser, VALUE emit)
308 if (parser->base_indent == -1) // indentation disabled
310 parser->current_indent -= 2;
313 int space_count = parser->current_indent + parser->base_indent;
315 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
318 // Pops a single item off the parser's scope stack.
319 // A corresponding closing tag is written to the target string.
320 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
321 void _Wikitext_pop_from_stack(parser_t *parser, VALUE target)
323 int top = ary_entry(parser->scope, -1);
327 target = parser->output;
329 // for headings, take base_heading_level into account
330 if (top >= H1_START && top <= H6_START)
332 top += parser->base_heading_level;
333 // no need to check for underflow (base_heading_level is never negative)
342 rb_str_cat(target, pre_end, sizeof(pre_end) - 1);
343 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
344 _Wikitext_dedent(parser, Qfalse);
348 case BLOCKQUOTE_START:
349 _Wikitext_dedent(parser, Qtrue);
350 rb_str_cat(target, blockquote_end, sizeof(blockquote_end) - 1);
351 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
355 // not a real HTML tag; so nothing to pop
360 rb_str_cat(target, strong_end, sizeof(strong_end) - 1);
365 rb_str_cat(target, em_end, sizeof(em_end) - 1);
370 rb_str_cat(target, tt_end, sizeof(tt_end) - 1);
374 _Wikitext_dedent(parser, Qtrue);
375 rb_str_cat(target, ol_end, sizeof(ol_end) - 1);
376 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
380 _Wikitext_dedent(parser, Qtrue);
381 rb_str_cat(target, ul_end, sizeof(ul_end) - 1);
382 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
386 // next token to pop will be a LI
387 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
388 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
389 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
390 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
391 _Wikitext_dedent(parser, Qtrue); // we really only want to emit the spaces
392 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
396 rb_str_cat(target, li_end, sizeof(li_end) - 1);
397 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
398 _Wikitext_dedent(parser, Qfalse);
402 rb_str_cat(target, h6_end, sizeof(h6_end) - 1);
403 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
404 _Wikitext_dedent(parser, Qfalse);
408 rb_str_cat(target, h5_end, sizeof(h5_end) - 1);
409 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
410 _Wikitext_dedent(parser, Qfalse);
414 rb_str_cat(target, h4_end, sizeof(h4_end) - 1);
415 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
416 _Wikitext_dedent(parser, Qfalse);
420 rb_str_cat(target, h3_end, sizeof(h3_end) - 1);
421 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
422 _Wikitext_dedent(parser, Qfalse);
426 rb_str_cat(target, h2_end, sizeof(h2_end) - 1);
427 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
428 _Wikitext_dedent(parser, Qfalse);
432 rb_str_cat(target, h1_end, sizeof(h1_end) - 1);
433 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
434 _Wikitext_dedent(parser, Qfalse);
438 // not an HTML tag; so nothing to emit
442 // not an HTML tag; so nothing to emit
446 // not an HTML tag; so nothing to emit
450 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
454 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
458 rb_str_cat(target, p_end, sizeof(p_end) - 1);
459 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
460 _Wikitext_dedent(parser, Qfalse);
468 // should probably raise an exception here
471 ary_pop(parser->scope);
474 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
475 // If including is Qtrue then the item itself is also popped.
476 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
477 void _Wikitext_pop_from_stack_up_to(parser_t *parser, VALUE target, int item, VALUE including)
479 int continue_looping = 1;
482 int top = ary_entry(parser->scope, -1);
487 if (including != Qtrue)
489 continue_looping = 0;
491 _Wikitext_pop_from_stack(parser, target);
492 } while (continue_looping);
495 void _Wikitext_pop_all_from_stack(parser_t *parser)
497 for (int i = 0, max = parser->scope->count; i < max; i++)
498 _Wikitext_pop_from_stack(parser, Qnil);
501 void _Wikitext_start_para_if_necessary(parser_t *parser)
503 if (parser->capturing)
506 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
507 if (parser->scope->count == 0 ||
508 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
509 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
511 _Wikitext_indent(parser);
512 rb_str_cat(parser->output, p_start, sizeof(p_start) - 1);
513 ary_push(parser->scope, P);
514 ary_push(parser->line, P);
516 else if (parser->pending_crlf)
519 // already in a paragraph block; convert pending CRLF into a space
520 rb_str_cat(parser->output, space, sizeof(space) - 1);
522 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
523 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
525 parser->pending_crlf = false;
528 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
530 if (parser->pending_crlf)
532 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
533 parser->pending_crlf = false;
537 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
538 // For example, given input like:
543 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
544 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
549 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
550 // but not on the line scope:
555 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
556 // on the line scope.
557 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
558 // entering the for loop.
559 void _Wikitext_pop_excess_elements(parser_t *parser)
561 if (parser->capturing)
563 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
565 // special case for last item on scope
568 // don't auto-pop P if it is only item on scope
569 if (ary_entry(parser->scope, -1) == P)
571 // add P to the line scope to prevent us entering the loop at all next time around
572 ary_push(parser->line, P);
576 _Wikitext_pop_from_stack(parser, parser->output);
580 #define INVALID_ENCODING(msg) do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
582 // convert a single UTF-8 codepoint to UTF-32
583 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
584 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
585 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
586 // raises a RangeError if the supplied character is invalid UTF-8
587 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
588 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
591 if ((unsigned char)src[0] <= 0x7f) // ASCII
596 else if ((src[0] & 0xe0) == 0xc0) // byte starts with 110..... : this should be a two-byte sequence
599 INVALID_ENCODING("truncated byte sequence"); // no second byte
600 else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
601 INVALID_ENCODING("overlong encoding"); // overlong encoding: lead byte of 110..... but code point <= 127
602 else if ((src[1] & 0xc0) != 0x80 )
603 INVALID_ENCODING("malformed byte sequence"); // should have second byte starting with 10......
604 dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
607 else if ((src[0] & 0xf0) == 0xe0) // byte starts with 1110.... : this should be a three-byte sequence
610 INVALID_ENCODING("truncated byte sequence"); // missing second or third byte
611 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
612 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
613 dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
616 else if ((src[0] & 0xf8) == 0xf0) // bytes starts with 11110... : this should be a four-byte sequence
619 INVALID_ENCODING("truncated byte sequence"); // missing second, third, or fourth byte
620 else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
621 INVALID_ENCODING("overlong encoding"); // disallowed by RFC 3629 (codepoints above 0x10ffff)
622 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
623 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
624 dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
627 else // invalid input
628 INVALID_ENCODING("unexpected byte");
632 VALUE _Wikitext_utf32_char_to_entity(uint32_t character)
634 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
635 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
636 char scratch = (character & 0xf000) >> 12;
637 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
638 scratch = (character & 0x0f00) >> 8;
639 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
640 scratch = (character & 0x00f0) >> 4;
641 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
642 scratch = character & 0x000f;
643 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
644 return rb_str_new((const char *)hex_string, sizeof(hex_string));
647 VALUE _Wikitext_parser_trim_link_target(VALUE string)
649 string = StringValue(string);
650 char *src = RSTRING_PTR(string);
651 char *start = src; // remember this so we can check if we're at the start
653 char *non_space = src; // remember last non-space character output
654 long len = RSTRING_LEN(string);
655 char *end = src + len;
667 if (left == start && non_space + 1 == end)
670 return rb_str_new(left, (non_space + 1) - left);
673 // - non-printable (non-ASCII) characters converted to numeric entities
674 // - QUOT and AMP characters converted to named entities
675 // - if rollback is Qtrue, there is no special treatment of spaces
676 // - if rollback is Qfalse, leading and trailing whitespace trimmed
677 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, VALUE rollback)
679 VALUE string = StringValue(parser->link_target); // raises if string is nil or doesn't quack like a string
680 char *src = RSTRING_PTR(string);
681 char *start = src; // remember this so we can check if we're at the start
682 long len = RSTRING_LEN(string);
683 char *end = src + len;
685 // start with a destination buffer twice the size of the source, will realloc if necessary
686 // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
687 // this efficiently handles the most common case (where the size of the buffer doesn't change much)
688 char *dest = ALLOC_N(char, len * 2);
689 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
690 char *non_space = dest; // remember last non-space character output
693 // need at most 8 characters (8 bytes) to display each character
694 if (dest + 8 > dest_ptr + len) // outgrowing buffer, must reallocate
696 char *old_dest = dest;
697 char *old_dest_ptr = dest_ptr;
698 len = len + (end - src) * 8; // allocate enough for worst case
699 dest = realloc(dest_ptr, len); // will never have to realloc more than once
702 // would have used reallocf, but this has to run on Linux too, not just Darwin
704 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
707 dest = dest_ptr + (old_dest - old_dest_ptr);
708 non_space = dest_ptr + (non_space - old_dest_ptr);
711 if (*src == '"') // QUOT
713 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
714 memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
715 dest += sizeof(quot_entity_literal);
717 else if (*src == '&') // AMP
719 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
720 memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
721 dest += sizeof(amp_entity_literal);
723 else if (*src == '<') // LESS_THAN
726 rb_raise(rb_eRangeError, "invalid link text (\"<\" may not appear in link text)");
728 else if (*src == '>') // GREATER_THAN
731 rb_raise(rb_eRangeError, "invalid link text (\">\" may not appear in link text)");
733 else if (*src == ' ' && src == start && rollback == Qfalse)
734 start++; // we eat leading space
735 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
740 else // all others: must convert to entities
743 VALUE entity = _Wikitext_utf32_char_to_entity(_Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
744 char *entity_src = RSTRING_PTR(entity);
745 long entity_len = RSTRING_LEN(entity); // should always be 8 characters (8 bytes)
746 memcpy(dest, entity_src, entity_len);
757 // trim trailing space if necessary
758 if (rollback == Qfalse && non_space > dest_ptr && dest != non_space)
759 len = non_space - dest_ptr;
761 len = dest - dest_ptr;
762 VALUE out = rb_str_new(dest_ptr, len);
767 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
770 parser.link_target = string;
771 return _Wikitext_parser_sanitize_link_target(&parser, Qfalse);
774 // encodes the input string according to RFCs 2396 and 2718
775 // leading and trailing whitespace trimmed
776 // note that the first character of the target link is not case-sensitive
777 // (this is a recommended application-level constraint; it is not imposed at this level)
778 // this is to allow links like:
779 // ...the [[foo]] is...
780 // to be equivalent to:
781 // thing. [[Foo]] was...
782 static void _Wikitext_parser_encode_link_target(parser_t *parser)
784 VALUE in = StringValue(parser->link_target);
785 char *input = RSTRING_PTR(in);
786 char *start = input; // remember this so we can check if we're at the start
787 long len = RSTRING_LEN(in);
790 char *end = input + len;
791 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
793 // to avoid most reallocations start with a destination buffer twice the size of the source
794 // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
795 // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
796 // the worst case is where _every_ byte must be written out using 3 bytes
797 long dest_len = len * 2;
798 char *dest = ALLOC_N(char, dest_len);
799 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
800 char *non_space = dest; // remember last non-space character output
801 for (; input < end; input++)
803 if ((dest + 3) > (dest_ptr + dest_len)) // worst case: a single character may grow to 3 characters once encoded
805 // outgrowing buffer, must reallocate
806 char *old_dest = dest;
807 char *old_dest_ptr = dest_ptr;
809 dest = realloc(dest_ptr, dest_len);
812 // would have used reallocf, but this has to run on Linux too, not just Darwin
814 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
817 dest = dest_ptr + (old_dest - old_dest_ptr);
818 non_space = dest_ptr + (non_space - old_dest_ptr);
821 // pass through unreserved characters
822 if (((*input >= 'a') && (*input <= 'z')) ||
823 ((*input >= 'A') && (*input <= 'Z')) ||
824 ((*input >= '0') && (*input <= '9')) ||
833 else if (*input == ' ' && input == start)
834 start++; // we eat leading space
835 else if (*input == ' ' && parser->space_to_underscore)
837 else // everything else gets URL-encoded
840 *dest++ = hex[(unsigned char)(*input) / 16]; // left
841 *dest++ = hex[(unsigned char)(*input) % 16]; // right
847 // trim trailing space if necessary
848 if (non_space > dest_ptr && dest != non_space)
849 dest_len = non_space - dest_ptr;
851 dest_len = dest - dest_ptr;
852 parser->link_target = rb_str_new(dest_ptr, dest_len);
856 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
859 parser.link_target = in;
860 parser.space_to_underscore = false;
861 _Wikitext_parser_encode_link_target(&parser);
862 return parser.link_target;
865 // this method exposed for testing only
866 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
869 parser.link_target = in;
870 parser.space_to_underscore = false;
871 _Wikitext_parser_encode_link_target(&parser);
872 return parser.link_target;
875 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
876 // returns 0 (false) otherwise
877 int _Wikitext_blank(VALUE str)
879 if (NIL_P(str) || RSTRING_LEN(str) == 0)
881 for (char *ptr = RSTRING_PTR(str),
882 *end = RSTRING_PTR(str) + RSTRING_LEN(str);
891 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
894 return; // nothing to do!
895 int scope_includes_separator = IN(SEPARATOR);
896 _Wikitext_pop_from_stack_up_to(parser, Qnil, LINK_START, Qtrue);
897 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
898 if (!NIL_P(parser->link_target))
900 VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, Qtrue);
901 rb_str_append(parser->output, sanitized);
902 if (scope_includes_separator)
904 rb_str_cat(parser->output, separator, sizeof(separator) - 1);
905 if (!NIL_P(parser->link_text))
906 rb_str_append(parser->output, parser->link_text);
909 parser->capturing = false;
910 parser->link_target = Qnil;
911 parser->link_text = Qnil;
914 void _Wikitext_rollback_failed_external_link(parser_t *parser)
916 if (!IN(EXT_LINK_START))
917 return; // nothing to do!
919 // store a couple of values before popping
920 int scope_includes_space = IN(SPACE);
921 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
922 _Wikitext_pop_from_stack_up_to(parser, Qnil, EXT_LINK_START, Qtrue);
924 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
925 if (!NIL_P(parser->link_target))
927 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, Qnil, link_class, Qtrue);
928 if (scope_includes_space)
930 rb_str_cat(parser->output, space, sizeof(space) - 1);
931 if (!NIL_P(parser->link_text))
932 rb_str_append(parser->output, parser->link_text);
935 parser->capturing = false;
936 parser->link_target = Qnil;
937 parser->link_text = Qnil;
940 void _Wikitext_rollback_failed_link(parser_t *parser)
942 _Wikitext_rollback_failed_internal_link(parser);
943 _Wikitext_rollback_failed_external_link(parser);
946 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
950 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
954 VALUE autolink = Qtrue;
955 VALUE line_ending = rb_str_new2("\n");
956 VALUE external_link_class = rb_str_new2("external");
957 VALUE mailto_class = rb_str_new2("mailto");
958 VALUE internal_link_prefix = rb_str_new2("/wiki/");
959 VALUE img_prefix = rb_str_new2("/images/");
960 VALUE space_to_underscore = Qtrue;
961 VALUE minimum_fulltext_token_length = INT2NUM(3);
962 VALUE base_heading_level = INT2NUM(0);
964 // process options hash (override defaults)
965 if (!NIL_P(options) && TYPE(options) == T_HASH)
967 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
968 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
969 autolink = OVERRIDE_IF_SET(autolink);
970 line_ending = OVERRIDE_IF_SET(line_ending);
971 external_link_class = OVERRIDE_IF_SET(external_link_class);
972 mailto_class = OVERRIDE_IF_SET(mailto_class);
973 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
974 img_prefix = OVERRIDE_IF_SET(img_prefix);
975 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
976 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
977 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
980 // no need to call super here; rb_call_super()
981 rb_iv_set(self, "@autolink", autolink);
982 rb_iv_set(self, "@line_ending", line_ending);
983 rb_iv_set(self, "@external_link_class", external_link_class);
984 rb_iv_set(self, "@mailto_class", mailto_class);
985 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
986 rb_iv_set(self, "@img_prefix", img_prefix);
987 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
988 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
989 rb_iv_set(self, "@base_heading_level", base_heading_level);
993 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
995 for (int i = 0; i < 100000; i++)
996 Wikitext_parser_parse(1, &string, self);
1000 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1002 // process arguments
1003 VALUE string, options;
1004 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1008 string = StringValue(string);
1010 // process options hash
1011 int base_indent = 0;
1012 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1013 if (!NIL_P(options) && TYPE(options) == T_HASH)
1015 // :indent => 0 (or more)
1016 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1018 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1019 if (indent == Qfalse)
1020 base_indent = -1; // indentation disabled
1023 base_indent = NUM2INT(indent);
1024 if (base_indent < 0)
1029 // :base_heading_level => 0/1/2/3/4/5/6
1030 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1031 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1034 // normalize, regardless of whether this came from instance variable or override
1035 if (base_heading_level < 0)
1036 base_heading_level = 0;
1037 if (base_heading_level > 6)
1038 base_heading_level = 6;
1041 char *p = RSTRING_PTR(string);
1042 long len = RSTRING_LEN(string);
1045 // access these once per parse
1046 VALUE line_ending = rb_iv_get(self, "@line_ending");
1047 line_ending = StringValue(line_ending);
1048 VALUE link_class = rb_iv_get(self, "@external_link_class");
1049 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1050 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1051 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1052 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1054 // set up parser struct to make passing parameters a little easier
1055 // eventually this will encapsulate most or all of the variables above
1057 parser_t *parser = &_parser;
1058 parser->output = rb_str_new2("");
1059 parser->capture = Qnil;
1060 parser->capturing = false;
1061 parser->link_target = Qnil;
1062 parser->link_text = Qnil;
1063 parser->external_link_class = link_class;
1064 parser->mailto_class = mailto_class;
1065 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1066 parser->scope = ary_new();
1067 GC_WRAP_ARY(parser->scope, scope_gc);
1068 parser->line = ary_new();
1069 GC_WRAP_ARY(parser->line, line_gc);
1070 parser->line_buffer = ary_new();
1071 GC_WRAP_ARY(parser->line_buffer, line_buffer_gc);
1072 parser->pending_crlf = false;
1073 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1074 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1075 parser->line_ending = str_new_from_string(line_ending);
1076 GC_WRAP_STR(parser->line_ending, line_ending_gc);
1077 parser->base_indent = base_indent;
1078 parser->current_indent = 0;
1079 parser->tabulation = str_new();
1080 GC_WRAP_STR(parser->tabulation, tabulation_gc);
1081 parser->base_heading_level = base_heading_level;
1083 // this simple looping design leads to a single enormous function,
1084 // but it's faster than doing actual recursive descent and also secure in the face of
1085 // malicious input that seeks to overflow the stack
1086 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1087 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1088 // than a straightforward looping translator like this one anyway
1090 _token.type = NO_TOKEN;
1091 token_t *token = NULL;
1094 // note that whenever we grab a token we push it into the line buffer
1095 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1096 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1098 // check to see if we have a token hanging around from a previous iteration of this loop
1101 if (_token.type == NO_TOKEN)
1103 // first time here (haven't started scanning yet)
1105 next_token(token, NULL, p, pe);
1106 ary_push(parser->line_buffer, token->type);
1112 int type = token->type;
1114 // can't declare new variables inside a switch statement, so predeclare them here
1115 long remove_strong = -1;
1116 long remove_em = -1;
1118 // general purpose counters and flags
1123 // The following giant switch statement contains cases for all the possible token types.
1124 // In the most basic sense we are emitting the HTML that corresponds to each token,
1125 // but some tokens require context information in order to decide what to output.
1126 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1127 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1129 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1130 // - the line buffer (records tokens seen so far on the current line)
1131 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1133 // Although this is fairly complicated, there is one key simplifying factor:
1134 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1135 // scope stack (up to the current token) is valid; our translator can take this as a given.
1136 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1137 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1141 if (IN(NO_WIKI_START) || IN(PRE_START))
1143 rb_str_cat(parser->output, space, sizeof(space) - 1);
1146 else if (IN(BLOCKQUOTE_START))
1148 // this kind of nesting not allowed (to avoid user confusion)
1149 _Wikitext_pop_excess_elements(parser);
1150 _Wikitext_start_para_if_necessary(parser);
1151 i = parser->capturing ? parser->capture : parser->output;
1152 rb_str_cat(i, space, sizeof(space) - 1);
1156 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1157 ary_push(parser->line, PRE);
1158 i = ary_count(parser->line, BLOCKQUOTE);
1159 j = ary_count(parser->scope, BLOCKQUOTE);
1162 // must pop (reduce nesting level)
1163 for (i = j - i; i > 0; i--)
1164 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1169 parser->pending_crlf = false;
1170 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1171 _Wikitext_indent(parser);
1172 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1173 ary_push(parser->scope, PRE);
1178 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1180 _Wikitext_emit_pending_crlf_if_necessary(parser);
1181 rb_str_cat(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1183 else if (IN(BLOCKQUOTE_START))
1185 _Wikitext_rollback_failed_link(parser); // if any
1186 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1187 _Wikitext_indent(parser);
1188 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1189 ary_push(parser->scope, PRE_START);
1190 ary_push(parser->line, PRE_START);
1192 else if (IN(BLOCKQUOTE))
1194 if (token->column_start == 1) // only allowed in first column
1196 _Wikitext_rollback_failed_link(parser); // if any
1197 _Wikitext_pop_all_from_stack(parser);
1198 _Wikitext_indent(parser);
1199 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1200 ary_push(parser->scope, PRE_START);
1201 ary_push(parser->line, PRE_START);
1203 else // PRE_START illegal here
1205 i = parser->capturing ? parser->capture : parser->output;
1206 _Wikitext_pop_excess_elements(parser);
1207 _Wikitext_start_para_if_necessary(parser);
1208 rb_str_cat(i, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1213 _Wikitext_rollback_failed_link(parser); // if any
1214 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1215 _Wikitext_indent(parser);
1216 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1217 ary_push(parser->scope, PRE_START);
1218 ary_push(parser->line, PRE_START);
1223 if (IN(NO_WIKI_START) || IN(PRE))
1225 _Wikitext_emit_pending_crlf_if_necessary(parser);
1226 rb_str_cat(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1231 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, Qtrue);
1234 i = parser->capturing ? parser->capture : parser->output;
1235 _Wikitext_pop_excess_elements(parser);
1236 _Wikitext_start_para_if_necessary(parser);
1237 rb_str_cat(i, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1243 if (IN(NO_WIKI_START) || IN(PRE_START))
1244 // no need to check for <pre>; can never appear inside it
1245 rb_str_cat(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1246 else if (IN(BLOCKQUOTE_START))
1248 // this kind of nesting not allowed (to avoid user confusion)
1249 _Wikitext_pop_excess_elements(parser);
1250 _Wikitext_start_para_if_necessary(parser);
1251 i = parser->capturing ? parser->capture : parser->output;
1252 rb_str_cat(i, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1257 ary_push(parser->line, BLOCKQUOTE);
1259 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1260 i = ary_count(parser->line, BLOCKQUOTE);
1261 j = ary_count(parser->scope, BLOCKQUOTE);
1263 // 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
1264 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1266 ary_push(parser->line, BLOCKQUOTE);
1270 // now decide whether to push, pop or do nothing
1273 // must push (increase nesting level)
1274 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1275 for (i = i - j; i > 0; i--)
1277 _Wikitext_indent(parser);
1278 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1279 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1280 ary_push(parser->scope, BLOCKQUOTE);
1285 // must pop (reduce nesting level)
1286 for (i = j - i; i > 0; i--)
1287 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1290 // jump to top of the loop to process token we scanned during lookahead
1295 case BLOCKQUOTE_START:
1296 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1298 _Wikitext_emit_pending_crlf_if_necessary(parser);
1299 rb_str_cat(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1301 else if (IN(BLOCKQUOTE_START))
1303 // nesting is fine here
1304 _Wikitext_rollback_failed_link(parser); // if any
1305 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1306 _Wikitext_indent(parser);
1307 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1308 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1309 ary_push(parser->scope, BLOCKQUOTE_START);
1310 ary_push(parser->line, BLOCKQUOTE_START);
1312 else if (IN(BLOCKQUOTE))
1314 if (token->column_start == 1) // only allowed in first column
1316 _Wikitext_rollback_failed_link(parser); // if any
1317 _Wikitext_pop_all_from_stack(parser);
1318 _Wikitext_indent(parser);
1319 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1320 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1321 ary_push(parser->scope, BLOCKQUOTE_START);
1322 ary_push(parser->line, BLOCKQUOTE_START);
1324 else // BLOCKQUOTE_START illegal here
1326 i = parser->capturing ? parser->capture : parser->output;
1327 _Wikitext_pop_excess_elements(parser);
1328 _Wikitext_start_para_if_necessary(parser);
1329 rb_str_cat(i, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1334 // would be nice to eliminate the repetition here but it's probably the clearest way
1335 _Wikitext_rollback_failed_link(parser); // if any
1336 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1337 _Wikitext_indent(parser);
1338 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1339 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1340 ary_push(parser->scope, BLOCKQUOTE_START);
1341 ary_push(parser->line, BLOCKQUOTE_START);
1345 case BLOCKQUOTE_END:
1346 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1348 _Wikitext_emit_pending_crlf_if_necessary(parser);
1349 rb_str_cat(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1353 if (IN(BLOCKQUOTE_START))
1354 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, Qtrue);
1357 i = parser->capturing ? parser->capture : parser->output;
1358 _Wikitext_pop_excess_elements(parser);
1359 _Wikitext_start_para_if_necessary(parser);
1360 rb_str_cat(i, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1366 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1368 _Wikitext_emit_pending_crlf_if_necessary(parser);
1369 rb_str_cat(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1373 _Wikitext_pop_excess_elements(parser);
1374 _Wikitext_start_para_if_necessary(parser);
1375 ary_push(parser->scope, NO_WIKI_START);
1376 ary_push(parser->line, NO_WIKI_START);
1381 if (IN(NO_WIKI_START))
1382 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1383 _Wikitext_pop_from_stack_up_to(parser, Qnil, NO_WIKI_START, Qtrue);
1386 _Wikitext_pop_excess_elements(parser);
1387 _Wikitext_start_para_if_necessary(parser);
1388 rb_str_cat(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1393 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1395 _Wikitext_emit_pending_crlf_if_necessary(parser);
1396 rb_str_cat(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1400 i = parser->capturing ? parser->capture : parser->output;
1401 _Wikitext_pop_excess_elements(parser);
1403 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1404 // otherwise, must open them
1407 j = parser->scope->count;
1408 for (j = j - 1; j >= 0; j--)
1410 int val = ary_entry(parser->scope, j);
1411 if (val == STRONG || val == STRONG_START)
1413 rb_str_cat(i, strong_end, sizeof(strong_end) - 1);
1416 else if (val == EM || val == EM_START)
1418 rb_str_cat(i, em_end, sizeof(em_end) - 1);
1423 if (remove_strong > remove_em) // must remove strong first
1425 ary_pop(parser->scope);
1427 ary_pop(parser->scope);
1428 else // there was no em to remove!, so consider this an opening em tag
1430 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1431 ary_push(parser->scope, EM);
1432 ary_push(parser->line, EM);
1435 else if (remove_em > remove_strong) // must remove em first
1437 ary_pop(parser->scope);
1438 if (remove_strong > -1)
1439 ary_pop(parser->scope);
1440 else // there was no strong to remove!, so consider this an opening strong tag
1442 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1443 ary_push(parser->scope, STRONG);
1444 ary_push(parser->line, STRONG);
1447 else // no strong or em to remove, so this must be a new opening of both
1449 _Wikitext_start_para_if_necessary(parser);
1450 rb_str_cat(i, strong_em_start, sizeof(strong_em_start) - 1);
1451 ary_push(parser->scope, STRONG);
1452 ary_push(parser->line, STRONG);
1453 ary_push(parser->scope, EM);
1454 ary_push(parser->line, EM);
1459 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1461 _Wikitext_emit_pending_crlf_if_necessary(parser);
1462 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1466 i = parser->capturing ? parser->capture : parser->output;
1467 if (IN(STRONG_START))
1468 // already in span started with <strong>, no choice but to emit this literally
1469 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1470 else if (IN(STRONG))
1471 // STRONG already seen, this is a closing tag
1472 _Wikitext_pop_from_stack_up_to(parser, i, STRONG, Qtrue);
1475 // this is a new opening
1476 _Wikitext_pop_excess_elements(parser);
1477 _Wikitext_start_para_if_necessary(parser);
1478 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1479 ary_push(parser->scope, STRONG);
1480 ary_push(parser->line, STRONG);
1486 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1488 _Wikitext_emit_pending_crlf_if_necessary(parser);
1489 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1493 i = parser->capturing ? parser->capture : parser->output;
1494 if (IN(STRONG_START) || IN(STRONG))
1495 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1498 _Wikitext_pop_excess_elements(parser);
1499 _Wikitext_start_para_if_necessary(parser);
1500 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1501 ary_push(parser->scope, STRONG_START);
1502 ary_push(parser->line, STRONG_START);
1508 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1510 _Wikitext_emit_pending_crlf_if_necessary(parser);
1511 rb_str_cat(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1515 i = parser->capturing ? parser->capture : parser->output;
1516 if (IN(STRONG_START))
1517 _Wikitext_pop_from_stack_up_to(parser, i, STRONG_START, Qtrue);
1520 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1521 _Wikitext_pop_excess_elements(parser);
1522 _Wikitext_start_para_if_necessary(parser);
1523 rb_str_cat(i, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1529 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1531 _Wikitext_emit_pending_crlf_if_necessary(parser);
1532 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1536 i = parser->capturing ? parser->capture : parser->output;
1538 // already in span started with <em>, no choice but to emit this literally
1539 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1541 // EM already seen, this is a closing tag
1542 _Wikitext_pop_from_stack_up_to(parser, i, EM, Qtrue);
1545 // this is a new opening
1546 _Wikitext_pop_excess_elements(parser);
1547 _Wikitext_start_para_if_necessary(parser);
1548 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1549 ary_push(parser->scope, EM);
1550 ary_push(parser->line, EM);
1556 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1558 _Wikitext_emit_pending_crlf_if_necessary(parser);
1559 rb_str_cat(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1563 i = parser->capturing ? parser->capture : parser->output;
1564 if (IN(EM_START) || IN(EM))
1565 rb_str_cat(i, escaped_em_start, sizeof(escaped_em_start) - 1);
1568 _Wikitext_pop_excess_elements(parser);
1569 _Wikitext_start_para_if_necessary(parser);
1570 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1571 ary_push(parser->scope, EM_START);
1572 ary_push(parser->line, EM_START);
1578 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1580 _Wikitext_emit_pending_crlf_if_necessary(parser);
1581 rb_str_cat(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1585 i = parser->capturing ? parser->capture : parser->output;
1587 _Wikitext_pop_from_stack_up_to(parser, i, EM_START, Qtrue);
1590 // no EM_START in scope, so must interpret the TT_END without any special meaning
1591 _Wikitext_pop_excess_elements(parser);
1592 _Wikitext_start_para_if_necessary(parser);
1593 rb_str_cat(i, escaped_em_end, sizeof(escaped_em_end) - 1);
1599 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1601 _Wikitext_emit_pending_crlf_if_necessary(parser);
1602 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1606 i = parser->capturing ? parser->capture : parser->output;
1608 // already in span started with <tt>, no choice but to emit this literally
1609 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1611 // TT (`) already seen, this is a closing tag
1612 _Wikitext_pop_from_stack_up_to(parser, i, TT, Qtrue);
1615 // this is a new opening
1616 _Wikitext_pop_excess_elements(parser);
1617 _Wikitext_start_para_if_necessary(parser);
1618 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1619 ary_push(parser->scope, TT);
1620 ary_push(parser->line, TT);
1626 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1628 _Wikitext_emit_pending_crlf_if_necessary(parser);
1629 rb_str_cat(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1633 i = parser->capturing ? parser->capture : parser->output;
1634 if (IN(TT_START) || IN(TT))
1635 rb_str_cat(i, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1638 _Wikitext_pop_excess_elements(parser);
1639 _Wikitext_start_para_if_necessary(parser);
1640 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1641 ary_push(parser->scope, TT_START);
1642 ary_push(parser->line, TT_START);
1648 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1650 _Wikitext_emit_pending_crlf_if_necessary(parser);
1651 rb_str_cat(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1655 i = parser->capturing ? parser->capture : parser->output;
1657 _Wikitext_pop_from_stack_up_to(parser, i, TT_START, Qtrue);
1660 // no TT_START in scope, so must interpret the TT_END without any special meaning
1661 _Wikitext_pop_excess_elements(parser);
1662 _Wikitext_start_para_if_necessary(parser);
1663 rb_str_cat(i, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1670 if (IN(NO_WIKI_START) || IN(PRE_START))
1672 // no need to check for PRE; can never appear inside it
1673 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1677 // count number of tokens in line and scope stacks
1678 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1679 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1680 j = parser->scope->count - bq_count;
1683 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1687 if (type == OL || type == UL)
1690 if (i - k >= 2) // already seen at least one OL or UL
1692 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1697 ary_push(parser->line, type);
1698 ary_push(parser->line, LI);
1700 // want to compare line with scope but can only do so if scope has enough items on it
1703 if (ary_entry(parser->scope, i + bq_count - 2) == type && ary_entry(parser->scope, i + bq_count - 1) == LI)
1705 // line and scope match at this point: do nothing yet
1709 // item just pushed onto line does not match corresponding slot of scope!
1710 for (; j >= i - 2; j--)
1711 // must pop back before emitting
1712 _Wikitext_pop_from_stack(parser, Qnil);
1714 // will emit UL or OL, then LI
1718 else // line stack size now exceeds scope stack size: must increase nesting level
1719 break; // will emit UL or OL, then LI
1723 // not a OL or UL token!
1725 // must close existing LI and re-open new one
1726 _Wikitext_pop_from_stack(parser, Qnil);
1729 // item just pushed onto line does not match corresponding slot of scope!
1731 // must pop back before emitting
1732 _Wikitext_pop_from_stack(parser, Qnil);
1740 if (type == OL || type == UL)
1742 // if LI is at the top of a stack this is the start of a nested list
1743 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1745 // so we should precede it with a CRLF, and indicate that it's a nested list
1746 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1747 ary_push(parser->scope, NESTED_LIST);
1751 // this is a new list
1752 if (IN(BLOCKQUOTE_START))
1753 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1755 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1759 _Wikitext_indent(parser);
1761 rb_str_cat(parser->output, ol_start, sizeof(ol_start) - 1);
1762 else if (type == UL)
1763 rb_str_cat(parser->output, ul_start, sizeof(ul_start) - 1);
1764 ary_push(parser->scope, type);
1765 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1767 else if (type == SPACE)
1768 // silently throw away the optional SPACE token after final list marker
1771 _Wikitext_indent(parser);
1772 rb_str_cat(parser->output, li_start, sizeof(li_start) - 1);
1773 ary_push(parser->scope, LI);
1775 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1776 if (type == OL || type == UL)
1779 while (k++, NEXT_TOKEN(), (type = token->type))
1781 if (type == OL || type == UL)
1782 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1783 else if (type == SPACE && k == 1)
1785 // silently throw away the optional SPACE token after final list marker
1794 // jump to top of the loop to process token we scanned during lookahead
1803 if (IN(NO_WIKI_START) || IN(PRE_START))
1805 // no need to check for PRE; can never appear inside it
1806 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1810 // pop up to but not including the last BLOCKQUOTE on the scope stack
1811 if (IN(BLOCKQUOTE_START))
1812 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1814 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1816 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1817 ary_push(parser->line, type);
1818 i = ary_count(parser->line, BLOCKQUOTE);
1819 j = ary_count(parser->scope, BLOCKQUOTE);
1821 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1824 // must pop (reduce nesting level)
1825 for (i = j - i; i > 0; i--)
1826 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1829 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1830 while (NEXT_TOKEN(), (token->type == SPACE))
1833 ary_push(parser->scope, type);
1834 _Wikitext_indent(parser);
1836 // take base_heading_level into account
1837 type += base_heading_level;
1838 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1841 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1842 if (type == H6_START)
1843 rb_str_cat(parser->output, h6_start, sizeof(h6_start) - 1);
1844 else if (type == H5_START)
1845 rb_str_cat(parser->output, h5_start, sizeof(h5_start) - 1);
1846 else if (type == H4_START)
1847 rb_str_cat(parser->output, h4_start, sizeof(h4_start) - 1);
1848 else if (type == H3_START)
1849 rb_str_cat(parser->output, h3_start, sizeof(h3_start) - 1);
1850 else if (type == H2_START)
1851 rb_str_cat(parser->output, h2_start, sizeof(h2_start) - 1);
1852 else if (type == H1_START)
1853 rb_str_cat(parser->output, h1_start, sizeof(h1_start) - 1);
1855 // jump to top of the loop to process token we scanned during lookahead
1859 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1861 _Wikitext_emit_pending_crlf_if_necessary(parser);
1862 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1866 _Wikitext_rollback_failed_external_link(parser); // if any
1869 // literal output only if not in h6 scope (we stay silent in that case)
1870 _Wikitext_start_para_if_necessary(parser);
1871 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1877 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1879 _Wikitext_emit_pending_crlf_if_necessary(parser);
1880 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1884 _Wikitext_rollback_failed_external_link(parser); // if any
1887 // literal output only if not in h5 scope (we stay silent in that case)
1888 _Wikitext_start_para_if_necessary(parser);
1889 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1895 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1897 _Wikitext_emit_pending_crlf_if_necessary(parser);
1898 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1902 _Wikitext_rollback_failed_external_link(parser); // if any
1905 // literal output only if not in h4 scope (we stay silent in that case)
1906 _Wikitext_start_para_if_necessary(parser);
1907 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1913 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1915 _Wikitext_emit_pending_crlf_if_necessary(parser);
1916 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1920 _Wikitext_rollback_failed_external_link(parser); // if any
1923 // literal output only if not in h3 scope (we stay silent in that case)
1924 _Wikitext_start_para_if_necessary(parser);
1925 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1931 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1933 _Wikitext_emit_pending_crlf_if_necessary(parser);
1934 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1938 _Wikitext_rollback_failed_external_link(parser); // if any
1941 // literal output only if not in h2 scope (we stay silent in that case)
1942 _Wikitext_start_para_if_necessary(parser);
1943 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1949 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1951 _Wikitext_emit_pending_crlf_if_necessary(parser);
1952 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1956 _Wikitext_rollback_failed_external_link(parser); // if any
1959 // literal output only if not in h1 scope (we stay silent in that case)
1960 _Wikitext_start_para_if_necessary(parser);
1961 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1967 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1969 _Wikitext_emit_pending_crlf_if_necessary(parser);
1970 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1974 _Wikitext_pop_excess_elements(parser);
1975 _Wikitext_start_para_if_necessary(parser);
1976 _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), TOKEN_TEXT(token), Qnil, mailto_class, Qtrue);
1981 if (IN(NO_WIKI_START))
1982 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1983 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1984 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1985 else if (IN(LINK_START))
1987 // if the URI were allowed it would have been handled already in LINK_START
1988 _Wikitext_rollback_failed_internal_link(parser);
1989 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
1991 else if (IN(EXT_LINK_START))
1993 if (NIL_P(parser->link_target))
1995 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1996 i = TOKEN_TEXT(token);
1998 if (token->type == SPACE)
2000 ary_push(parser->scope, SPACE);
2001 parser->link_target = i;
2002 parser->link_text = rb_str_new2("");
2003 parser->capture = parser->link_text;
2004 parser->capturing = true;
2005 token = NULL; // silently consume space
2009 // didn't see the space! this must be an error
2010 _Wikitext_pop_from_stack(parser, Qnil);
2011 _Wikitext_pop_excess_elements(parser);
2012 _Wikitext_start_para_if_necessary(parser);
2013 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2014 _Wikitext_append_hyperlink(parser, Qnil, i, Qnil, parser->external_link_class, Qtrue);
2019 if (NIL_P(parser->link_text))
2020 // this must be the first part of our link text
2021 parser->link_text = TOKEN_TEXT(token);
2023 // add to existing link text
2024 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2029 _Wikitext_pop_excess_elements(parser);
2030 _Wikitext_start_para_if_necessary(parser);
2031 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
2036 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2037 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2038 else if (IN(EXT_LINK_START))
2040 if (NIL_P(parser->link_target))
2042 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2043 i = TOKEN_TEXT(token);
2045 if (token->type == SPACE)
2047 ary_push(parser->scope, PATH);
2048 ary_push(parser->scope, SPACE);
2049 parser->link_target = i;
2050 parser->link_text = rb_str_new2("");
2051 parser->capture = parser->link_text;
2052 parser->capturing = true;
2053 token = NULL; // silently consume space
2057 // didn't see the space! this must be an error
2058 _Wikitext_pop_from_stack(parser, Qnil);
2059 _Wikitext_pop_excess_elements(parser);
2060 _Wikitext_start_para_if_necessary(parser);
2061 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2062 rb_str_append(parser->output, i);
2067 if (NIL_P(parser->link_text))
2068 // this must be the first part of our link text
2069 parser->link_text = TOKEN_TEXT(token);
2071 // add to existing link text
2072 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2077 i = parser->capturing ? parser->capture : parser->output;
2078 _Wikitext_pop_excess_elements(parser);
2079 _Wikitext_start_para_if_necessary(parser);
2080 rb_str_cat(i, 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 i = parser->capturing ? parser->capture : parser->output;
2108 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2110 _Wikitext_emit_pending_crlf_if_necessary(parser);
2111 rb_str_cat(i, 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 rb_str_cat(i, 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 rb_str_cat(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 (NIL_P(parser->link_target))
2154 parser->link_target = rb_str_new2("");
2155 parser->capture = parser->link_target;
2156 parser->capturing = true;
2158 if (type == QUOT_ENTITY)
2159 // don't insert the entity, insert the literal quote
2160 rb_str_cat(parser->link_target, quote, sizeof(quote) - 1);
2161 else if (type == AMP_ENTITY)
2162 // don't insert the entity, insert the literal ampersand
2163 rb_str_cat(parser->link_target, ampersand, sizeof(ampersand) - 1);
2165 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2167 else if (type == LINK_END)
2169 if (NIL_P(parser->link_target)) // bail for inputs like "[[]]"
2170 _Wikitext_rollback_failed_internal_link(parser);
2171 break; // jump back to top of loop (will handle this in LINK_END case below)
2173 else if (type == SEPARATOR)
2175 if (NIL_P(parser->link_target)) // bail for inputs like "[[|"
2176 _Wikitext_rollback_failed_internal_link(parser);
2179 ary_push(parser->scope, SEPARATOR);
2180 parser->link_text = rb_str_new2("");
2181 parser->capture = parser->link_text;
2182 parser->capturing = true;
2187 else // unexpected token (syntax error)
2189 _Wikitext_rollback_failed_internal_link(parser);
2190 break; // jump back to top of loop to handle unexpected token
2194 // jump to top of the loop to process token we scanned during lookahead (if any)
2200 i = parser->capturing ? parser->capture : parser->output;
2201 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2203 _Wikitext_emit_pending_crlf_if_necessary(parser);
2204 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2206 else if (IN(EXT_LINK_START))
2207 // already in external link scope! (and in fact, must be capturing link_text right now)
2208 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2209 else if (IN(LINK_START)) // in internal link scope!
2211 if (_Wikitext_blank(parser->link_target))
2213 // special case for inputs like "[[ ]]"
2214 _Wikitext_rollback_failed_internal_link(parser);
2215 rb_str_cat(parser->output, link_end, sizeof(link_end) - 1);
2218 if (NIL_P(parser->link_text) ||
2219 RSTRING_LEN(parser->link_text) == 0 ||
2220 _Wikitext_blank(parser->link_text))
2221 // use link target as link text
2222 parser->link_text = _Wikitext_parser_sanitize_link_target(parser, Qfalse);
2224 parser->link_text = _Wikitext_parser_trim_link_target(parser->link_text);
2225 _Wikitext_parser_encode_link_target(parser);
2226 _Wikitext_pop_from_stack_up_to(parser, i, LINK_START, Qtrue);
2227 parser->capture = Qnil;
2228 parser->capturing = false;
2229 _Wikitext_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, Qfalse);
2230 parser->link_target = Qnil;
2231 parser->link_text = Qnil;
2233 else // wasn't in internal link scope
2235 _Wikitext_pop_excess_elements(parser);
2236 _Wikitext_start_para_if_necessary(parser);
2237 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2241 // external links look like this:
2242 // [http://google.com/ the link text]
2243 // [/other/page/on/site see this page]
2244 // strings in square brackets which don't match this syntax get passed through literally; eg:
2245 // he was very angery [sic] about the turn of events
2246 case EXT_LINK_START:
2247 i = parser->capturing ? parser->capture : parser->output;
2248 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2250 _Wikitext_emit_pending_crlf_if_necessary(parser);
2251 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2253 else if (IN(EXT_LINK_START))
2254 // already in external link scope! (and in fact, must be capturing link_text right now)
2255 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2256 else if (IN(LINK_START))
2258 // already in internal link scope!
2259 i = rb_str_new(ext_link_start, sizeof(ext_link_start) - 1);
2260 if (NIL_P(parser->link_target))
2261 // this must be the first character of our link target
2262 parser->link_target = i;
2265 // link target has already been scanned
2266 if (NIL_P(parser->link_text))
2267 // this must be the first character of our link text
2268 parser->link_text = i;
2270 // add to existing link text
2271 rb_str_append(parser->link_text, i);
2274 // add to existing link target
2275 rb_str_append(parser->link_target, i);
2277 else // not in external link scope yet
2279 // will either emit a link, or the rollback of a failed link, so start the para now
2280 _Wikitext_pop_excess_elements(parser);
2281 _Wikitext_start_para_if_necessary(parser);
2283 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2285 if (token->type == URI || token->type == PATH)
2286 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2288 // only get here if there was a syntax error (missing URI)
2289 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2290 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2295 i = parser->capturing ? parser->capture : parser->output;
2296 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2298 _Wikitext_emit_pending_crlf_if_necessary(parser);
2299 rb_str_cat(i, ext_link_end, sizeof(ext_link_end) - 1);
2301 else if (IN(EXT_LINK_START))
2303 if (NIL_P(parser->link_text))
2304 // syntax error: external link with no link text
2305 _Wikitext_rollback_failed_external_link(parser);
2309 j = IN(PATH) ? Qnil : parser->external_link_class;
2310 _Wikitext_pop_from_stack_up_to(parser, i, EXT_LINK_START, Qtrue);
2311 parser->capture = Qnil;
2312 parser->capturing = false;
2313 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, Qfalse);
2315 parser->link_target = Qnil;
2316 parser->link_text = Qnil;
2320 _Wikitext_pop_excess_elements(parser);
2321 _Wikitext_start_para_if_necessary(parser);
2322 rb_str_cat(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2327 i = parser->capturing ? parser->capture : parser->output;
2328 _Wikitext_pop_excess_elements(parser);
2329 _Wikitext_start_para_if_necessary(parser);
2330 rb_str_cat(i, separator, sizeof(separator) - 1);
2334 i = parser->capturing ? parser->capture : parser->output;
2335 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2337 _Wikitext_emit_pending_crlf_if_necessary(parser);
2338 rb_str_cat(i, token->start, TOKEN_LEN(token));
2342 // peek ahead to see next token
2343 char *token_ptr = token->start;
2344 int token_len = TOKEN_LEN(token);
2347 if (((type == H6_END) && IN(H6_START)) ||
2348 ((type == H5_END) && IN(H5_START)) ||
2349 ((type == H4_END) && IN(H4_START)) ||
2350 ((type == H3_END) && IN(H3_START)) ||
2351 ((type == H2_END) && IN(H2_START)) ||
2352 ((type == H1_END) && IN(H1_START)))
2354 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2359 _Wikitext_pop_excess_elements(parser);
2360 _Wikitext_start_para_if_necessary(parser);
2361 rb_str_cat(i, token_ptr, token_len);
2364 // jump to top of the loop to process token we scanned during lookahead
2372 case DECIMAL_ENTITY:
2373 // pass these through unaltered as they are case sensitive
2374 i = parser->capturing ? parser->capture : parser->output;
2375 _Wikitext_pop_excess_elements(parser);
2376 _Wikitext_start_para_if_necessary(parser);
2377 rb_str_cat(i, token->start, TOKEN_LEN(token));
2381 // normalize hex entities (downcase them)
2382 i = parser->capturing ? parser->capture : parser->output;
2383 _Wikitext_pop_excess_elements(parser);
2384 _Wikitext_start_para_if_necessary(parser);
2385 rb_str_append(i, _Wikitext_downcase_bang(TOKEN_TEXT(token)));
2389 i = parser->capturing ? parser->capture : parser->output;
2390 _Wikitext_pop_excess_elements(parser);
2391 _Wikitext_start_para_if_necessary(parser);
2392 rb_str_cat(i, quot_entity, sizeof(quot_entity) - 1);
2396 i = parser->capturing ? parser->capture : parser->output;
2397 _Wikitext_pop_excess_elements(parser);
2398 _Wikitext_start_para_if_necessary(parser);
2399 rb_str_cat(i, amp_entity, sizeof(amp_entity) - 1);
2403 i = parser->capturing ? parser->capture : parser->output;
2404 _Wikitext_pop_excess_elements(parser);
2405 _Wikitext_start_para_if_necessary(parser);
2406 rb_str_cat(i, lt_entity, sizeof(lt_entity) - 1);
2410 i = parser->capturing ? parser->capture : parser->output;
2411 _Wikitext_pop_excess_elements(parser);
2412 _Wikitext_start_para_if_necessary(parser);
2413 rb_str_cat(i, gt_entity, sizeof(gt_entity) - 1);
2417 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2419 _Wikitext_emit_pending_crlf_if_necessary(parser);
2420 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2422 else if (parser->capturing)
2423 rb_str_cat(parser->capture, token->start, TOKEN_LEN(token));
2426 // not currently capturing: will be emitting something on success or failure, so get ready
2427 _Wikitext_pop_excess_elements(parser);
2428 _Wikitext_start_para_if_necessary(parser);
2430 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2431 // will cheat here and abuse the link_target capture buffer to accumulate text
2432 if (NIL_P(parser->link_target))
2433 parser->link_target = rb_str_new2("");
2434 while (NEXT_TOKEN(), (type = token->type))
2436 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2437 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2438 else if (type == IMG_END && RSTRING_LEN(parser->link_target) > 0)
2441 _Wikitext_append_img(parser, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2445 else // unexpected token or zero-length target (syntax error)
2448 rb_str_cat(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2449 rb_str_cat(parser->output, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2454 // jump to top of the loop to process token we scanned during lookahead
2455 parser->link_target = Qnil;
2461 i = parser->pending_crlf;
2462 parser->pending_crlf = false;
2463 _Wikitext_rollback_failed_link(parser); // if any
2464 if (IN(NO_WIKI_START) || IN(PRE_START))
2466 ary_clear(parser->line_buffer);
2467 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2472 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2473 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2474 // don't emit in this case
2475 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2478 if (ary_entry(parser->line_buffer, -2) == PRE)
2480 // only thing on line is the PRE: emit pending line ending (if we had one)
2482 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2485 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2486 ary_clear(parser->line);
2487 ary_clear(parser->line_buffer);
2489 // peek ahead to see if this is definitely the end of the PRE block
2492 if (type != BLOCKQUOTE && type != PRE)
2493 // this is definitely the end of the block, so don't emit
2494 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2496 // potentially will emit
2497 parser->pending_crlf = true;
2499 continue; // jump back to top of loop to handle token grabbed via lookahead
2504 parser->pending_crlf = true;
2506 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2507 // as a side effect, this handles any open span-level elements and unclosed blocks
2508 // (with special handling for P blocks and LI elements)
2509 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2510 for (j = parser->scope->count; j > i; j--)
2512 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2514 parser->pending_crlf = false;
2518 // special handling on last iteration through the loop if the top item on the scope is a P block
2519 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2521 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2522 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2523 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2524 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2525 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2527 parser->pending_crlf = false;
2529 // not a paragraph break!
2532 _Wikitext_pop_from_stack(parser, Qnil);
2536 // delete the entire contents of the line scope stack and buffer
2537 ary_clear(parser->line);
2538 ary_clear(parser->line_buffer);
2541 case SPECIAL_URI_CHARS:
2547 i = parser->capturing ? parser->capture : parser->output;
2548 _Wikitext_pop_excess_elements(parser);
2549 _Wikitext_start_para_if_necessary(parser);
2550 rb_str_cat(i, token->start, TOKEN_LEN(token));
2554 i = parser->capturing ? parser->capture : parser->output;
2555 _Wikitext_pop_excess_elements(parser);
2556 _Wikitext_start_para_if_necessary(parser);
2557 rb_str_append(i, _Wikitext_utf32_char_to_entity(token->code_point)); // convert to entity
2561 // special case for input like " foo\n " (see pre_spec.rb)
2563 ary_entry(parser->line_buffer, -2) == PRE &&
2564 parser->pending_crlf)
2565 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2567 // close any open scopes on hitting EOF
2568 _Wikitext_rollback_failed_link(parser); // if any
2569 _Wikitext_pop_all_from_stack(parser);
2570 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2576 // reset current token; forcing lexer to return another token at the top of the loop
2580 return parser->output;