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
47 ary_t *scope; // stack for tracking scope
48 ary_t *line; // stack for tracking scope as implied by current line
49 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
52 bool space_to_underscore;
54 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
55 int current_indent; // fluctuates according to currently nested structures
56 str_t *tabulation; // caching buffer for emitting indentation
57 int base_heading_level;
60 const char escaped_no_wiki_start[] = "<nowiki>";
61 const char escaped_no_wiki_end[] = "</nowiki>";
62 const char literal_strong_em[] = "'''''";
63 const char literal_strong[] = "'''";
64 const char literal_em[] = "''";
65 const char escaped_em_start[] = "<em>";
66 const char escaped_em_end[] = "</em>";
67 const char escaped_strong_start[] = "<strong>";
68 const char escaped_strong_end[] = "</strong>";
69 const char escaped_tt_start[] = "<tt>";
70 const char escaped_tt_end[] = "</tt>";
71 const char literal_h6[] = "======";
72 const char literal_h5[] = "=====";
73 const char literal_h4[] = "====";
74 const char literal_h3[] = "===";
75 const char literal_h2[] = "==";
76 const char literal_h1[] = "=";
77 const char pre_start[] = "<pre>";
78 const char pre_end[] = "</pre>";
79 const char escaped_pre_start[] = "<pre>";
80 const char escaped_pre_end[] = "</pre>";
81 const char blockquote_start[] = "<blockquote>";
82 const char blockquote_end[] = "</blockquote>";
83 const char escaped_blockquote_start[] = "<blockquote>";
84 const char escaped_blockquote_end[] = "</blockquote>";
85 const char strong_em_start[] = "<strong><em>";
86 const char strong_start[] = "<strong>";
87 const char strong_end[] = "</strong>";
88 const char em_start[] = "<em>";
89 const char em_end[] = "</em>";
90 const char tt_start[] = "<tt>";
91 const char tt_end[] = "</tt>";
92 const char ol_start[] = "<ol>";
93 const char ol_end[] = "</ol>";
94 const char ul_start[] = "<ul>";
95 const char ul_end[] = "</ul>";
96 const char li_start[] = "<li>";
97 const char li_end[] = "</li>";
98 const char h6_start[] = "<h6>";
99 const char h6_end[] = "</h6>";
100 const char h5_start[] = "<h5>";
101 const char h5_end[] = "</h5>";
102 const char h4_start[] = "<h4>";
103 const char h4_end[] = "</h4>";
104 const char h3_start[] = "<h3>";
105 const char h3_end[] = "</h3>";
106 const char h2_start[] = "<h2>";
107 const char h2_end[] = "</h2>";
108 const char h1_start[] = "<h1>";
109 const char h1_end[] = "</h1>";
110 const char p_start[] = "<p>";
111 const char p_end[] = "</p>";
112 const char space[] = " ";
113 const char a_start[] = "<a href=\"";
114 const char a_class[] = "\" class=\"";
115 const char a_start_close[] = "\">";
116 const char a_end[] = "</a>";
117 const char link_start[] = "[[";
118 const char link_end[] = "]]";
119 const char separator[] = "|";
120 const char ext_link_start[] = "[";
121 const char backtick[] = "`";
122 const char quote[] = "\"";
123 const char ampersand[] = "&";
124 const char quot_entity[] = """;
125 const char amp_entity[] = "&";
126 const char lt_entity[] = "<";
127 const char gt_entity[] = ">";
128 const char escaped_blockquote[] = "> ";
129 const char ext_link_end[] = "]";
130 const char literal_img_start[] = "{{";
131 const char img_start[] = "<img src=\"";
132 const char img_end[] = "\" />";
133 const char img_alt[] = "\" alt=\"";
135 // for testing and debugging only
136 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
140 string = StringValue(string);
141 VALUE tokens = rb_ary_new();
142 char *p = RSTRING_PTR(string);
143 long len = RSTRING_LEN(string);
146 next_token(&token, NULL, p, pe);
147 rb_ary_push(tokens, _Wikitext_token(&token));
148 while (token.type != END_OF_FILE)
150 next_token(&token, &token, NULL, pe);
151 rb_ary_push(tokens, _Wikitext_token(&token));
156 // for benchmarking raw tokenization speed only
157 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
161 string = StringValue(string);
162 char *p = RSTRING_PTR(string);
163 long len = RSTRING_LEN(string);
166 next_token(&token, NULL, p, pe);
167 while (token.type != END_OF_FILE)
168 next_token(&token, &token, NULL, pe);
172 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
175 VALUE string, options;
176 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
180 string = StringValue(string);
181 VALUE tokens = rb_ary_new();
183 // check instance variables
184 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
186 // process options hash (can override instance variables)
187 if (!NIL_P(options) && TYPE(options) == T_HASH)
189 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
190 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
192 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
197 char *p = RSTRING_PTR(string);
198 long len = RSTRING_LEN(string);
201 token_t *_token = &token;
202 next_token(&token, NULL, p, pe);
203 while (token.type != END_OF_FILE)
210 if (TOKEN_LEN(_token) >= min_len)
211 rb_ary_push(tokens, TOKEN_TEXT(_token));
214 // ignore everything else
217 next_token(&token, &token, NULL, pe);
222 // we downcase "in place", overwriting the original contents of the buffer and returning the same string
223 VALUE _Wikitext_downcase_bang(VALUE string)
225 char *ptr = RSTRING_PTR(string);
226 long len = RSTRING_LEN(string);
227 for (long i = 0; i < len; i++)
229 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
235 // prepare hyperlink and append it to parser->output
236 // if check_autolink is Qtrue, checks parser->autolink to decide whether to emit a real hyperlink
237 // or merely the literal link target
238 // if link_text is Qnil, the link_target is re-used for the link text
239 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class, VALUE check_autolink)
241 if (check_autolink == Qtrue && !parser->autolink)
242 rb_str_append(parser->output, link_target);
245 rb_str_cat(parser->output, a_start, sizeof(a_start) - 1); // <a href="
246 if (!NIL_P(link_prefix))
247 rb_str_append(parser->output, link_prefix);
248 rb_str_append(parser->output, link_target);
250 // special handling for mailto URIs
251 const char *mailto = "mailto:";
252 if (NIL_P(link_prefix) &&
253 RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
254 strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
255 link_class = parser->mailto_class; // use mailto_class from parser
256 if (link_class != Qnil)
258 rb_str_cat(parser->output, a_class, sizeof(a_class) - 1); // " class="
259 rb_str_append(parser->output, link_class);
261 rb_str_cat(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
262 if (NIL_P(link_text)) // re-use link_target
263 rb_str_append(parser->output, link_target);
265 rb_str_append(parser->output, link_text);
266 rb_str_cat(parser->output, a_end, sizeof(a_end) - 1); // </a>
270 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
272 rb_str_cat(parser->output, img_start, sizeof(img_start) - 1); // <img src="
273 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
274 rb_str_append(parser->output, parser->img_prefix);
275 rb_str_cat(parser->output, token_ptr, token_len);
276 rb_str_cat(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
277 rb_str_cat(parser->output, token_ptr, token_len);
278 rb_str_cat(parser->output, img_end, sizeof(img_end) - 1); // " />
281 // will emit indentation only if we are about to emit any of:
282 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
283 // each time we enter one of those spans must ++ the indentation level
284 void _Wikitext_indent(parser_t *parser)
286 if (parser->base_indent == -1) // indentation disabled
288 int space_count = parser->current_indent + parser->base_indent;
291 char *old_end, *new_end;
292 if (parser->tabulation->len < space_count)
293 str_grow(parser->tabulation, space_count); // reallocates if necessary
294 old_end = parser->tabulation->ptr + parser->tabulation->len;
295 new_end = parser->tabulation->ptr + space_count;
296 while (old_end < new_end)
298 if (space_count > parser->tabulation->len)
299 parser->tabulation->len = space_count;
300 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
302 parser->current_indent += 2;
305 void _Wikitext_dedent(parser_t *parser, VALUE emit)
307 if (parser->base_indent == -1) // indentation disabled
309 parser->current_indent -= 2;
312 int space_count = parser->current_indent + parser->base_indent;
314 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
317 // Pops a single item off the parser's scope stack.
318 // A corresponding closing tag is written to the target string.
319 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
320 void _Wikitext_pop_from_stack(parser_t *parser, VALUE target)
322 int top = ary_entry(parser->scope, -1);
326 target = parser->output;
328 // for headings, take base_heading_level into account
329 if (top >= H1_START && top <= H6_START)
331 top += parser->base_heading_level;
332 // no need to check for underflow (base_heading_level is never negative)
341 rb_str_cat(target, pre_end, sizeof(pre_end) - 1);
342 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
343 _Wikitext_dedent(parser, Qfalse);
347 case BLOCKQUOTE_START:
348 _Wikitext_dedent(parser, Qtrue);
349 rb_str_cat(target, blockquote_end, sizeof(blockquote_end) - 1);
350 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
354 // not a real HTML tag; so nothing to pop
359 rb_str_cat(target, strong_end, sizeof(strong_end) - 1);
364 rb_str_cat(target, em_end, sizeof(em_end) - 1);
369 rb_str_cat(target, tt_end, sizeof(tt_end) - 1);
373 _Wikitext_dedent(parser, Qtrue);
374 rb_str_cat(target, ol_end, sizeof(ol_end) - 1);
375 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
379 _Wikitext_dedent(parser, Qtrue);
380 rb_str_cat(target, ul_end, sizeof(ul_end) - 1);
381 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
385 // next token to pop will be a LI
386 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
387 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
388 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
389 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
390 _Wikitext_dedent(parser, Qtrue); // we really only want to emit the spaces
391 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
395 rb_str_cat(target, li_end, sizeof(li_end) - 1);
396 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
397 _Wikitext_dedent(parser, Qfalse);
401 rb_str_cat(target, h6_end, sizeof(h6_end) - 1);
402 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
403 _Wikitext_dedent(parser, Qfalse);
407 rb_str_cat(target, h5_end, sizeof(h5_end) - 1);
408 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
409 _Wikitext_dedent(parser, Qfalse);
413 rb_str_cat(target, h4_end, sizeof(h4_end) - 1);
414 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
415 _Wikitext_dedent(parser, Qfalse);
419 rb_str_cat(target, h3_end, sizeof(h3_end) - 1);
420 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
421 _Wikitext_dedent(parser, Qfalse);
425 rb_str_cat(target, h2_end, sizeof(h2_end) - 1);
426 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
427 _Wikitext_dedent(parser, Qfalse);
431 rb_str_cat(target, h1_end, sizeof(h1_end) - 1);
432 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
433 _Wikitext_dedent(parser, Qfalse);
437 // not an HTML tag; so nothing to emit
441 // not an HTML tag; so nothing to emit
445 // not an HTML tag; so nothing to emit
449 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
453 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
457 rb_str_cat(target, p_end, sizeof(p_end) - 1);
458 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
459 _Wikitext_dedent(parser, Qfalse);
467 // should probably raise an exception here
470 ary_pop(parser->scope);
473 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
474 // If including is Qtrue then the item itself is also popped.
475 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
476 void _Wikitext_pop_from_stack_up_to(parser_t *parser, VALUE target, int item, VALUE including)
478 int continue_looping = 1;
481 int top = ary_entry(parser->scope, -1);
486 if (including != Qtrue)
488 continue_looping = 0;
490 _Wikitext_pop_from_stack(parser, target);
491 } while (continue_looping);
494 void _Wikitext_pop_all_from_stack(parser_t *parser)
496 for (int i = 0, max = parser->scope->count; i < max; i++)
497 _Wikitext_pop_from_stack(parser, Qnil);
500 void _Wikitext_start_para_if_necessary(parser_t *parser)
502 if (!NIL_P(parser->capture)) // we don't do anything if in capturing mode
505 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
506 if (parser->scope->count == 0 ||
507 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
508 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
510 _Wikitext_indent(parser);
511 rb_str_cat(parser->output, p_start, sizeof(p_start) - 1);
512 ary_push(parser->scope, P);
513 ary_push(parser->line, P);
515 else if (parser->pending_crlf)
518 // already in a paragraph block; convert pending CRLF into a space
519 rb_str_cat(parser->output, space, sizeof(space) - 1);
521 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
522 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
524 parser->pending_crlf = false;
527 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
529 if (parser->pending_crlf)
531 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
532 parser->pending_crlf = false;
536 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
537 // For example, given input like:
542 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
543 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
548 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
549 // but not on the line scope:
554 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
555 // on the line scope.
556 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
557 // entering the for loop.
558 void _Wikitext_pop_excess_elements(parser_t *parser)
560 if (!NIL_P(parser->capture)) // we don't pop anything if in capturing mode
562 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
564 // special case for last item on scope
567 // don't auto-pop P if it is only item on scope
568 if (ary_entry(parser->scope, -1) == P)
570 // add P to the line scope to prevent us entering the loop at all next time around
571 ary_push(parser->line, P);
575 _Wikitext_pop_from_stack(parser, parser->output);
579 #define INVALID_ENCODING(msg) do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
581 // convert a single UTF-8 codepoint to UTF-32
582 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
583 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
584 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
585 // raises a RangeError if the supplied character is invalid UTF-8
586 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
587 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
590 if ((unsigned char)src[0] <= 0x7f) // ASCII
595 else if ((src[0] & 0xe0) == 0xc0) // byte starts with 110..... : this should be a two-byte sequence
598 INVALID_ENCODING("truncated byte sequence"); // no second byte
599 else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
600 INVALID_ENCODING("overlong encoding"); // overlong encoding: lead byte of 110..... but code point <= 127
601 else if ((src[1] & 0xc0) != 0x80 )
602 INVALID_ENCODING("malformed byte sequence"); // should have second byte starting with 10......
603 dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
606 else if ((src[0] & 0xf0) == 0xe0) // byte starts with 1110.... : this should be a three-byte sequence
609 INVALID_ENCODING("truncated byte sequence"); // missing second or third byte
610 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
611 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
612 dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
615 else if ((src[0] & 0xf8) == 0xf0) // bytes starts with 11110... : this should be a four-byte sequence
618 INVALID_ENCODING("truncated byte sequence"); // missing second, third, or fourth byte
619 else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
620 INVALID_ENCODING("overlong encoding"); // disallowed by RFC 3629 (codepoints above 0x10ffff)
621 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
622 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
623 dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
626 else // invalid input
627 INVALID_ENCODING("unexpected byte");
631 VALUE _Wikitext_utf32_char_to_entity(uint32_t character)
633 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
634 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
635 char scratch = (character & 0xf000) >> 12;
636 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
637 scratch = (character & 0x0f00) >> 8;
638 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
639 scratch = (character & 0x00f0) >> 4;
640 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
641 scratch = character & 0x000f;
642 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
643 return rb_str_new((const char *)hex_string, sizeof(hex_string));
646 VALUE _Wikitext_parser_trim_link_target(VALUE string)
648 string = StringValue(string);
649 char *src = RSTRING_PTR(string);
650 char *start = src; // remember this so we can check if we're at the start
652 char *non_space = src; // remember last non-space character output
653 long len = RSTRING_LEN(string);
654 char *end = src + len;
666 if (left == start && non_space + 1 == end)
669 return rb_str_new(left, (non_space + 1) - left);
672 // - non-printable (non-ASCII) characters converted to numeric entities
673 // - QUOT and AMP characters converted to named entities
674 // - if rollback is Qtrue, there is no special treatment of spaces
675 // - if rollback is Qfalse, leading and trailing whitespace trimmed
676 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, VALUE rollback)
678 VALUE string = StringValue(parser->link_target); // raises if string is nil or doesn't quack like a string
679 char *src = RSTRING_PTR(string);
680 char *start = src; // remember this so we can check if we're at the start
681 long len = RSTRING_LEN(string);
682 char *end = src + len;
684 // start with a destination buffer twice the size of the source, will realloc if necessary
685 // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
686 // this efficiently handles the most common case (where the size of the buffer doesn't change much)
687 char *dest = ALLOC_N(char, len * 2);
688 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
689 char *non_space = dest; // remember last non-space character output
692 // need at most 8 characters (8 bytes) to display each character
693 if (dest + 8 > dest_ptr + len) // outgrowing buffer, must reallocate
695 char *old_dest = dest;
696 char *old_dest_ptr = dest_ptr;
697 len = len + (end - src) * 8; // allocate enough for worst case
698 dest = realloc(dest_ptr, len); // will never have to realloc more than once
701 // would have used reallocf, but this has to run on Linux too, not just Darwin
703 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
706 dest = dest_ptr + (old_dest - old_dest_ptr);
707 non_space = dest_ptr + (non_space - old_dest_ptr);
710 if (*src == '"') // QUOT
712 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
713 memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
714 dest += sizeof(quot_entity_literal);
716 else if (*src == '&') // AMP
718 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
719 memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
720 dest += sizeof(amp_entity_literal);
722 else if (*src == '<') // LESS_THAN
725 rb_raise(rb_eRangeError, "invalid link text (\"<\" may not appear in link text)");
727 else if (*src == '>') // GREATER_THAN
730 rb_raise(rb_eRangeError, "invalid link text (\">\" may not appear in link text)");
732 else if (*src == ' ' && src == start && rollback == Qfalse)
733 start++; // we eat leading space
734 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
739 else // all others: must convert to entities
742 VALUE entity = _Wikitext_utf32_char_to_entity(_Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
743 char *entity_src = RSTRING_PTR(entity);
744 long entity_len = RSTRING_LEN(entity); // should always be 8 characters (8 bytes)
745 memcpy(dest, entity_src, entity_len);
756 // trim trailing space if necessary
757 if (rollback == Qfalse && non_space > dest_ptr && dest != non_space)
758 len = non_space - dest_ptr;
760 len = dest - dest_ptr;
761 VALUE out = rb_str_new(dest_ptr, len);
766 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
769 parser.link_target = string;
770 return _Wikitext_parser_sanitize_link_target(&parser, Qfalse);
773 // encodes the input string according to RFCs 2396 and 2718
774 // leading and trailing whitespace trimmed
775 // note that the first character of the target link is not case-sensitive
776 // (this is a recommended application-level constraint; it is not imposed at this level)
777 // this is to allow links like:
778 // ...the [[foo]] is...
779 // to be equivalent to:
780 // thing. [[Foo]] was...
781 static void _Wikitext_parser_encode_link_target(parser_t *parser)
783 VALUE in = StringValue(parser->link_target);
784 char *input = RSTRING_PTR(in);
785 char *start = input; // remember this so we can check if we're at the start
786 long len = RSTRING_LEN(in);
789 char *end = input + len;
790 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
792 // to avoid most reallocations start with a destination buffer twice the size of the source
793 // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
794 // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
795 // the worst case is where _every_ byte must be written out using 3 bytes
796 long dest_len = len * 2;
797 char *dest = ALLOC_N(char, dest_len);
798 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
799 char *non_space = dest; // remember last non-space character output
800 for (; input < end; input++)
802 if ((dest + 3) > (dest_ptr + dest_len)) // worst case: a single character may grow to 3 characters once encoded
804 // outgrowing buffer, must reallocate
805 char *old_dest = dest;
806 char *old_dest_ptr = dest_ptr;
808 dest = realloc(dest_ptr, dest_len);
811 // would have used reallocf, but this has to run on Linux too, not just Darwin
813 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
816 dest = dest_ptr + (old_dest - old_dest_ptr);
817 non_space = dest_ptr + (non_space - old_dest_ptr);
820 // pass through unreserved characters
821 if (((*input >= 'a') && (*input <= 'z')) ||
822 ((*input >= 'A') && (*input <= 'Z')) ||
823 ((*input >= '0') && (*input <= '9')) ||
832 else if (*input == ' ' && input == start)
833 start++; // we eat leading space
834 else if (*input == ' ' && parser->space_to_underscore)
836 else // everything else gets URL-encoded
839 *dest++ = hex[(unsigned char)(*input) / 16]; // left
840 *dest++ = hex[(unsigned char)(*input) % 16]; // right
846 // trim trailing space if necessary
847 if (non_space > dest_ptr && dest != non_space)
848 dest_len = non_space - dest_ptr;
850 dest_len = dest - dest_ptr;
851 parser->link_target = rb_str_new(dest_ptr, dest_len);
855 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
858 parser.link_target = in;
859 parser.space_to_underscore = false;
860 _Wikitext_parser_encode_link_target(&parser);
861 return parser.link_target;
864 // this method exposed for testing only
865 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
868 parser.link_target = in;
869 parser.space_to_underscore = false;
870 _Wikitext_parser_encode_link_target(&parser);
871 return parser.link_target;
874 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
875 // returns 0 (false) otherwise
876 int _Wikitext_blank(VALUE str)
878 if (NIL_P(str) || RSTRING_LEN(str) == 0)
880 for (char *ptr = RSTRING_PTR(str),
881 *end = RSTRING_PTR(str) + RSTRING_LEN(str);
890 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
893 return; // nothing to do!
894 int scope_includes_separator = IN(SEPARATOR);
895 _Wikitext_pop_from_stack_up_to(parser, Qnil, LINK_START, Qtrue);
896 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
897 if (!NIL_P(parser->link_target))
899 VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, Qtrue);
900 rb_str_append(parser->output, sanitized);
901 if (scope_includes_separator)
903 rb_str_cat(parser->output, separator, sizeof(separator) - 1);
904 if (!NIL_P(parser->link_text))
905 rb_str_append(parser->output, parser->link_text);
908 parser->capture = Qnil;
909 parser->link_target = Qnil;
910 parser->link_text = Qnil;
913 void _Wikitext_rollback_failed_external_link(parser_t *parser)
915 if (!IN(EXT_LINK_START))
916 return; // nothing to do!
918 // store a couple of values before popping
919 int scope_includes_space = IN(SPACE);
920 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
921 _Wikitext_pop_from_stack_up_to(parser, Qnil, EXT_LINK_START, Qtrue);
923 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
924 if (!NIL_P(parser->link_target))
926 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, Qnil, link_class, Qtrue);
927 if (scope_includes_space)
929 rb_str_cat(parser->output, space, sizeof(space) - 1);
930 if (!NIL_P(parser->link_text))
931 rb_str_append(parser->output, parser->link_text);
934 parser->capture = Qnil;
935 parser->link_target = Qnil;
936 parser->link_text = Qnil;
939 void _Wikitext_rollback_failed_link(parser_t *parser)
941 _Wikitext_rollback_failed_internal_link(parser);
942 _Wikitext_rollback_failed_external_link(parser);
945 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
949 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
953 VALUE autolink = Qtrue;
954 VALUE line_ending = rb_str_new2("\n");
955 VALUE external_link_class = rb_str_new2("external");
956 VALUE mailto_class = rb_str_new2("mailto");
957 VALUE internal_link_prefix = rb_str_new2("/wiki/");
958 VALUE img_prefix = rb_str_new2("/images/");
959 VALUE space_to_underscore = Qtrue;
960 VALUE minimum_fulltext_token_length = INT2NUM(3);
961 VALUE base_heading_level = INT2NUM(0);
963 // process options hash (override defaults)
964 if (!NIL_P(options) && TYPE(options) == T_HASH)
966 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
967 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
968 autolink = OVERRIDE_IF_SET(autolink);
969 line_ending = OVERRIDE_IF_SET(line_ending);
970 external_link_class = OVERRIDE_IF_SET(external_link_class);
971 mailto_class = OVERRIDE_IF_SET(mailto_class);
972 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
973 img_prefix = OVERRIDE_IF_SET(img_prefix);
974 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
975 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
976 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
979 // no need to call super here; rb_call_super()
980 rb_iv_set(self, "@autolink", autolink);
981 rb_iv_set(self, "@line_ending", line_ending);
982 rb_iv_set(self, "@external_link_class", external_link_class);
983 rb_iv_set(self, "@mailto_class", mailto_class);
984 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
985 rb_iv_set(self, "@img_prefix", img_prefix);
986 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
987 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
988 rb_iv_set(self, "@base_heading_level", base_heading_level);
992 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
994 for (int i = 0; i < 100000; i++)
995 Wikitext_parser_parse(1, &string, self);
999 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1001 // process arguments
1002 VALUE string, options;
1003 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1007 string = StringValue(string);
1009 // process options hash
1010 int base_indent = 0;
1011 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1012 if (!NIL_P(options) && TYPE(options) == T_HASH)
1014 // :indent => 0 (or more)
1015 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1017 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1018 if (indent == Qfalse)
1019 base_indent = -1; // indentation disabled
1022 base_indent = NUM2INT(indent);
1023 if (base_indent < 0)
1028 // :base_heading_level => 0/1/2/3/4/5/6
1029 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1030 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1033 // normalize, regardless of whether this came from instance variable or override
1034 if (base_heading_level < 0)
1035 base_heading_level = 0;
1036 if (base_heading_level > 6)
1037 base_heading_level = 6;
1040 char *p = RSTRING_PTR(string);
1041 long len = RSTRING_LEN(string);
1044 // access these once per parse
1045 VALUE line_ending = rb_iv_get(self, "@line_ending");
1046 line_ending = StringValue(line_ending);
1047 VALUE link_class = rb_iv_get(self, "@external_link_class");
1048 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1049 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1050 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1051 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1053 // set up parser struct to make passing parameters a little easier
1054 // eventually this will encapsulate most or all of the variables above
1056 parser_t *parser = &_parser;
1057 parser->output = rb_str_new2("");
1058 parser->capture = Qnil;
1059 parser->link_target = Qnil;
1060 parser->link_text = Qnil;
1061 parser->external_link_class = link_class;
1062 parser->mailto_class = mailto_class;
1063 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1064 parser->scope = ary_new();
1065 GC_WRAP_ARY(parser->scope, scope_gc);
1066 parser->line = ary_new();
1067 GC_WRAP_ARY(parser->line, line_gc);
1068 parser->line_buffer = ary_new();
1069 GC_WRAP_ARY(parser->line_buffer, line_buffer_gc);
1070 parser->pending_crlf = false;
1071 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1072 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1073 parser->line_ending = str_new_from_string(line_ending);
1074 GC_WRAP_STR(parser->line_ending, line_ending_gc);
1075 parser->base_indent = base_indent;
1076 parser->current_indent = 0;
1077 parser->tabulation = str_new();
1078 GC_WRAP_STR(parser->tabulation, tabulation_gc);
1079 parser->base_heading_level = base_heading_level;
1081 // this simple looping design leads to a single enormous function,
1082 // but it's faster than doing actual recursive descent and also secure in the face of
1083 // malicious input that seeks to overflow the stack
1084 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1085 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1086 // than a straightforward looping translator like this one anyway
1088 _token.type = NO_TOKEN;
1089 token_t *token = NULL;
1092 // note that whenever we grab a token we push it into the line buffer
1093 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1094 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1096 // check to see if we have a token hanging around from a previous iteration of this loop
1099 if (_token.type == NO_TOKEN)
1101 // first time here (haven't started scanning yet)
1103 next_token(token, NULL, p, pe);
1104 ary_push(parser->line_buffer, token->type);
1110 int type = token->type;
1112 // can't declare new variables inside a switch statement, so predeclare them here
1113 long remove_strong = -1;
1114 long remove_em = -1;
1116 // general purpose counters and flags
1121 // The following giant switch statement contains cases for all the possible token types.
1122 // In the most basic sense we are emitting the HTML that corresponds to each token,
1123 // but some tokens require context information in order to decide what to output.
1124 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1125 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1127 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1128 // - the line buffer (records tokens seen so far on the current line)
1129 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1131 // Although this is fairly complicated, there is one key simplifying factor:
1132 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1133 // scope stack (up to the current token) is valid; our translator can take this as a given.
1134 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1135 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1139 if (IN(NO_WIKI_START) || IN(PRE_START))
1141 rb_str_cat(parser->output, space, sizeof(space) - 1);
1144 else if (IN(BLOCKQUOTE_START))
1146 // this kind of nesting not allowed (to avoid user confusion)
1147 _Wikitext_pop_excess_elements(parser);
1148 _Wikitext_start_para_if_necessary(parser);
1149 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1150 rb_str_cat(i, space, sizeof(space) - 1);
1154 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1155 ary_push(parser->line, PRE);
1156 i = ary_count(parser->line, BLOCKQUOTE);
1157 j = ary_count(parser->scope, BLOCKQUOTE);
1160 // must pop (reduce nesting level)
1161 for (i = j - i; i > 0; i--)
1162 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1167 parser->pending_crlf = false;
1168 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1169 _Wikitext_indent(parser);
1170 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1171 ary_push(parser->scope, PRE);
1176 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1178 _Wikitext_emit_pending_crlf_if_necessary(parser);
1179 rb_str_cat(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1181 else if (IN(BLOCKQUOTE_START))
1183 _Wikitext_rollback_failed_link(parser); // if any
1184 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1185 _Wikitext_indent(parser);
1186 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1187 ary_push(parser->scope, PRE_START);
1188 ary_push(parser->line, PRE_START);
1190 else if (IN(BLOCKQUOTE))
1192 if (token->column_start == 1) // only allowed in first column
1194 _Wikitext_rollback_failed_link(parser); // if any
1195 _Wikitext_pop_all_from_stack(parser);
1196 _Wikitext_indent(parser);
1197 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1198 ary_push(parser->scope, PRE_START);
1199 ary_push(parser->line, PRE_START);
1201 else // PRE_START illegal here
1203 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1204 _Wikitext_pop_excess_elements(parser);
1205 _Wikitext_start_para_if_necessary(parser);
1206 rb_str_cat(i, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1211 _Wikitext_rollback_failed_link(parser); // if any
1212 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1213 _Wikitext_indent(parser);
1214 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1215 ary_push(parser->scope, PRE_START);
1216 ary_push(parser->line, PRE_START);
1221 if (IN(NO_WIKI_START) || IN(PRE))
1223 _Wikitext_emit_pending_crlf_if_necessary(parser);
1224 rb_str_cat(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1229 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, Qtrue);
1232 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1233 _Wikitext_pop_excess_elements(parser);
1234 _Wikitext_start_para_if_necessary(parser);
1235 rb_str_cat(i, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1241 if (IN(NO_WIKI_START) || IN(PRE_START))
1242 // no need to check for <pre>; can never appear inside it
1243 rb_str_cat(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1244 else if (IN(BLOCKQUOTE_START))
1246 // this kind of nesting not allowed (to avoid user confusion)
1247 _Wikitext_pop_excess_elements(parser);
1248 _Wikitext_start_para_if_necessary(parser);
1249 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1250 rb_str_cat(i, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1255 ary_push(parser->line, BLOCKQUOTE);
1257 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1258 i = ary_count(parser->line, BLOCKQUOTE);
1259 j = ary_count(parser->scope, BLOCKQUOTE);
1261 // 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
1262 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1264 ary_push(parser->line, BLOCKQUOTE);
1268 // now decide whether to push, pop or do nothing
1271 // must push (increase nesting level)
1272 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1273 for (i = i - j; i > 0; i--)
1275 _Wikitext_indent(parser);
1276 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1277 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1278 ary_push(parser->scope, BLOCKQUOTE);
1283 // must pop (reduce nesting level)
1284 for (i = j - i; i > 0; i--)
1285 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1288 // jump to top of the loop to process token we scanned during lookahead
1293 case BLOCKQUOTE_START:
1294 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1296 _Wikitext_emit_pending_crlf_if_necessary(parser);
1297 rb_str_cat(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1299 else if (IN(BLOCKQUOTE_START))
1301 // nesting is fine here
1302 _Wikitext_rollback_failed_link(parser); // if any
1303 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1304 _Wikitext_indent(parser);
1305 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1306 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1307 ary_push(parser->scope, BLOCKQUOTE_START);
1308 ary_push(parser->line, BLOCKQUOTE_START);
1310 else if (IN(BLOCKQUOTE))
1312 if (token->column_start == 1) // only allowed in first column
1314 _Wikitext_rollback_failed_link(parser); // if any
1315 _Wikitext_pop_all_from_stack(parser);
1316 _Wikitext_indent(parser);
1317 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1318 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1319 ary_push(parser->scope, BLOCKQUOTE_START);
1320 ary_push(parser->line, BLOCKQUOTE_START);
1322 else // BLOCKQUOTE_START illegal here
1324 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1325 _Wikitext_pop_excess_elements(parser);
1326 _Wikitext_start_para_if_necessary(parser);
1327 rb_str_cat(i, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1332 // would be nice to eliminate the repetition here but it's probably the clearest way
1333 _Wikitext_rollback_failed_link(parser); // if any
1334 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1335 _Wikitext_indent(parser);
1336 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1337 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1338 ary_push(parser->scope, BLOCKQUOTE_START);
1339 ary_push(parser->line, BLOCKQUOTE_START);
1343 case BLOCKQUOTE_END:
1344 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1346 _Wikitext_emit_pending_crlf_if_necessary(parser);
1347 rb_str_cat(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1351 if (IN(BLOCKQUOTE_START))
1352 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, Qtrue);
1355 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1356 _Wikitext_pop_excess_elements(parser);
1357 _Wikitext_start_para_if_necessary(parser);
1358 rb_str_cat(i, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1364 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1366 _Wikitext_emit_pending_crlf_if_necessary(parser);
1367 rb_str_cat(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1371 _Wikitext_pop_excess_elements(parser);
1372 _Wikitext_start_para_if_necessary(parser);
1373 ary_push(parser->scope, NO_WIKI_START);
1374 ary_push(parser->line, NO_WIKI_START);
1379 if (IN(NO_WIKI_START))
1380 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1381 _Wikitext_pop_from_stack_up_to(parser, Qnil, NO_WIKI_START, Qtrue);
1384 _Wikitext_pop_excess_elements(parser);
1385 _Wikitext_start_para_if_necessary(parser);
1386 rb_str_cat(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1391 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1393 _Wikitext_emit_pending_crlf_if_necessary(parser);
1394 rb_str_cat(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1398 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1399 _Wikitext_pop_excess_elements(parser);
1401 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1402 // otherwise, must open them
1405 j = parser->scope->count;
1406 for (j = j - 1; j >= 0; j--)
1408 int val = ary_entry(parser->scope, j);
1409 if (val == STRONG || val == STRONG_START)
1411 rb_str_cat(i, strong_end, sizeof(strong_end) - 1);
1414 else if (val == EM || val == EM_START)
1416 rb_str_cat(i, em_end, sizeof(em_end) - 1);
1421 if (remove_strong > remove_em) // must remove strong first
1423 ary_pop(parser->scope);
1425 ary_pop(parser->scope);
1426 else // there was no em to remove!, so consider this an opening em tag
1428 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1429 ary_push(parser->scope, EM);
1430 ary_push(parser->line, EM);
1433 else if (remove_em > remove_strong) // must remove em first
1435 ary_pop(parser->scope);
1436 if (remove_strong > -1)
1437 ary_pop(parser->scope);
1438 else // there was no strong to remove!, so consider this an opening strong tag
1440 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1441 ary_push(parser->scope, STRONG);
1442 ary_push(parser->line, STRONG);
1445 else // no strong or em to remove, so this must be a new opening of both
1447 _Wikitext_start_para_if_necessary(parser);
1448 rb_str_cat(i, strong_em_start, sizeof(strong_em_start) - 1);
1449 ary_push(parser->scope, STRONG);
1450 ary_push(parser->line, STRONG);
1451 ary_push(parser->scope, EM);
1452 ary_push(parser->line, EM);
1457 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1459 _Wikitext_emit_pending_crlf_if_necessary(parser);
1460 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1464 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1465 if (IN(STRONG_START))
1466 // already in span started with <strong>, no choice but to emit this literally
1467 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1468 else if (IN(STRONG))
1469 // STRONG already seen, this is a closing tag
1470 _Wikitext_pop_from_stack_up_to(parser, i, STRONG, Qtrue);
1473 // this is a new opening
1474 _Wikitext_pop_excess_elements(parser);
1475 _Wikitext_start_para_if_necessary(parser);
1476 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1477 ary_push(parser->scope, STRONG);
1478 ary_push(parser->line, STRONG);
1484 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1486 _Wikitext_emit_pending_crlf_if_necessary(parser);
1487 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1491 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1492 if (IN(STRONG_START) || IN(STRONG))
1493 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1496 _Wikitext_pop_excess_elements(parser);
1497 _Wikitext_start_para_if_necessary(parser);
1498 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1499 ary_push(parser->scope, STRONG_START);
1500 ary_push(parser->line, STRONG_START);
1506 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1508 _Wikitext_emit_pending_crlf_if_necessary(parser);
1509 rb_str_cat(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1513 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1514 if (IN(STRONG_START))
1515 _Wikitext_pop_from_stack_up_to(parser, i, STRONG_START, Qtrue);
1518 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1519 _Wikitext_pop_excess_elements(parser);
1520 _Wikitext_start_para_if_necessary(parser);
1521 rb_str_cat(i, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1527 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1529 _Wikitext_emit_pending_crlf_if_necessary(parser);
1530 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1534 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1536 // already in span started with <em>, no choice but to emit this literally
1537 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1539 // EM already seen, this is a closing tag
1540 _Wikitext_pop_from_stack_up_to(parser, i, EM, Qtrue);
1543 // this is a new opening
1544 _Wikitext_pop_excess_elements(parser);
1545 _Wikitext_start_para_if_necessary(parser);
1546 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1547 ary_push(parser->scope, EM);
1548 ary_push(parser->line, EM);
1554 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1556 _Wikitext_emit_pending_crlf_if_necessary(parser);
1557 rb_str_cat(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1561 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1562 if (IN(EM_START) || IN(EM))
1563 rb_str_cat(i, escaped_em_start, sizeof(escaped_em_start) - 1);
1566 _Wikitext_pop_excess_elements(parser);
1567 _Wikitext_start_para_if_necessary(parser);
1568 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1569 ary_push(parser->scope, EM_START);
1570 ary_push(parser->line, EM_START);
1576 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1578 _Wikitext_emit_pending_crlf_if_necessary(parser);
1579 rb_str_cat(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1583 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1585 _Wikitext_pop_from_stack_up_to(parser, i, EM_START, Qtrue);
1588 // no EM_START in scope, so must interpret the TT_END without any special meaning
1589 _Wikitext_pop_excess_elements(parser);
1590 _Wikitext_start_para_if_necessary(parser);
1591 rb_str_cat(i, escaped_em_end, sizeof(escaped_em_end) - 1);
1597 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1599 _Wikitext_emit_pending_crlf_if_necessary(parser);
1600 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1604 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1606 // already in span started with <tt>, no choice but to emit this literally
1607 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1609 // TT (`) already seen, this is a closing tag
1610 _Wikitext_pop_from_stack_up_to(parser, i, TT, Qtrue);
1613 // this is a new opening
1614 _Wikitext_pop_excess_elements(parser);
1615 _Wikitext_start_para_if_necessary(parser);
1616 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1617 ary_push(parser->scope, TT);
1618 ary_push(parser->line, TT);
1624 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1626 _Wikitext_emit_pending_crlf_if_necessary(parser);
1627 rb_str_cat(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1631 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1632 if (IN(TT_START) || IN(TT))
1633 rb_str_cat(i, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1636 _Wikitext_pop_excess_elements(parser);
1637 _Wikitext_start_para_if_necessary(parser);
1638 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1639 ary_push(parser->scope, TT_START);
1640 ary_push(parser->line, TT_START);
1646 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1648 _Wikitext_emit_pending_crlf_if_necessary(parser);
1649 rb_str_cat(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1653 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1655 _Wikitext_pop_from_stack_up_to(parser, i, TT_START, Qtrue);
1658 // no TT_START in scope, so must interpret the TT_END without any special meaning
1659 _Wikitext_pop_excess_elements(parser);
1660 _Wikitext_start_para_if_necessary(parser);
1661 rb_str_cat(i, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1668 if (IN(NO_WIKI_START) || IN(PRE_START))
1670 // no need to check for PRE; can never appear inside it
1671 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1675 // count number of tokens in line and scope stacks
1676 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1677 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1678 j = parser->scope->count - bq_count;
1681 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1685 if (type == OL || type == UL)
1688 if (i - k >= 2) // already seen at least one OL or UL
1690 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1695 ary_push(parser->line, type);
1696 ary_push(parser->line, LI);
1698 // want to compare line with scope but can only do so if scope has enough items on it
1701 if (ary_entry(parser->scope, i + bq_count - 2) == type && ary_entry(parser->scope, i + bq_count - 1) == LI)
1703 // line and scope match at this point: do nothing yet
1707 // item just pushed onto line does not match corresponding slot of scope!
1708 for (; j >= i - 2; j--)
1709 // must pop back before emitting
1710 _Wikitext_pop_from_stack(parser, Qnil);
1712 // will emit UL or OL, then LI
1716 else // line stack size now exceeds scope stack size: must increase nesting level
1717 break; // will emit UL or OL, then LI
1721 // not a OL or UL token!
1723 // must close existing LI and re-open new one
1724 _Wikitext_pop_from_stack(parser, Qnil);
1727 // item just pushed onto line does not match corresponding slot of scope!
1729 // must pop back before emitting
1730 _Wikitext_pop_from_stack(parser, Qnil);
1738 if (type == OL || type == UL)
1740 // if LI is at the top of a stack this is the start of a nested list
1741 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1743 // so we should precede it with a CRLF, and indicate that it's a nested list
1744 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1745 ary_push(parser->scope, NESTED_LIST);
1749 // this is a new list
1750 if (IN(BLOCKQUOTE_START))
1751 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1753 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1757 _Wikitext_indent(parser);
1759 rb_str_cat(parser->output, ol_start, sizeof(ol_start) - 1);
1760 else if (type == UL)
1761 rb_str_cat(parser->output, ul_start, sizeof(ul_start) - 1);
1762 ary_push(parser->scope, type);
1763 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1765 else if (type == SPACE)
1766 // silently throw away the optional SPACE token after final list marker
1769 _Wikitext_indent(parser);
1770 rb_str_cat(parser->output, li_start, sizeof(li_start) - 1);
1771 ary_push(parser->scope, LI);
1773 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1774 if (type == OL || type == UL)
1777 while (k++, NEXT_TOKEN(), (type = token->type))
1779 if (type == OL || type == UL)
1780 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1781 else if (type == SPACE && k == 1)
1783 // silently throw away the optional SPACE token after final list marker
1792 // jump to top of the loop to process token we scanned during lookahead
1801 if (IN(NO_WIKI_START) || IN(PRE_START))
1803 // no need to check for PRE; can never appear inside it
1804 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1808 // pop up to but not including the last BLOCKQUOTE on the scope stack
1809 if (IN(BLOCKQUOTE_START))
1810 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1812 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1814 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1815 ary_push(parser->line, type);
1816 i = ary_count(parser->line, BLOCKQUOTE);
1817 j = ary_count(parser->scope, BLOCKQUOTE);
1819 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1822 // must pop (reduce nesting level)
1823 for (i = j - i; i > 0; i--)
1824 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1827 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1828 while (NEXT_TOKEN(), (token->type == SPACE))
1831 ary_push(parser->scope, type);
1832 _Wikitext_indent(parser);
1834 // take base_heading_level into account
1835 type += base_heading_level;
1836 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1839 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1840 if (type == H6_START)
1841 rb_str_cat(parser->output, h6_start, sizeof(h6_start) - 1);
1842 else if (type == H5_START)
1843 rb_str_cat(parser->output, h5_start, sizeof(h5_start) - 1);
1844 else if (type == H4_START)
1845 rb_str_cat(parser->output, h4_start, sizeof(h4_start) - 1);
1846 else if (type == H3_START)
1847 rb_str_cat(parser->output, h3_start, sizeof(h3_start) - 1);
1848 else if (type == H2_START)
1849 rb_str_cat(parser->output, h2_start, sizeof(h2_start) - 1);
1850 else if (type == H1_START)
1851 rb_str_cat(parser->output, h1_start, sizeof(h1_start) - 1);
1853 // jump to top of the loop to process token we scanned during lookahead
1857 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1859 _Wikitext_emit_pending_crlf_if_necessary(parser);
1860 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1864 _Wikitext_rollback_failed_external_link(parser); // if any
1867 // literal output only if not in h6 scope (we stay silent in that case)
1868 _Wikitext_start_para_if_necessary(parser);
1869 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1875 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1877 _Wikitext_emit_pending_crlf_if_necessary(parser);
1878 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1882 _Wikitext_rollback_failed_external_link(parser); // if any
1885 // literal output only if not in h5 scope (we stay silent in that case)
1886 _Wikitext_start_para_if_necessary(parser);
1887 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1893 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1895 _Wikitext_emit_pending_crlf_if_necessary(parser);
1896 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1900 _Wikitext_rollback_failed_external_link(parser); // if any
1903 // literal output only if not in h4 scope (we stay silent in that case)
1904 _Wikitext_start_para_if_necessary(parser);
1905 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1911 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1913 _Wikitext_emit_pending_crlf_if_necessary(parser);
1914 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1918 _Wikitext_rollback_failed_external_link(parser); // if any
1921 // literal output only if not in h3 scope (we stay silent in that case)
1922 _Wikitext_start_para_if_necessary(parser);
1923 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1929 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1931 _Wikitext_emit_pending_crlf_if_necessary(parser);
1932 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1936 _Wikitext_rollback_failed_external_link(parser); // if any
1939 // literal output only if not in h2 scope (we stay silent in that case)
1940 _Wikitext_start_para_if_necessary(parser);
1941 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1947 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1949 _Wikitext_emit_pending_crlf_if_necessary(parser);
1950 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1954 _Wikitext_rollback_failed_external_link(parser); // if any
1957 // literal output only if not in h1 scope (we stay silent in that case)
1958 _Wikitext_start_para_if_necessary(parser);
1959 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1965 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1967 _Wikitext_emit_pending_crlf_if_necessary(parser);
1968 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1972 _Wikitext_pop_excess_elements(parser);
1973 _Wikitext_start_para_if_necessary(parser);
1974 _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), TOKEN_TEXT(token), Qnil, mailto_class, Qtrue);
1979 if (IN(NO_WIKI_START))
1980 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1981 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1982 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1983 else if (IN(LINK_START))
1985 // if the URI were allowed it would have been handled already in LINK_START
1986 _Wikitext_rollback_failed_internal_link(parser);
1987 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
1989 else if (IN(EXT_LINK_START))
1991 if (NIL_P(parser->link_target))
1993 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1994 i = TOKEN_TEXT(token);
1996 if (token->type == SPACE)
1998 ary_push(parser->scope, SPACE);
1999 parser->link_target = i;
2000 parser->link_text = rb_str_new2("");
2001 parser->capture = parser->link_text;
2002 token = NULL; // silently consume space
2006 // didn't see the space! this must be an error
2007 _Wikitext_pop_from_stack(parser, Qnil);
2008 _Wikitext_pop_excess_elements(parser);
2009 _Wikitext_start_para_if_necessary(parser);
2010 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2011 _Wikitext_append_hyperlink(parser, Qnil, i, Qnil, parser->external_link_class, Qtrue);
2016 if (NIL_P(parser->link_text))
2017 // this must be the first part of our link text
2018 parser->link_text = TOKEN_TEXT(token);
2020 // add to existing link text
2021 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2026 _Wikitext_pop_excess_elements(parser);
2027 _Wikitext_start_para_if_necessary(parser);
2028 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
2033 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2034 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2035 else if (IN(EXT_LINK_START))
2037 if (NIL_P(parser->link_target))
2039 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2040 i = TOKEN_TEXT(token);
2042 if (token->type == SPACE)
2044 ary_push(parser->scope, PATH);
2045 ary_push(parser->scope, SPACE);
2046 parser->link_target = i;
2047 parser->link_text = rb_str_new2("");
2048 parser->capture = parser->link_text;
2049 token = NULL; // silently consume space
2053 // didn't see the space! this must be an error
2054 _Wikitext_pop_from_stack(parser, Qnil);
2055 _Wikitext_pop_excess_elements(parser);
2056 _Wikitext_start_para_if_necessary(parser);
2057 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2058 rb_str_append(parser->output, i);
2063 if (NIL_P(parser->link_text))
2064 // this must be the first part of our link text
2065 parser->link_text = TOKEN_TEXT(token);
2067 // add to existing link text
2068 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2073 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2074 _Wikitext_pop_excess_elements(parser);
2075 _Wikitext_start_para_if_necessary(parser);
2076 rb_str_cat(i, token->start, TOKEN_LEN(token));
2080 // internal links (links to other wiki articles) look like this:
2081 // [[another article]] (would point at, for example, "/wiki/another_article")
2082 // [[the other article|the link text we'll use for it]]
2083 // [[the other article | the link text we'll use for it]]
2084 // MediaWiki has strict requirements about what it will accept as a link target:
2085 // all wikitext markup is disallowed:
2086 // example [[foo ''bar'' baz]]
2087 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2088 // example [[foo <em>bar</em> baz]]
2089 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2090 // example [[foo <nowiki>''</nowiki> baz]]
2091 // renders [[foo '' baz]] (ie. not a link)
2092 // example [[foo <bar> baz]]
2093 // renders [[foo <bar> baz]] (ie. not a link)
2094 // HTML entities and non-ASCII, however, make it through:
2095 // example [[foo €]]
2096 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2097 // example [[foo €]]
2098 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2099 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2100 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2101 // everything else will be rejected
2103 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2104 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2106 _Wikitext_emit_pending_crlf_if_necessary(parser);
2107 rb_str_cat(i, link_start, sizeof(link_start) - 1);
2109 else if (IN(EXT_LINK_START))
2110 // already in external link scope! (and in fact, must be capturing link_text right now)
2111 rb_str_cat(i, link_start, sizeof(link_start) - 1);
2112 else if (IN(LINK_START))
2114 // already in internal link scope! this is a syntax error
2115 _Wikitext_rollback_failed_internal_link(parser);
2116 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
2118 else if (IN(SEPARATOR))
2120 // scanning internal link text
2122 else // not in internal link scope yet
2124 // will either emit a link, or the rollback of a failed link, so start the para now
2125 _Wikitext_pop_excess_elements(parser);
2126 _Wikitext_start_para_if_necessary(parser);
2127 ary_push(parser->scope, LINK_START);
2129 // look ahead and try to gobble up link target
2130 while (NEXT_TOKEN(), (type = token->type))
2132 if (type == SPACE ||
2133 type == SPECIAL_URI_CHARS ||
2135 type == PRINTABLE ||
2139 type == QUOT_ENTITY ||
2141 type == AMP_ENTITY ||
2142 type == IMG_START ||
2144 type == LEFT_CURLY ||
2145 type == RIGHT_CURLY)
2147 // accumulate these tokens into link_target
2148 if (NIL_P(parser->link_target))
2150 parser->link_target = rb_str_new2("");
2151 parser->capture = parser->link_target;
2153 if (type == QUOT_ENTITY)
2154 // don't insert the entity, insert the literal quote
2155 rb_str_cat(parser->link_target, quote, sizeof(quote) - 1);
2156 else if (type == AMP_ENTITY)
2157 // don't insert the entity, insert the literal ampersand
2158 rb_str_cat(parser->link_target, ampersand, sizeof(ampersand) - 1);
2160 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2162 else if (type == LINK_END)
2164 if (NIL_P(parser->link_target)) // bail for inputs like "[[]]"
2165 _Wikitext_rollback_failed_internal_link(parser);
2166 break; // jump back to top of loop (will handle this in LINK_END case below)
2168 else if (type == SEPARATOR)
2170 if (NIL_P(parser->link_target)) // bail for inputs like "[[|"
2171 _Wikitext_rollback_failed_internal_link(parser);
2174 ary_push(parser->scope, SEPARATOR);
2175 parser->link_text = rb_str_new2("");
2176 parser->capture = parser->link_text;
2181 else // unexpected token (syntax error)
2183 _Wikitext_rollback_failed_internal_link(parser);
2184 break; // jump back to top of loop to handle unexpected token
2188 // jump to top of the loop to process token we scanned during lookahead (if any)
2194 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2195 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2197 _Wikitext_emit_pending_crlf_if_necessary(parser);
2198 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2200 else if (IN(EXT_LINK_START))
2201 // already in external link scope! (and in fact, must be capturing link_text right now)
2202 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2203 else if (IN(LINK_START)) // in internal link scope!
2205 if (_Wikitext_blank(parser->link_target))
2207 // special case for inputs like "[[ ]]"
2208 _Wikitext_rollback_failed_internal_link(parser);
2209 rb_str_cat(parser->output, link_end, sizeof(link_end) - 1);
2212 if (NIL_P(parser->link_text) ||
2213 RSTRING_LEN(parser->link_text) == 0 ||
2214 _Wikitext_blank(parser->link_text))
2215 // use link target as link text
2216 parser->link_text = _Wikitext_parser_sanitize_link_target(parser, Qfalse);
2218 parser->link_text = _Wikitext_parser_trim_link_target(parser->link_text);
2219 _Wikitext_parser_encode_link_target(parser);
2220 _Wikitext_pop_from_stack_up_to(parser, i, LINK_START, Qtrue);
2221 parser->capture = Qnil;
2222 _Wikitext_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, Qfalse);
2223 parser->link_target = Qnil;
2224 parser->link_text = Qnil;
2226 else // wasn't in internal link scope
2228 _Wikitext_pop_excess_elements(parser);
2229 _Wikitext_start_para_if_necessary(parser);
2230 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2234 // external links look like this:
2235 // [http://google.com/ the link text]
2236 // [/other/page/on/site see this page]
2237 // strings in square brackets which don't match this syntax get passed through literally; eg:
2238 // he was very angery [sic] about the turn of events
2239 case EXT_LINK_START:
2240 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2241 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2243 _Wikitext_emit_pending_crlf_if_necessary(parser);
2244 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2246 else if (IN(EXT_LINK_START))
2247 // already in external link scope! (and in fact, must be capturing link_text right now)
2248 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2249 else if (IN(LINK_START))
2251 // already in internal link scope!
2252 i = rb_str_new(ext_link_start, sizeof(ext_link_start) - 1);
2253 if (NIL_P(parser->link_target))
2254 // this must be the first character of our link target
2255 parser->link_target = i;
2258 // link target has already been scanned
2259 if (NIL_P(parser->link_text))
2260 // this must be the first character of our link text
2261 parser->link_text = i;
2263 // add to existing link text
2264 rb_str_append(parser->link_text, i);
2267 // add to existing link target
2268 rb_str_append(parser->link_target, i);
2270 else // not in external link scope yet
2272 // will either emit a link, or the rollback of a failed link, so start the para now
2273 _Wikitext_pop_excess_elements(parser);
2274 _Wikitext_start_para_if_necessary(parser);
2276 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2278 if (token->type == URI || token->type == PATH)
2279 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2281 // only get here if there was a syntax error (missing URI)
2282 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2283 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2288 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2289 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2291 _Wikitext_emit_pending_crlf_if_necessary(parser);
2292 rb_str_cat(i, ext_link_end, sizeof(ext_link_end) - 1);
2294 else if (IN(EXT_LINK_START))
2296 if (NIL_P(parser->link_text))
2297 // syntax error: external link with no link text
2298 _Wikitext_rollback_failed_external_link(parser);
2302 j = IN(PATH) ? Qnil : parser->external_link_class;
2303 _Wikitext_pop_from_stack_up_to(parser, i, EXT_LINK_START, Qtrue);
2304 parser->capture = Qnil;
2305 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, Qfalse);
2307 parser->link_target = Qnil;
2308 parser->link_text = Qnil;
2312 _Wikitext_pop_excess_elements(parser);
2313 _Wikitext_start_para_if_necessary(parser);
2314 rb_str_cat(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2319 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2320 _Wikitext_pop_excess_elements(parser);
2321 _Wikitext_start_para_if_necessary(parser);
2322 rb_str_cat(i, separator, sizeof(separator) - 1);
2326 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2327 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2329 _Wikitext_emit_pending_crlf_if_necessary(parser);
2330 rb_str_cat(i, token->start, TOKEN_LEN(token));
2334 // peek ahead to see next token
2335 char *token_ptr = token->start;
2336 int token_len = TOKEN_LEN(token);
2339 if (((type == H6_END) && IN(H6_START)) ||
2340 ((type == H5_END) && IN(H5_START)) ||
2341 ((type == H4_END) && IN(H4_START)) ||
2342 ((type == H3_END) && IN(H3_START)) ||
2343 ((type == H2_END) && IN(H2_START)) ||
2344 ((type == H1_END) && IN(H1_START)))
2346 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2351 _Wikitext_pop_excess_elements(parser);
2352 _Wikitext_start_para_if_necessary(parser);
2353 rb_str_cat(i, token_ptr, token_len);
2356 // jump to top of the loop to process token we scanned during lookahead
2364 case DECIMAL_ENTITY:
2365 // pass these through unaltered as they are case sensitive
2366 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2367 _Wikitext_pop_excess_elements(parser);
2368 _Wikitext_start_para_if_necessary(parser);
2369 rb_str_cat(i, token->start, TOKEN_LEN(token));
2373 // normalize hex entities (downcase them)
2374 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2375 _Wikitext_pop_excess_elements(parser);
2376 _Wikitext_start_para_if_necessary(parser);
2377 rb_str_append(i, _Wikitext_downcase_bang(TOKEN_TEXT(token)));
2381 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2382 _Wikitext_pop_excess_elements(parser);
2383 _Wikitext_start_para_if_necessary(parser);
2384 rb_str_cat(i, quot_entity, sizeof(quot_entity) - 1);
2388 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2389 _Wikitext_pop_excess_elements(parser);
2390 _Wikitext_start_para_if_necessary(parser);
2391 rb_str_cat(i, amp_entity, sizeof(amp_entity) - 1);
2395 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2396 _Wikitext_pop_excess_elements(parser);
2397 _Wikitext_start_para_if_necessary(parser);
2398 rb_str_cat(i, lt_entity, sizeof(lt_entity) - 1);
2402 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2403 _Wikitext_pop_excess_elements(parser);
2404 _Wikitext_start_para_if_necessary(parser);
2405 rb_str_cat(i, gt_entity, sizeof(gt_entity) - 1);
2409 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2411 _Wikitext_emit_pending_crlf_if_necessary(parser);
2412 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2414 else if (!NIL_P(parser->capture))
2415 rb_str_cat(parser->capture, token->start, TOKEN_LEN(token));
2418 // not currently capturing: will be emitting something on success or failure, so get ready
2419 _Wikitext_pop_excess_elements(parser);
2420 _Wikitext_start_para_if_necessary(parser);
2422 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2423 // will cheat here and abuse the link_target capture buffer to accumulate text
2424 if (NIL_P(parser->link_target))
2425 parser->link_target = rb_str_new2("");
2426 while (NEXT_TOKEN(), (type = token->type))
2428 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2429 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2430 else if (type == IMG_END && RSTRING_LEN(parser->link_target) > 0)
2433 _Wikitext_append_img(parser, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2437 else // unexpected token or zero-length target (syntax error)
2440 rb_str_cat(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2441 rb_str_cat(parser->output, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2446 // jump to top of the loop to process token we scanned during lookahead
2447 parser->link_target = Qnil;
2453 i = parser->pending_crlf;
2454 parser->pending_crlf = false;
2455 _Wikitext_rollback_failed_link(parser); // if any
2456 if (IN(NO_WIKI_START) || IN(PRE_START))
2458 ary_clear(parser->line_buffer);
2459 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2464 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2465 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2466 // don't emit in this case
2467 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2470 if (ary_entry(parser->line_buffer, -2) == PRE)
2472 // only thing on line is the PRE: emit pending line ending (if we had one)
2474 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2477 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2478 ary_clear(parser->line);
2479 ary_clear(parser->line_buffer);
2481 // peek ahead to see if this is definitely the end of the PRE block
2484 if (type != BLOCKQUOTE && type != PRE)
2485 // this is definitely the end of the block, so don't emit
2486 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2488 // potentially will emit
2489 parser->pending_crlf = true;
2491 continue; // jump back to top of loop to handle token grabbed via lookahead
2496 parser->pending_crlf = true;
2498 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2499 // as a side effect, this handles any open span-level elements and unclosed blocks
2500 // (with special handling for P blocks and LI elements)
2501 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2502 for (j = parser->scope->count; j > i; j--)
2504 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2506 parser->pending_crlf = false;
2510 // special handling on last iteration through the loop if the top item on the scope is a P block
2511 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2513 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2514 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2515 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2516 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2517 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2519 parser->pending_crlf = false;
2521 // not a paragraph break!
2524 _Wikitext_pop_from_stack(parser, Qnil);
2528 // delete the entire contents of the line scope stack and buffer
2529 ary_clear(parser->line);
2530 ary_clear(parser->line_buffer);
2533 case SPECIAL_URI_CHARS:
2539 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2540 _Wikitext_pop_excess_elements(parser);
2541 _Wikitext_start_para_if_necessary(parser);
2542 rb_str_cat(i, token->start, TOKEN_LEN(token));
2546 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2547 _Wikitext_pop_excess_elements(parser);
2548 _Wikitext_start_para_if_necessary(parser);
2549 rb_str_append(i, _Wikitext_utf32_char_to_entity(token->code_point)); // convert to entity
2553 // special case for input like " foo\n " (see pre_spec.rb)
2555 ary_entry(parser->line_buffer, -2) == PRE &&
2556 parser->pending_crlf)
2557 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2559 // close any open scopes on hitting EOF
2560 _Wikitext_rollback_failed_link(parser); // if any
2561 _Wikitext_pop_all_from_stack(parser);
2562 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2568 // reset current token; forcing lexer to return another token at the top of the loop
2572 return parser->output;