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.
28 #include "wikitext_ragel.h"
30 #define IN(type) ary_includes(parser->scope, type)
32 // poor man's object orientation in C:
33 // instead of parsing around multiple parameters between functions in the parser
34 // we pack everything into a struct and pass around only a pointer to that
35 // TODO: consider changing some of the VALUE members (eg link_target) to the more efficient str_t type
38 VALUE output; // for accumulating output to be returned
39 VALUE capture; // for capturing substrings
40 VALUE link_target; // short term "memory" for parsing links
41 VALUE link_text; // short term "memory" for parsing links
42 VALUE external_link_class; // CSS class applied to external links
43 VALUE mailto_class; // CSS class applied to email (mailto) links
44 VALUE img_prefix; // path prepended when emitting img tags
45 ary_t *scope; // stack for tracking scope
46 ary_t *line; // stack for tracking scope as implied by current line
47 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
48 VALUE pending_crlf; // boolean (Qtrue or Qfalse)
49 VALUE autolink; // boolean (Qtrue or Qfalse)
50 VALUE space_to_underscore; // boolean (Qtrue or Qfalse)
52 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
53 int current_indent; // fluctuates according to currently nested structures
54 str_t *tabulation; // caching buffer for emitting indentation
55 int base_heading_level;
58 const char escaped_no_wiki_start[] = "<nowiki>";
59 const char escaped_no_wiki_end[] = "</nowiki>";
60 const char literal_strong_em[] = "'''''";
61 const char literal_strong[] = "'''";
62 const char literal_em[] = "''";
63 const char escaped_em_start[] = "<em>";
64 const char escaped_em_end[] = "</em>";
65 const char escaped_strong_start[] = "<strong>";
66 const char escaped_strong_end[] = "</strong>";
67 const char escaped_tt_start[] = "<tt>";
68 const char escaped_tt_end[] = "</tt>";
69 const char literal_h6[] = "======";
70 const char literal_h5[] = "=====";
71 const char literal_h4[] = "====";
72 const char literal_h3[] = "===";
73 const char literal_h2[] = "==";
74 const char literal_h1[] = "=";
75 const char pre_start[] = "<pre>";
76 const char pre_end[] = "</pre>";
77 const char escaped_pre_start[] = "<pre>";
78 const char escaped_pre_end[] = "</pre>";
79 const char blockquote_start[] = "<blockquote>";
80 const char blockquote_end[] = "</blockquote>";
81 const char escaped_blockquote_start[] = "<blockquote>";
82 const char escaped_blockquote_end[] = "</blockquote>";
83 const char strong_em_start[] = "<strong><em>";
84 const char strong_start[] = "<strong>";
85 const char strong_end[] = "</strong>";
86 const char em_start[] = "<em>";
87 const char em_end[] = "</em>";
88 const char tt_start[] = "<tt>";
89 const char tt_end[] = "</tt>";
90 const char ol_start[] = "<ol>";
91 const char ol_end[] = "</ol>";
92 const char ul_start[] = "<ul>";
93 const char ul_end[] = "</ul>";
94 const char li_start[] = "<li>";
95 const char li_end[] = "</li>";
96 const char h6_start[] = "<h6>";
97 const char h6_end[] = "</h6>";
98 const char h5_start[] = "<h5>";
99 const char h5_end[] = "</h5>";
100 const char h4_start[] = "<h4>";
101 const char h4_end[] = "</h4>";
102 const char h3_start[] = "<h3>";
103 const char h3_end[] = "</h3>";
104 const char h2_start[] = "<h2>";
105 const char h2_end[] = "</h2>";
106 const char h1_start[] = "<h1>";
107 const char h1_end[] = "</h1>";
108 const char p_start[] = "<p>";
109 const char p_end[] = "</p>";
110 const char space[] = " ";
111 const char a_start[] = "<a href=\"";
112 const char a_class[] = "\" class=\"";
113 const char a_start_close[] = "\">";
114 const char a_end[] = "</a>";
115 const char link_start[] = "[[";
116 const char link_end[] = "]]";
117 const char separator[] = "|";
118 const char ext_link_start[] = "[";
119 const char backtick[] = "`";
120 const char quote[] = "\"";
121 const char ampersand[] = "&";
122 const char quot_entity[] = """;
123 const char amp_entity[] = "&";
124 const char lt_entity[] = "<";
125 const char gt_entity[] = ">";
126 const char escaped_blockquote[] = "> ";
127 const char ext_link_end[] = "]";
128 const char literal_img_start[] = "{{";
129 const char img_start[] = "<img src=\"";
130 const char img_end[] = "\" />";
131 const char img_alt[] = "\" alt=\"";
133 // for testing and debugging only
134 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
138 string = StringValue(string);
139 VALUE tokens = rb_ary_new();
140 char *p = RSTRING_PTR(string);
141 long len = RSTRING_LEN(string);
144 next_token(&token, NULL, p, pe);
145 rb_ary_push(tokens, _Wikitext_token(&token));
146 while (token.type != END_OF_FILE)
148 next_token(&token, &token, NULL, pe);
149 rb_ary_push(tokens, _Wikitext_token(&token));
154 // for benchmarking raw tokenization speed only
155 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
159 string = StringValue(string);
160 char *p = RSTRING_PTR(string);
161 long len = RSTRING_LEN(string);
164 next_token(&token, NULL, p, pe);
165 while (token.type != END_OF_FILE)
166 next_token(&token, &token, NULL, pe);
170 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
173 VALUE string, options;
174 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
178 string = StringValue(string);
179 VALUE tokens = rb_ary_new();
181 // check instance variables
182 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
184 // process options hash (can override instance variables)
185 if (!NIL_P(options) && TYPE(options) == T_HASH)
187 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
188 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
190 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
195 char *p = RSTRING_PTR(string);
196 long len = RSTRING_LEN(string);
199 token_t *_token = &token;
200 next_token(&token, NULL, p, pe);
201 while (token.type != END_OF_FILE)
208 if (TOKEN_LEN(_token) >= min_len)
209 rb_ary_push(tokens, TOKEN_TEXT(_token));
212 // ignore everything else
215 next_token(&token, &token, NULL, pe);
220 // we downcase "in place", overwriting the original contents of the buffer and returning the same string
221 VALUE _Wikitext_downcase_bang(VALUE string)
223 char *ptr = RSTRING_PTR(string);
224 long len = RSTRING_LEN(string);
225 for (long i = 0; i < len; i++)
227 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
233 // prepare hyperlink and append it to parser->output
234 // if check_autolink is Qtrue, checks parser->autolink to decide whether to emit a real hyperlink
235 // or merely the literal link target
236 // if link_text is Qnil, the link_target is re-used for the link text
237 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class, VALUE check_autolink)
239 if (check_autolink == Qtrue && parser->autolink != Qtrue)
240 rb_str_append(parser->output, link_target);
243 rb_str_cat(parser->output, a_start, sizeof(a_start) - 1); // <a href="
244 if (!NIL_P(link_prefix))
245 rb_str_append(parser->output, link_prefix);
246 rb_str_append(parser->output, link_target);
248 // special handling for mailto URIs
249 const char *mailto = "mailto:";
250 if (NIL_P(link_prefix) &&
251 RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
252 strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
253 link_class = parser->mailto_class; // use mailto_class from parser
254 if (link_class != Qnil)
256 rb_str_cat(parser->output, a_class, sizeof(a_class) - 1); // " class="
257 rb_str_append(parser->output, link_class);
259 rb_str_cat(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
260 if (NIL_P(link_text)) // re-use link_target
261 rb_str_append(parser->output, link_target);
263 rb_str_append(parser->output, link_text);
264 rb_str_cat(parser->output, a_end, sizeof(a_end) - 1); // </a>
268 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
270 rb_str_cat(parser->output, img_start, sizeof(img_start) - 1); // <img src="
271 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
272 rb_str_append(parser->output, parser->img_prefix);
273 rb_str_cat(parser->output, token_ptr, token_len);
274 rb_str_cat(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
275 rb_str_cat(parser->output, token_ptr, token_len);
276 rb_str_cat(parser->output, img_end, sizeof(img_end) - 1); // " />
279 // will emit indentation only if we are about to emit any of:
280 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
281 // each time we enter one of those spans must ++ the indentation level
282 void _Wikitext_indent(parser_t *parser)
284 if (parser->base_indent == -1) // indentation disabled
286 int space_count = parser->current_indent + parser->base_indent;
289 char *old_end, *new_end;
290 if (parser->tabulation->len < space_count)
291 str_grow(parser->tabulation, space_count); // reallocates if necessary
292 old_end = parser->tabulation->ptr + parser->tabulation->len;
293 new_end = parser->tabulation->ptr + space_count;
294 while (old_end < new_end)
296 if (space_count > parser->tabulation->len)
297 parser->tabulation->len = space_count;
298 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
300 parser->current_indent += 2;
303 void _Wikitext_dedent(parser_t *parser, VALUE emit)
305 if (parser->base_indent == -1) // indentation disabled
307 parser->current_indent -= 2;
310 int space_count = parser->current_indent + parser->base_indent;
312 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
315 // Pops a single item off the parser's scope stack.
316 // A corresponding closing tag is written to the target string.
317 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
318 void _Wikitext_pop_from_stack(parser_t *parser, VALUE target)
320 int top = ary_entry(parser->scope, -1);
324 target = parser->output;
326 // for headings, take base_heading_level into account
327 if (top >= H1_START && top <= H6_START)
329 top += parser->base_heading_level;
330 // no need to check for underflow (base_heading_level is never negative)
339 rb_str_cat(target, pre_end, sizeof(pre_end) - 1);
340 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
341 _Wikitext_dedent(parser, Qfalse);
345 case BLOCKQUOTE_START:
346 _Wikitext_dedent(parser, Qtrue);
347 rb_str_cat(target, blockquote_end, sizeof(blockquote_end) - 1);
348 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
352 // not a real HTML tag; so nothing to pop
357 rb_str_cat(target, strong_end, sizeof(strong_end) - 1);
362 rb_str_cat(target, em_end, sizeof(em_end) - 1);
367 rb_str_cat(target, tt_end, sizeof(tt_end) - 1);
371 _Wikitext_dedent(parser, Qtrue);
372 rb_str_cat(target, ol_end, sizeof(ol_end) - 1);
373 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
377 _Wikitext_dedent(parser, Qtrue);
378 rb_str_cat(target, ul_end, sizeof(ul_end) - 1);
379 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
383 // next token to pop will be a LI
384 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
385 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
386 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
387 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
388 _Wikitext_dedent(parser, Qtrue); // we really only want to emit the spaces
389 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
393 rb_str_cat(target, li_end, sizeof(li_end) - 1);
394 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
395 _Wikitext_dedent(parser, Qfalse);
399 rb_str_cat(target, h6_end, sizeof(h6_end) - 1);
400 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
401 _Wikitext_dedent(parser, Qfalse);
405 rb_str_cat(target, h5_end, sizeof(h5_end) - 1);
406 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
407 _Wikitext_dedent(parser, Qfalse);
411 rb_str_cat(target, h4_end, sizeof(h4_end) - 1);
412 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
413 _Wikitext_dedent(parser, Qfalse);
417 rb_str_cat(target, h3_end, sizeof(h3_end) - 1);
418 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
419 _Wikitext_dedent(parser, Qfalse);
423 rb_str_cat(target, h2_end, sizeof(h2_end) - 1);
424 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
425 _Wikitext_dedent(parser, Qfalse);
429 rb_str_cat(target, h1_end, sizeof(h1_end) - 1);
430 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
431 _Wikitext_dedent(parser, Qfalse);
435 // not an HTML tag; so nothing to emit
439 // not an HTML tag; so nothing to emit
443 // not an HTML tag; so nothing to emit
447 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
451 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
455 rb_str_cat(target, p_end, sizeof(p_end) - 1);
456 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
457 _Wikitext_dedent(parser, Qfalse);
465 // should probably raise an exception here
468 ary_pop(parser->scope);
471 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
472 // If including is Qtrue then the item itself is also popped.
473 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
474 void _Wikitext_pop_from_stack_up_to(parser_t *parser, VALUE target, int item, VALUE including)
476 int continue_looping = 1;
479 int top = ary_entry(parser->scope, -1);
484 if (including != Qtrue)
486 continue_looping = 0;
488 _Wikitext_pop_from_stack(parser, target);
489 } while (continue_looping);
492 void _Wikitext_pop_all_from_stack(parser_t *parser, VALUE target)
494 for (int i = 0, max = parser->scope->count; i < max; i++)
495 _Wikitext_pop_from_stack(parser, target);
498 void _Wikitext_start_para_if_necessary(parser_t *parser)
500 if (!NIL_P(parser->capture)) // we don't do anything if in capturing mode
503 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
504 if (parser->scope->count == 0 ||
505 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
506 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
508 _Wikitext_indent(parser);
509 rb_str_cat(parser->output, p_start, sizeof(p_start) - 1);
510 ary_push(parser->scope, P);
511 ary_push(parser->line, P);
513 else if (parser->pending_crlf == Qtrue)
516 // already in a paragraph block; convert pending CRLF into a space
517 rb_str_cat(parser->output, space, sizeof(space) - 1);
519 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
520 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
522 parser->pending_crlf = Qfalse;
525 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
527 if (parser->pending_crlf == Qtrue)
529 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
530 parser->pending_crlf = Qfalse;
534 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
535 // For example, given input like:
540 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
541 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
546 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
547 // but not on the line scope:
552 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
553 // on the line scope.
554 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
555 // entering the for loop.
556 void _Wikitext_pop_excess_elements(parser_t *parser)
558 if (!NIL_P(parser->capture)) // we don't pop anything if in capturing mode
560 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
562 // special case for last item on scope
565 // don't auto-pop P if it is only item on scope
566 if (ary_entry(parser->scope, -1) == P)
568 // add P to the line scope to prevent us entering the loop at all next time around
569 ary_push(parser->line, P);
573 _Wikitext_pop_from_stack(parser, parser->output);
577 #define INVALID_ENCODING(msg) do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
579 // convert a single UTF-8 codepoint to UTF-32
580 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
581 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
582 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
583 // raises a RangeError if the supplied character is invalid UTF-8
584 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
585 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
588 if ((unsigned char)src[0] <= 0x7f) // ASCII
593 else if ((src[0] & 0xe0) == 0xc0) // byte starts with 110..... : this should be a two-byte sequence
596 INVALID_ENCODING("truncated byte sequence"); // no second byte
597 else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
598 INVALID_ENCODING("overlong encoding"); // overlong encoding: lead byte of 110..... but code point <= 127
599 else if ((src[1] & 0xc0) != 0x80 )
600 INVALID_ENCODING("malformed byte sequence"); // should have second byte starting with 10......
601 dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
604 else if ((src[0] & 0xf0) == 0xe0) // byte starts with 1110.... : this should be a three-byte sequence
607 INVALID_ENCODING("truncated byte sequence"); // missing second or third byte
608 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
609 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
610 dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
613 else if ((src[0] & 0xf8) == 0xf0) // bytes starts with 11110... : this should be a four-byte sequence
616 INVALID_ENCODING("truncated byte sequence"); // missing second, third, or fourth byte
617 else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
618 INVALID_ENCODING("overlong encoding"); // disallowed by RFC 3629 (codepoints above 0x10ffff)
619 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
620 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
621 dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
624 else // invalid input
625 INVALID_ENCODING("unexpected byte");
629 VALUE _Wikitext_utf32_char_to_entity(uint32_t character)
631 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
632 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
633 char scratch = (character & 0xf000) >> 12;
634 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
635 scratch = (character & 0x0f00) >> 8;
636 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
637 scratch = (character & 0x00f0) >> 4;
638 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
639 scratch = character & 0x000f;
640 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
641 return rb_str_new((const char *)hex_string, sizeof(hex_string));
644 VALUE _Wikitext_parser_trim_link_target(VALUE string)
646 string = StringValue(string);
647 char *src = RSTRING_PTR(string);
648 char *start = src; // remember this so we can check if we're at the start
650 char *non_space = src; // remember last non-space character output
651 long len = RSTRING_LEN(string);
652 char *end = src + len;
664 if (left == start && non_space + 1 == end)
667 return rb_str_new(left, (non_space + 1) - left);
670 // - non-printable (non-ASCII) characters converted to numeric entities
671 // - QUOT and AMP characters converted to named entities
672 // - if rollback is Qtrue, there is no special treatment of spaces
673 // - if rollback is Qfalse, leading and trailing whitespace trimmed
674 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, VALUE rollback)
676 VALUE string = StringValue(parser->link_target); // raises if string is nil or doesn't quack like a string
677 char *src = RSTRING_PTR(string);
678 char *start = src; // remember this so we can check if we're at the start
679 long len = RSTRING_LEN(string);
680 char *end = src + len;
682 // start with a destination buffer twice the size of the source, will realloc if necessary
683 // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
684 // this efficiently handles the most common case (where the size of the buffer doesn't change much)
685 char *dest = ALLOC_N(char, len * 2);
686 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
687 char *non_space = dest; // remember last non-space character output
690 // need at most 8 characters (8 bytes) to display each character
691 if (dest + 8 > dest_ptr + len) // outgrowing buffer, must reallocate
693 char *old_dest = dest;
694 char *old_dest_ptr = dest_ptr;
695 len = len + (end - src) * 8; // allocate enough for worst case
696 dest = realloc(dest_ptr, len); // will never have to realloc more than once
699 // would have used reallocf, but this has to run on Linux too, not just Darwin
701 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
704 dest = dest_ptr + (old_dest - old_dest_ptr);
705 non_space = dest_ptr + (non_space - old_dest_ptr);
708 if (*src == '"') // QUOT
710 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
711 memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
712 dest += sizeof(quot_entity_literal);
714 else if (*src == '&') // AMP
716 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
717 memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
718 dest += sizeof(amp_entity_literal);
720 else if (*src == '<') // LESS_THAN
723 rb_raise(rb_eRangeError, "invalid link text (\"<\" may not appear in link text)");
725 else if (*src == '>') // GREATER_THAN
728 rb_raise(rb_eRangeError, "invalid link text (\">\" may not appear in link text)");
730 else if (*src == ' ' && src == start && rollback == Qfalse)
731 start++; // we eat leading space
732 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
737 else // all others: must convert to entities
740 VALUE entity = _Wikitext_utf32_char_to_entity(_Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
741 char *entity_src = RSTRING_PTR(entity);
742 long entity_len = RSTRING_LEN(entity); // should always be 8 characters (8 bytes)
743 memcpy(dest, entity_src, entity_len);
754 // trim trailing space if necessary
755 if (rollback == Qfalse && non_space > dest_ptr && dest != non_space)
756 len = non_space - dest_ptr;
758 len = dest - dest_ptr;
759 VALUE out = rb_str_new(dest_ptr, len);
764 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
767 parser.link_target = string;
768 return _Wikitext_parser_sanitize_link_target(&parser, Qfalse);
771 // encodes the input string according to RFCs 2396 and 2718
772 // leading and trailing whitespace trimmed
773 // note that the first character of the target link is not case-sensitive
774 // (this is a recommended application-level constraint; it is not imposed at this level)
775 // this is to allow links like:
776 // ...the [[foo]] is...
777 // to be equivalent to:
778 // thing. [[Foo]] was...
779 static void _Wikitext_parser_encode_link_target(parser_t *parser)
781 VALUE in = StringValue(parser->link_target);
782 char *input = RSTRING_PTR(in);
783 char *start = input; // remember this so we can check if we're at the start
784 long len = RSTRING_LEN(in);
787 char *end = input + len;
788 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
790 // to avoid most reallocations start with a destination buffer twice the size of the source
791 // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
792 // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
793 // the worst case is where _every_ byte must be written out using 3 bytes
794 long dest_len = len * 2;
795 char *dest = ALLOC_N(char, dest_len);
796 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
797 char *non_space = dest; // remember last non-space character output
798 for (; input < end; input++)
800 if ((dest + 3) > (dest_ptr + dest_len)) // worst case: a single character may grow to 3 characters once encoded
802 // outgrowing buffer, must reallocate
803 char *old_dest = dest;
804 char *old_dest_ptr = dest_ptr;
806 dest = realloc(dest_ptr, dest_len);
809 // would have used reallocf, but this has to run on Linux too, not just Darwin
811 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
814 dest = dest_ptr + (old_dest - old_dest_ptr);
815 non_space = dest_ptr + (non_space - old_dest_ptr);
818 // pass through unreserved characters
819 if (((*input >= 'a') && (*input <= 'z')) ||
820 ((*input >= 'A') && (*input <= 'Z')) ||
821 ((*input >= '0') && (*input <= '9')) ||
830 else if (*input == ' ' && input == start)
831 start++; // we eat leading space
832 else if (*input == ' ' && parser->space_to_underscore == Qtrue)
834 else // everything else gets URL-encoded
837 *dest++ = hex[(unsigned char)(*input) / 16]; // left
838 *dest++ = hex[(unsigned char)(*input) % 16]; // right
844 // trim trailing space if necessary
845 if (non_space > dest_ptr && dest != non_space)
846 dest_len = non_space - dest_ptr;
848 dest_len = dest - dest_ptr;
849 parser->link_target = rb_str_new(dest_ptr, dest_len);
853 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
856 parser.link_target = in;
857 parser.space_to_underscore = Qfalse;
858 _Wikitext_parser_encode_link_target(&parser);
859 return parser.link_target;
862 // this method exposed for testing only
863 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
866 parser.link_target = in;
867 parser.space_to_underscore = Qfalse;
868 _Wikitext_parser_encode_link_target(&parser);
869 return parser.link_target;
872 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
873 // returns 0 (false) otherwise
874 int _Wikitext_blank(VALUE str)
876 if (NIL_P(str) || RSTRING_LEN(str) == 0)
878 for (char *ptr = RSTRING_PTR(str),
879 *end = RSTRING_PTR(str) + RSTRING_LEN(str);
888 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
891 return; // nothing to do!
892 int scope_includes_separator = IN(SEPARATOR);
893 _Wikitext_pop_from_stack_up_to(parser, Qnil, LINK_START, Qtrue);
894 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
895 if (!NIL_P(parser->link_target))
897 VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, Qtrue);
898 rb_str_append(parser->output, sanitized);
899 if (scope_includes_separator)
901 rb_str_cat(parser->output, separator, sizeof(separator) - 1);
902 if (!NIL_P(parser->link_text))
903 rb_str_append(parser->output, parser->link_text);
906 parser->capture = Qnil;
907 parser->link_target = Qnil;
908 parser->link_text = Qnil;
911 void _Wikitext_rollback_failed_external_link(parser_t *parser)
913 if (!IN(EXT_LINK_START))
914 return; // nothing to do!
916 // store a couple of values before popping
917 int scope_includes_space = IN(SPACE);
918 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
919 _Wikitext_pop_from_stack_up_to(parser, Qnil, EXT_LINK_START, Qtrue);
921 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
922 if (!NIL_P(parser->link_target))
924 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, Qnil, link_class, Qtrue);
925 if (scope_includes_space)
927 rb_str_cat(parser->output, space, sizeof(space) - 1);
928 if (!NIL_P(parser->link_text))
929 rb_str_append(parser->output, parser->link_text);
932 parser->capture = Qnil;
933 parser->link_target = Qnil;
934 parser->link_text = Qnil;
937 void _Wikitext_rollback_failed_link(parser_t *parser)
939 _Wikitext_rollback_failed_internal_link(parser);
940 _Wikitext_rollback_failed_external_link(parser);
943 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
947 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
951 VALUE autolink = Qtrue;
952 VALUE line_ending = rb_str_new2("\n");
953 VALUE external_link_class = rb_str_new2("external");
954 VALUE mailto_class = rb_str_new2("mailto");
955 VALUE internal_link_prefix = rb_str_new2("/wiki/");
956 VALUE img_prefix = rb_str_new2("/images/");
957 VALUE space_to_underscore = Qtrue;
958 VALUE minimum_fulltext_token_length = INT2NUM(3);
959 VALUE base_heading_level = INT2NUM(0);
961 // process options hash (override defaults)
962 if (!NIL_P(options) && TYPE(options) == T_HASH)
964 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
965 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
966 autolink = OVERRIDE_IF_SET(autolink);
967 line_ending = OVERRIDE_IF_SET(line_ending);
968 external_link_class = OVERRIDE_IF_SET(external_link_class);
969 mailto_class = OVERRIDE_IF_SET(mailto_class);
970 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
971 img_prefix = OVERRIDE_IF_SET(img_prefix);
972 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
973 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
974 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
977 // no need to call super here; rb_call_super()
978 rb_iv_set(self, "@autolink", autolink);
979 rb_iv_set(self, "@line_ending", line_ending);
980 rb_iv_set(self, "@external_link_class", external_link_class);
981 rb_iv_set(self, "@mailto_class", mailto_class);
982 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
983 rb_iv_set(self, "@img_prefix", img_prefix);
984 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
985 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
986 rb_iv_set(self, "@base_heading_level", base_heading_level);
990 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
992 for (int i = 0; i < 100000; i++)
993 Wikitext_parser_parse(1, &string, self);
997 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1000 VALUE string, options;
1001 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1005 string = StringValue(string);
1007 // process options hash
1008 int base_indent = 0;
1009 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1010 if (!NIL_P(options) && TYPE(options) == T_HASH)
1012 // :indent => 0 (or more)
1013 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1015 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1016 if (indent == Qfalse)
1017 base_indent = -1; // indentation disabled
1020 base_indent = NUM2INT(indent);
1021 if (base_indent < 0)
1026 // :base_heading_level => 0/1/2/3/4/5/6
1027 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1028 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1031 // normalize, regardless of whether this came from instance variable or override
1032 if (base_heading_level < 0)
1033 base_heading_level = 0;
1034 if (base_heading_level > 6)
1035 base_heading_level = 6;
1038 char *p = RSTRING_PTR(string);
1039 long len = RSTRING_LEN(string);
1042 // access these once per parse
1043 VALUE line_ending = rb_iv_get(self, "@line_ending");
1044 line_ending = StringValue(line_ending);
1045 VALUE link_class = rb_iv_get(self, "@external_link_class");
1046 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1047 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1048 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1049 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1051 // set up parser struct to make passing parameters a little easier
1052 // eventually this will encapsulate most or all of the variables above
1054 parser_t *parser = &_parser;
1055 parser->output = rb_str_new2("");
1056 parser->capture = Qnil;
1057 parser->link_target = Qnil;
1058 parser->link_text = Qnil;
1059 parser->external_link_class = link_class;
1060 parser->mailto_class = mailto_class;
1061 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1062 parser->scope = ary_new();
1063 GC_WRAP_ARY(parser->scope, scope_gc);
1064 parser->line = ary_new();
1065 GC_WRAP_ARY(parser->line, line_gc);
1066 parser->line_buffer = ary_new();
1067 GC_WRAP_ARY(parser->line_buffer, line_buffer_gc);
1068 parser->pending_crlf = Qfalse;
1069 parser->autolink = rb_iv_get(self, "@autolink");
1070 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore");
1071 parser->line_ending = str_new_from_string(line_ending);
1072 GC_WRAP_STR(parser->line_ending, line_ending_gc);
1073 parser->base_indent = base_indent;
1074 parser->current_indent = 0;
1075 parser->tabulation = str_new();
1076 GC_WRAP_STR(parser->tabulation, tabulation_gc);
1077 parser->base_heading_level = base_heading_level;
1079 // this simple looping design leads to a single enormous function,
1080 // but it's faster than doing actual recursive descent and also secure in the face of
1081 // malicious input that seeks to overflow the stack
1082 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1083 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1084 // than a straightforward looping translator like this one anyway
1086 _token.type = NO_TOKEN;
1087 token_t *token = NULL;
1090 // note that whenever we grab a token we push it into the line buffer
1091 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1092 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1094 // check to see if we have a token hanging around from a previous iteration of this loop
1097 if (_token.type == NO_TOKEN)
1099 // first time here (haven't started scanning yet)
1101 next_token(token, NULL, p, pe);
1102 ary_push(parser->line_buffer, token->type);
1108 int type = token->type;
1110 // can't declare new variables inside a switch statement, so predeclare them here
1111 long remove_strong = -1;
1112 long remove_em = -1;
1114 // general purpose counters and flags
1119 // The following giant switch statement contains cases for all the possible token types.
1120 // In the most basic sense we are emitting the HTML that corresponds to each token,
1121 // but some tokens require context information in order to decide what to output.
1122 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1123 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1125 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1126 // - the line buffer (records tokens seen so far on the current line)
1127 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1129 // Although this is fairly complicated, there is one key simplifying factor:
1130 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1131 // scope stack (up to the current token) is valid; our translator can take this as a given.
1132 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1133 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1137 if (IN(NO_WIKI_START) || IN(PRE_START))
1139 rb_str_cat(parser->output, space, sizeof(space) - 1);
1142 else if (IN(BLOCKQUOTE_START))
1144 // this kind of nesting not allowed (to avoid user confusion)
1145 _Wikitext_pop_excess_elements(parser);
1146 _Wikitext_start_para_if_necessary(parser);
1147 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1148 rb_str_cat(i, space, sizeof(space) - 1);
1152 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1153 ary_push(parser->line, PRE);
1154 i = ary_count(parser->line, BLOCKQUOTE);
1155 j = ary_count(parser->scope, BLOCKQUOTE);
1158 // must pop (reduce nesting level)
1159 for (i = j - i; i > 0; i--)
1160 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1165 parser->pending_crlf = Qfalse;
1166 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1167 _Wikitext_indent(parser);
1168 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1169 ary_push(parser->scope, PRE);
1174 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1176 _Wikitext_emit_pending_crlf_if_necessary(parser);
1177 rb_str_cat(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1179 else if (IN(BLOCKQUOTE_START))
1181 _Wikitext_rollback_failed_link(parser); // if any
1182 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1183 _Wikitext_indent(parser);
1184 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1185 ary_push(parser->scope, PRE_START);
1186 ary_push(parser->line, PRE_START);
1188 else if (IN(BLOCKQUOTE))
1190 if (token->column_start == 1) // only allowed in first column
1192 _Wikitext_rollback_failed_link(parser); // if any
1193 _Wikitext_pop_all_from_stack(parser, Qnil);
1194 _Wikitext_indent(parser);
1195 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1196 ary_push(parser->scope, PRE_START);
1197 ary_push(parser->line, PRE_START);
1199 else // PRE_START illegal here
1201 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1202 _Wikitext_pop_excess_elements(parser);
1203 _Wikitext_start_para_if_necessary(parser);
1204 rb_str_cat(i, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1209 _Wikitext_rollback_failed_link(parser); // if any
1210 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1211 _Wikitext_indent(parser);
1212 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1213 ary_push(parser->scope, PRE_START);
1214 ary_push(parser->line, PRE_START);
1219 if (IN(NO_WIKI_START) || IN(PRE))
1221 _Wikitext_emit_pending_crlf_if_necessary(parser);
1222 rb_str_cat(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1227 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, Qtrue);
1230 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1231 _Wikitext_pop_excess_elements(parser);
1232 _Wikitext_start_para_if_necessary(parser);
1233 rb_str_cat(i, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1239 if (IN(NO_WIKI_START) || IN(PRE_START))
1240 // no need to check for <pre>; can never appear inside it
1241 rb_str_cat(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1242 else if (IN(BLOCKQUOTE_START))
1244 // this kind of nesting not allowed (to avoid user confusion)
1245 _Wikitext_pop_excess_elements(parser);
1246 _Wikitext_start_para_if_necessary(parser);
1247 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1248 rb_str_cat(i, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1253 ary_push(parser->line, BLOCKQUOTE);
1255 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1256 i = ary_count(parser->line, BLOCKQUOTE);
1257 j = ary_count(parser->scope, BLOCKQUOTE);
1259 // 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
1260 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1262 ary_push(parser->line, BLOCKQUOTE);
1266 // now decide whether to push, pop or do nothing
1269 // must push (increase nesting level)
1270 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1271 for (i = i - j; i > 0; i--)
1273 _Wikitext_indent(parser);
1274 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1275 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1276 ary_push(parser->scope, BLOCKQUOTE);
1281 // must pop (reduce nesting level)
1282 for (i = j - i; i > 0; i--)
1283 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1286 // jump to top of the loop to process token we scanned during lookahead
1291 case BLOCKQUOTE_START:
1292 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1294 _Wikitext_emit_pending_crlf_if_necessary(parser);
1295 rb_str_cat(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1297 else if (IN(BLOCKQUOTE_START))
1299 // nesting is fine here
1300 _Wikitext_rollback_failed_link(parser); // if any
1301 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1302 _Wikitext_indent(parser);
1303 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1304 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1305 ary_push(parser->scope, BLOCKQUOTE_START);
1306 ary_push(parser->line, BLOCKQUOTE_START);
1308 else if (IN(BLOCKQUOTE))
1310 if (token->column_start == 1) // only allowed in first column
1312 _Wikitext_rollback_failed_link(parser); // if any
1313 _Wikitext_pop_all_from_stack(parser, Qnil);
1314 _Wikitext_indent(parser);
1315 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1316 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1317 ary_push(parser->scope, BLOCKQUOTE_START);
1318 ary_push(parser->line, BLOCKQUOTE_START);
1320 else // BLOCKQUOTE_START illegal here
1322 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1323 _Wikitext_pop_excess_elements(parser);
1324 _Wikitext_start_para_if_necessary(parser);
1325 rb_str_cat(i, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1330 // would be nice to eliminate the repetition here but it's probably the clearest way
1331 _Wikitext_rollback_failed_link(parser); // if any
1332 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1333 _Wikitext_indent(parser);
1334 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1335 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1336 ary_push(parser->scope, BLOCKQUOTE_START);
1337 ary_push(parser->line, BLOCKQUOTE_START);
1341 case BLOCKQUOTE_END:
1342 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1344 _Wikitext_emit_pending_crlf_if_necessary(parser);
1345 rb_str_cat(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1349 if (IN(BLOCKQUOTE_START))
1350 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, Qtrue);
1353 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1354 _Wikitext_pop_excess_elements(parser);
1355 _Wikitext_start_para_if_necessary(parser);
1356 rb_str_cat(i, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1362 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1364 _Wikitext_emit_pending_crlf_if_necessary(parser);
1365 rb_str_cat(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1369 _Wikitext_pop_excess_elements(parser);
1370 _Wikitext_start_para_if_necessary(parser);
1371 ary_push(parser->scope, NO_WIKI_START);
1372 ary_push(parser->line, NO_WIKI_START);
1377 if (IN(NO_WIKI_START))
1378 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1379 _Wikitext_pop_from_stack_up_to(parser, Qnil, NO_WIKI_START, Qtrue);
1382 _Wikitext_pop_excess_elements(parser);
1383 _Wikitext_start_para_if_necessary(parser);
1384 rb_str_cat(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1389 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1391 _Wikitext_emit_pending_crlf_if_necessary(parser);
1392 rb_str_cat(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1396 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1397 _Wikitext_pop_excess_elements(parser);
1399 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1400 // otherwise, must open them
1403 j = parser->scope->count;
1404 for (j = j - 1; j >= 0; j--)
1406 int val = ary_entry(parser->scope, j);
1407 if (val == STRONG || val == STRONG_START)
1409 rb_str_cat(i, strong_end, sizeof(strong_end) - 1);
1412 else if (val == EM || val == EM_START)
1414 rb_str_cat(i, em_end, sizeof(em_end) - 1);
1419 if (remove_strong > remove_em) // must remove strong first
1421 ary_pop(parser->scope);
1423 ary_pop(parser->scope);
1424 else // there was no em to remove!, so consider this an opening em tag
1426 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1427 ary_push(parser->scope, EM);
1428 ary_push(parser->line, EM);
1431 else if (remove_em > remove_strong) // must remove em first
1433 ary_pop(parser->scope);
1434 if (remove_strong > -1)
1435 ary_pop(parser->scope);
1436 else // there was no strong to remove!, so consider this an opening strong tag
1438 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1439 ary_push(parser->scope, STRONG);
1440 ary_push(parser->line, STRONG);
1443 else // no strong or em to remove, so this must be a new opening of both
1445 _Wikitext_start_para_if_necessary(parser);
1446 rb_str_cat(i, strong_em_start, sizeof(strong_em_start) - 1);
1447 ary_push(parser->scope, STRONG);
1448 ary_push(parser->line, STRONG);
1449 ary_push(parser->scope, EM);
1450 ary_push(parser->line, EM);
1455 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1457 _Wikitext_emit_pending_crlf_if_necessary(parser);
1458 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1462 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1463 if (IN(STRONG_START))
1464 // already in span started with <strong>, no choice but to emit this literally
1465 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1466 else if (IN(STRONG))
1467 // STRONG already seen, this is a closing tag
1468 _Wikitext_pop_from_stack_up_to(parser, i, STRONG, Qtrue);
1471 // this is a new opening
1472 _Wikitext_pop_excess_elements(parser);
1473 _Wikitext_start_para_if_necessary(parser);
1474 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1475 ary_push(parser->scope, STRONG);
1476 ary_push(parser->line, STRONG);
1482 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1484 _Wikitext_emit_pending_crlf_if_necessary(parser);
1485 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1489 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1490 if (IN(STRONG_START) || IN(STRONG))
1491 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1494 _Wikitext_pop_excess_elements(parser);
1495 _Wikitext_start_para_if_necessary(parser);
1496 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1497 ary_push(parser->scope, STRONG_START);
1498 ary_push(parser->line, STRONG_START);
1504 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1506 _Wikitext_emit_pending_crlf_if_necessary(parser);
1507 rb_str_cat(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1511 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1512 if (IN(STRONG_START))
1513 _Wikitext_pop_from_stack_up_to(parser, i, STRONG_START, Qtrue);
1516 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1517 _Wikitext_pop_excess_elements(parser);
1518 _Wikitext_start_para_if_necessary(parser);
1519 rb_str_cat(i, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1525 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1527 _Wikitext_emit_pending_crlf_if_necessary(parser);
1528 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1532 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1534 // already in span started with <em>, no choice but to emit this literally
1535 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1537 // EM already seen, this is a closing tag
1538 _Wikitext_pop_from_stack_up_to(parser, i, EM, Qtrue);
1541 // this is a new opening
1542 _Wikitext_pop_excess_elements(parser);
1543 _Wikitext_start_para_if_necessary(parser);
1544 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1545 ary_push(parser->scope, EM);
1546 ary_push(parser->line, EM);
1552 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1554 _Wikitext_emit_pending_crlf_if_necessary(parser);
1555 rb_str_cat(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1559 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1560 if (IN(EM_START) || IN(EM))
1561 rb_str_cat(i, escaped_em_start, sizeof(escaped_em_start) - 1);
1564 _Wikitext_pop_excess_elements(parser);
1565 _Wikitext_start_para_if_necessary(parser);
1566 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1567 ary_push(parser->scope, EM_START);
1568 ary_push(parser->line, EM_START);
1574 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1576 _Wikitext_emit_pending_crlf_if_necessary(parser);
1577 rb_str_cat(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1581 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1583 _Wikitext_pop_from_stack_up_to(parser, i, EM_START, Qtrue);
1586 // no EM_START in scope, so must interpret the TT_END without any special meaning
1587 _Wikitext_pop_excess_elements(parser);
1588 _Wikitext_start_para_if_necessary(parser);
1589 rb_str_cat(i, escaped_em_end, sizeof(escaped_em_end) - 1);
1595 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1597 _Wikitext_emit_pending_crlf_if_necessary(parser);
1598 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1602 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1604 // already in span started with <tt>, no choice but to emit this literally
1605 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1607 // TT (`) already seen, this is a closing tag
1608 _Wikitext_pop_from_stack_up_to(parser, i, TT, Qtrue);
1611 // this is a new opening
1612 _Wikitext_pop_excess_elements(parser);
1613 _Wikitext_start_para_if_necessary(parser);
1614 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1615 ary_push(parser->scope, TT);
1616 ary_push(parser->line, TT);
1622 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1624 _Wikitext_emit_pending_crlf_if_necessary(parser);
1625 rb_str_cat(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1629 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1630 if (IN(TT_START) || IN(TT))
1631 rb_str_cat(i, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1634 _Wikitext_pop_excess_elements(parser);
1635 _Wikitext_start_para_if_necessary(parser);
1636 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1637 ary_push(parser->scope, TT_START);
1638 ary_push(parser->line, TT_START);
1644 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1646 _Wikitext_emit_pending_crlf_if_necessary(parser);
1647 rb_str_cat(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1651 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1653 _Wikitext_pop_from_stack_up_to(parser, i, TT_START, Qtrue);
1656 // no TT_START in scope, so must interpret the TT_END without any special meaning
1657 _Wikitext_pop_excess_elements(parser);
1658 _Wikitext_start_para_if_necessary(parser);
1659 rb_str_cat(i, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1666 if (IN(NO_WIKI_START) || IN(PRE_START))
1668 // no need to check for PRE; can never appear inside it
1669 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1673 // count number of tokens in line and scope stacks
1674 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1675 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1676 j = parser->scope->count - bq_count;
1679 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1683 if (type == OL || type == UL)
1686 if (i - k >= 2) // already seen at least one OL or UL
1688 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1693 ary_push(parser->line, type);
1694 ary_push(parser->line, LI);
1696 // want to compare line with scope but can only do so if scope has enough items on it
1699 if (ary_entry(parser->scope, i + bq_count - 2) == type && ary_entry(parser->scope, i + bq_count - 1) == LI)
1701 // line and scope match at this point: do nothing yet
1705 // item just pushed onto line does not match corresponding slot of scope!
1706 for (; j >= i - 2; j--)
1707 // must pop back before emitting
1708 _Wikitext_pop_from_stack(parser, Qnil);
1710 // will emit UL or OL, then LI
1714 else // line stack size now exceeds scope stack size: must increase nesting level
1715 break; // will emit UL or OL, then LI
1719 // not a OL or UL token!
1721 // must close existing LI and re-open new one
1722 _Wikitext_pop_from_stack(parser, Qnil);
1725 // item just pushed onto line does not match corresponding slot of scope!
1727 // must pop back before emitting
1728 _Wikitext_pop_from_stack(parser, Qnil);
1736 if (type == OL || type == UL)
1738 // if LI is at the top of a stack this is the start of a nested list
1739 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1741 // so we should precede it with a CRLF, and indicate that it's a nested list
1742 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1743 ary_push(parser->scope, NESTED_LIST);
1747 // this is a new list
1748 if (IN(BLOCKQUOTE_START))
1749 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1751 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1755 _Wikitext_indent(parser);
1757 rb_str_cat(parser->output, ol_start, sizeof(ol_start) - 1);
1758 else if (type == UL)
1759 rb_str_cat(parser->output, ul_start, sizeof(ul_start) - 1);
1760 ary_push(parser->scope, type);
1761 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1763 else if (type == SPACE)
1764 // silently throw away the optional SPACE token after final list marker
1767 _Wikitext_indent(parser);
1768 rb_str_cat(parser->output, li_start, sizeof(li_start) - 1);
1769 ary_push(parser->scope, LI);
1771 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1772 if (type == OL || type == UL)
1775 while (k++, NEXT_TOKEN(), (type = token->type))
1777 if (type == OL || type == UL)
1778 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1779 else if (type == SPACE && k == 1)
1781 // silently throw away the optional SPACE token after final list marker
1790 // jump to top of the loop to process token we scanned during lookahead
1799 if (IN(NO_WIKI_START) || IN(PRE_START))
1801 // no need to check for PRE; can never appear inside it
1802 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1806 // pop up to but not including the last BLOCKQUOTE on the scope stack
1807 if (IN(BLOCKQUOTE_START))
1808 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1810 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1812 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1813 ary_push(parser->line, type);
1814 i = ary_count(parser->line, BLOCKQUOTE);
1815 j = ary_count(parser->scope, BLOCKQUOTE);
1817 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1820 // must pop (reduce nesting level)
1821 for (i = j - i; i > 0; i--)
1822 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1825 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1826 while (NEXT_TOKEN(), (token->type == SPACE))
1829 ary_push(parser->scope, type);
1830 _Wikitext_indent(parser);
1832 // take base_heading_level into account
1833 type += base_heading_level;
1834 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1837 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1838 if (type == H6_START)
1839 rb_str_cat(parser->output, h6_start, sizeof(h6_start) - 1);
1840 else if (type == H5_START)
1841 rb_str_cat(parser->output, h5_start, sizeof(h5_start) - 1);
1842 else if (type == H4_START)
1843 rb_str_cat(parser->output, h4_start, sizeof(h4_start) - 1);
1844 else if (type == H3_START)
1845 rb_str_cat(parser->output, h3_start, sizeof(h3_start) - 1);
1846 else if (type == H2_START)
1847 rb_str_cat(parser->output, h2_start, sizeof(h2_start) - 1);
1848 else if (type == H1_START)
1849 rb_str_cat(parser->output, h1_start, sizeof(h1_start) - 1);
1851 // jump to top of the loop to process token we scanned during lookahead
1855 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1857 _Wikitext_emit_pending_crlf_if_necessary(parser);
1858 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1862 _Wikitext_rollback_failed_external_link(parser); // if any
1865 // literal output only if not in h6 scope (we stay silent in that case)
1866 _Wikitext_start_para_if_necessary(parser);
1867 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1873 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1875 _Wikitext_emit_pending_crlf_if_necessary(parser);
1876 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1880 _Wikitext_rollback_failed_external_link(parser); // if any
1883 // literal output only if not in h5 scope (we stay silent in that case)
1884 _Wikitext_start_para_if_necessary(parser);
1885 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1891 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1893 _Wikitext_emit_pending_crlf_if_necessary(parser);
1894 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1898 _Wikitext_rollback_failed_external_link(parser); // if any
1901 // literal output only if not in h4 scope (we stay silent in that case)
1902 _Wikitext_start_para_if_necessary(parser);
1903 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1909 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1911 _Wikitext_emit_pending_crlf_if_necessary(parser);
1912 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1916 _Wikitext_rollback_failed_external_link(parser); // if any
1919 // literal output only if not in h3 scope (we stay silent in that case)
1920 _Wikitext_start_para_if_necessary(parser);
1921 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1927 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1929 _Wikitext_emit_pending_crlf_if_necessary(parser);
1930 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1934 _Wikitext_rollback_failed_external_link(parser); // if any
1937 // literal output only if not in h2 scope (we stay silent in that case)
1938 _Wikitext_start_para_if_necessary(parser);
1939 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1945 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1947 _Wikitext_emit_pending_crlf_if_necessary(parser);
1948 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1952 _Wikitext_rollback_failed_external_link(parser); // if any
1955 // literal output only if not in h1 scope (we stay silent in that case)
1956 _Wikitext_start_para_if_necessary(parser);
1957 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1963 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1965 _Wikitext_emit_pending_crlf_if_necessary(parser);
1966 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1970 // in plain scope, will turn into autolink (with appropriate, user-configurable CSS)
1971 _Wikitext_pop_excess_elements(parser);
1972 _Wikitext_start_para_if_necessary(parser);
1973 _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), TOKEN_TEXT(token), Qnil, mailto_class, Qtrue);
1978 if (IN(NO_WIKI_START))
1979 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1980 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1981 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1982 else if (IN(LINK_START))
1984 // if the URI were allowed it would have been handled already in LINK_START
1985 _Wikitext_rollback_failed_internal_link(parser);
1986 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
1988 else if (IN(EXT_LINK_START))
1990 if (NIL_P(parser->link_target))
1992 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1993 i = TOKEN_TEXT(token);
1995 if (token->type == SPACE)
1997 ary_push(parser->scope, SPACE);
1998 parser->link_target = i;
1999 parser->link_text = rb_str_new2("");
2000 parser->capture = parser->link_text;
2001 token = NULL; // silently consume space
2005 // didn't see the space! this must be an error
2006 _Wikitext_pop_from_stack(parser, Qnil);
2007 _Wikitext_pop_excess_elements(parser);
2008 _Wikitext_start_para_if_necessary(parser);
2009 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2010 _Wikitext_append_hyperlink(parser, Qnil, i, Qnil, parser->external_link_class, Qtrue);
2015 if (NIL_P(parser->link_text))
2016 // this must be the first part of our link text
2017 parser->link_text = TOKEN_TEXT(token);
2019 // add to existing link text
2020 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2025 // in plain scope, will turn into autolink (with appropriate, user-configurable CSS)
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 = Qfalse;
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 = Qtrue;
2491 continue; // jump back to top of loop to handle token grabbed via lookahead
2496 parser->pending_crlf = Qtrue;
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 = Qfalse;
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 = Qfalse;
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 == Qtrue)
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 for (i = 0, j = parser->scope->count; i < j; i++)
2562 _Wikitext_pop_from_stack(parser, Qnil);
2563 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2569 // reset current token; forcing lexer to return another token at the top of the loop
2573 return parser->output;