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)
35 #warning TRUE macro already defined
41 #warning FALSE macro already defined
44 // poor man's object orientation in C:
45 // instead of parsing around multiple parameters between functions in the parser
46 // we pack everything into a struct and pass around only a pointer to that
47 // TODO: consider changing some of the VALUE members (eg link_target) to the more efficient str_t type
50 VALUE output; // for accumulating output to be returned
51 VALUE capture; // for capturing substrings
52 VALUE link_target; // short term "memory" for parsing links
53 VALUE link_text; // short term "memory" for parsing links
54 VALUE external_link_class; // CSS class applied to external links
55 VALUE mailto_class; // CSS class applied to email (mailto) links
56 VALUE img_prefix; // path prepended when emitting img tags
57 ary_t *scope; // stack for tracking scope
58 ary_t *line; // stack for tracking scope as implied by current line
59 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
60 char pending_crlf; // boolean
61 char autolink; // boolean
62 char space_to_underscore; // boolean
64 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
65 int current_indent; // fluctuates according to currently nested structures
66 str_t *tabulation; // caching buffer for emitting indentation
67 int base_heading_level;
70 const char escaped_no_wiki_start[] = "<nowiki>";
71 const char escaped_no_wiki_end[] = "</nowiki>";
72 const char literal_strong_em[] = "'''''";
73 const char literal_strong[] = "'''";
74 const char literal_em[] = "''";
75 const char escaped_em_start[] = "<em>";
76 const char escaped_em_end[] = "</em>";
77 const char escaped_strong_start[] = "<strong>";
78 const char escaped_strong_end[] = "</strong>";
79 const char escaped_tt_start[] = "<tt>";
80 const char escaped_tt_end[] = "</tt>";
81 const char literal_h6[] = "======";
82 const char literal_h5[] = "=====";
83 const char literal_h4[] = "====";
84 const char literal_h3[] = "===";
85 const char literal_h2[] = "==";
86 const char literal_h1[] = "=";
87 const char pre_start[] = "<pre>";
88 const char pre_end[] = "</pre>";
89 const char escaped_pre_start[] = "<pre>";
90 const char escaped_pre_end[] = "</pre>";
91 const char blockquote_start[] = "<blockquote>";
92 const char blockquote_end[] = "</blockquote>";
93 const char escaped_blockquote_start[] = "<blockquote>";
94 const char escaped_blockquote_end[] = "</blockquote>";
95 const char strong_em_start[] = "<strong><em>";
96 const char strong_start[] = "<strong>";
97 const char strong_end[] = "</strong>";
98 const char em_start[] = "<em>";
99 const char em_end[] = "</em>";
100 const char tt_start[] = "<tt>";
101 const char tt_end[] = "</tt>";
102 const char ol_start[] = "<ol>";
103 const char ol_end[] = "</ol>";
104 const char ul_start[] = "<ul>";
105 const char ul_end[] = "</ul>";
106 const char li_start[] = "<li>";
107 const char li_end[] = "</li>";
108 const char h6_start[] = "<h6>";
109 const char h6_end[] = "</h6>";
110 const char h5_start[] = "<h5>";
111 const char h5_end[] = "</h5>";
112 const char h4_start[] = "<h4>";
113 const char h4_end[] = "</h4>";
114 const char h3_start[] = "<h3>";
115 const char h3_end[] = "</h3>";
116 const char h2_start[] = "<h2>";
117 const char h2_end[] = "</h2>";
118 const char h1_start[] = "<h1>";
119 const char h1_end[] = "</h1>";
120 const char p_start[] = "<p>";
121 const char p_end[] = "</p>";
122 const char space[] = " ";
123 const char a_start[] = "<a href=\"";
124 const char a_class[] = "\" class=\"";
125 const char a_start_close[] = "\">";
126 const char a_end[] = "</a>";
127 const char link_start[] = "[[";
128 const char link_end[] = "]]";
129 const char separator[] = "|";
130 const char ext_link_start[] = "[";
131 const char backtick[] = "`";
132 const char quote[] = "\"";
133 const char ampersand[] = "&";
134 const char quot_entity[] = """;
135 const char amp_entity[] = "&";
136 const char lt_entity[] = "<";
137 const char gt_entity[] = ">";
138 const char escaped_blockquote[] = "> ";
139 const char ext_link_end[] = "]";
140 const char literal_img_start[] = "{{";
141 const char img_start[] = "<img src=\"";
142 const char img_end[] = "\" />";
143 const char img_alt[] = "\" alt=\"";
145 // for testing and debugging only
146 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
150 string = StringValue(string);
151 VALUE tokens = rb_ary_new();
152 char *p = RSTRING_PTR(string);
153 long len = RSTRING_LEN(string);
156 next_token(&token, NULL, p, pe);
157 rb_ary_push(tokens, _Wikitext_token(&token));
158 while (token.type != END_OF_FILE)
160 next_token(&token, &token, NULL, pe);
161 rb_ary_push(tokens, _Wikitext_token(&token));
166 // for benchmarking raw tokenization speed only
167 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
171 string = StringValue(string);
172 char *p = RSTRING_PTR(string);
173 long len = RSTRING_LEN(string);
176 next_token(&token, NULL, p, pe);
177 while (token.type != END_OF_FILE)
178 next_token(&token, &token, NULL, pe);
182 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
185 VALUE string, options;
186 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
190 string = StringValue(string);
191 VALUE tokens = rb_ary_new();
193 // check instance variables
194 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
196 // process options hash (can override instance variables)
197 if (!NIL_P(options) && TYPE(options) == T_HASH)
199 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
200 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
202 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
207 char *p = RSTRING_PTR(string);
208 long len = RSTRING_LEN(string);
211 token_t *_token = &token;
212 next_token(&token, NULL, p, pe);
213 while (token.type != END_OF_FILE)
220 if (TOKEN_LEN(_token) >= min_len)
221 rb_ary_push(tokens, TOKEN_TEXT(_token));
224 // ignore everything else
227 next_token(&token, &token, NULL, pe);
232 // we downcase "in place", overwriting the original contents of the buffer and returning the same string
233 VALUE _Wikitext_downcase_bang(VALUE string)
235 char *ptr = RSTRING_PTR(string);
236 long len = RSTRING_LEN(string);
237 for (long i = 0; i < len; i++)
239 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
245 // prepare hyperlink and append it to parser->output
246 // if check_autolink is Qtrue, checks parser->autolink to decide whether to emit a real hyperlink
247 // or merely the literal link target
248 // if link_text is Qnil, the link_target is re-used for the link text
249 void _Wikitext_append_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class, VALUE check_autolink)
251 if (check_autolink == Qtrue && !parser->autolink)
252 rb_str_append(parser->output, link_target);
255 rb_str_cat(parser->output, a_start, sizeof(a_start) - 1); // <a href="
256 if (!NIL_P(link_prefix))
257 rb_str_append(parser->output, link_prefix);
258 rb_str_append(parser->output, link_target);
260 // special handling for mailto URIs
261 const char *mailto = "mailto:";
262 if (NIL_P(link_prefix) &&
263 RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
264 strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
265 link_class = parser->mailto_class; // use mailto_class from parser
266 if (link_class != Qnil)
268 rb_str_cat(parser->output, a_class, sizeof(a_class) - 1); // " class="
269 rb_str_append(parser->output, link_class);
271 rb_str_cat(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
272 if (NIL_P(link_text)) // re-use link_target
273 rb_str_append(parser->output, link_target);
275 rb_str_append(parser->output, link_text);
276 rb_str_cat(parser->output, a_end, sizeof(a_end) - 1); // </a>
280 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
282 rb_str_cat(parser->output, img_start, sizeof(img_start) - 1); // <img src="
283 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
284 rb_str_append(parser->output, parser->img_prefix);
285 rb_str_cat(parser->output, token_ptr, token_len);
286 rb_str_cat(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
287 rb_str_cat(parser->output, token_ptr, token_len);
288 rb_str_cat(parser->output, img_end, sizeof(img_end) - 1); // " />
291 // will emit indentation only if we are about to emit any of:
292 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
293 // each time we enter one of those spans must ++ the indentation level
294 void _Wikitext_indent(parser_t *parser)
296 if (parser->base_indent == -1) // indentation disabled
298 int space_count = parser->current_indent + parser->base_indent;
301 char *old_end, *new_end;
302 if (parser->tabulation->len < space_count)
303 str_grow(parser->tabulation, space_count); // reallocates if necessary
304 old_end = parser->tabulation->ptr + parser->tabulation->len;
305 new_end = parser->tabulation->ptr + space_count;
306 while (old_end < new_end)
308 if (space_count > parser->tabulation->len)
309 parser->tabulation->len = space_count;
310 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
312 parser->current_indent += 2;
315 void _Wikitext_dedent(parser_t *parser, VALUE emit)
317 if (parser->base_indent == -1) // indentation disabled
319 parser->current_indent -= 2;
322 int space_count = parser->current_indent + parser->base_indent;
324 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
327 // Pops a single item off the parser's scope stack.
328 // A corresponding closing tag is written to the target string.
329 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
330 void _Wikitext_pop_from_stack(parser_t *parser, VALUE target)
332 int top = ary_entry(parser->scope, -1);
336 target = parser->output;
338 // for headings, take base_heading_level into account
339 if (top >= H1_START && top <= H6_START)
341 top += parser->base_heading_level;
342 // no need to check for underflow (base_heading_level is never negative)
351 rb_str_cat(target, pre_end, sizeof(pre_end) - 1);
352 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
353 _Wikitext_dedent(parser, Qfalse);
357 case BLOCKQUOTE_START:
358 _Wikitext_dedent(parser, Qtrue);
359 rb_str_cat(target, blockquote_end, sizeof(blockquote_end) - 1);
360 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
364 // not a real HTML tag; so nothing to pop
369 rb_str_cat(target, strong_end, sizeof(strong_end) - 1);
374 rb_str_cat(target, em_end, sizeof(em_end) - 1);
379 rb_str_cat(target, tt_end, sizeof(tt_end) - 1);
383 _Wikitext_dedent(parser, Qtrue);
384 rb_str_cat(target, ol_end, sizeof(ol_end) - 1);
385 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
389 _Wikitext_dedent(parser, Qtrue);
390 rb_str_cat(target, ul_end, sizeof(ul_end) - 1);
391 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
395 // next token to pop will be a LI
396 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
397 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
398 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
399 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
400 _Wikitext_dedent(parser, Qtrue); // we really only want to emit the spaces
401 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
405 rb_str_cat(target, li_end, sizeof(li_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, h6_end, sizeof(h6_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, h5_end, sizeof(h5_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, h4_end, sizeof(h4_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, h3_end, sizeof(h3_end) - 1);
430 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
431 _Wikitext_dedent(parser, Qfalse);
435 rb_str_cat(target, h2_end, sizeof(h2_end) - 1);
436 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
437 _Wikitext_dedent(parser, Qfalse);
441 rb_str_cat(target, h1_end, sizeof(h1_end) - 1);
442 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
443 _Wikitext_dedent(parser, Qfalse);
447 // not an HTML tag; so nothing to emit
451 // not an HTML tag; so nothing to emit
455 // not an HTML tag; so nothing to emit
459 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
463 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
467 rb_str_cat(target, p_end, sizeof(p_end) - 1);
468 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
469 _Wikitext_dedent(parser, Qfalse);
477 // should probably raise an exception here
480 ary_pop(parser->scope);
483 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
484 // If including is Qtrue then the item itself is also popped.
485 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
486 void _Wikitext_pop_from_stack_up_to(parser_t *parser, VALUE target, int item, VALUE including)
488 int continue_looping = 1;
491 int top = ary_entry(parser->scope, -1);
496 if (including != Qtrue)
498 continue_looping = 0;
500 _Wikitext_pop_from_stack(parser, target);
501 } while (continue_looping);
504 void _Wikitext_pop_all_from_stack(parser_t *parser)
506 for (int i = 0, max = parser->scope->count; i < max; i++)
507 _Wikitext_pop_from_stack(parser, Qnil);
510 void _Wikitext_start_para_if_necessary(parser_t *parser)
512 if (!NIL_P(parser->capture)) // we don't do anything if in capturing mode
515 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
516 if (parser->scope->count == 0 ||
517 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
518 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
520 _Wikitext_indent(parser);
521 rb_str_cat(parser->output, p_start, sizeof(p_start) - 1);
522 ary_push(parser->scope, P);
523 ary_push(parser->line, P);
525 else if (parser->pending_crlf)
528 // already in a paragraph block; convert pending CRLF into a space
529 rb_str_cat(parser->output, space, sizeof(space) - 1);
531 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
532 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
534 parser->pending_crlf = FALSE;
537 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
539 if (parser->pending_crlf)
541 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
542 parser->pending_crlf = FALSE;
546 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
547 // For example, given input like:
552 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
553 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
558 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
559 // but not on the line scope:
564 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
565 // on the line scope.
566 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
567 // entering the for loop.
568 void _Wikitext_pop_excess_elements(parser_t *parser)
570 if (!NIL_P(parser->capture)) // we don't pop anything if in capturing mode
572 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
574 // special case for last item on scope
577 // don't auto-pop P if it is only item on scope
578 if (ary_entry(parser->scope, -1) == P)
580 // add P to the line scope to prevent us entering the loop at all next time around
581 ary_push(parser->line, P);
585 _Wikitext_pop_from_stack(parser, parser->output);
589 #define INVALID_ENCODING(msg) do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
591 // convert a single UTF-8 codepoint to UTF-32
592 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
593 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
594 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
595 // raises a RangeError if the supplied character is invalid UTF-8
596 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
597 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
600 if ((unsigned char)src[0] <= 0x7f) // ASCII
605 else if ((src[0] & 0xe0) == 0xc0) // byte starts with 110..... : this should be a two-byte sequence
608 INVALID_ENCODING("truncated byte sequence"); // no second byte
609 else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
610 INVALID_ENCODING("overlong encoding"); // overlong encoding: lead byte of 110..... but code point <= 127
611 else if ((src[1] & 0xc0) != 0x80 )
612 INVALID_ENCODING("malformed byte sequence"); // should have second byte starting with 10......
613 dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
616 else if ((src[0] & 0xf0) == 0xe0) // byte starts with 1110.... : this should be a three-byte sequence
619 INVALID_ENCODING("truncated byte sequence"); // missing second or third byte
620 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
621 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
622 dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
625 else if ((src[0] & 0xf8) == 0xf0) // bytes starts with 11110... : this should be a four-byte sequence
628 INVALID_ENCODING("truncated byte sequence"); // missing second, third, or fourth byte
629 else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
630 INVALID_ENCODING("overlong encoding"); // disallowed by RFC 3629 (codepoints above 0x10ffff)
631 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
632 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
633 dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
636 else // invalid input
637 INVALID_ENCODING("unexpected byte");
641 VALUE _Wikitext_utf32_char_to_entity(uint32_t character)
643 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
644 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
645 char scratch = (character & 0xf000) >> 12;
646 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
647 scratch = (character & 0x0f00) >> 8;
648 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
649 scratch = (character & 0x00f0) >> 4;
650 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
651 scratch = character & 0x000f;
652 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
653 return rb_str_new((const char *)hex_string, sizeof(hex_string));
656 VALUE _Wikitext_parser_trim_link_target(VALUE string)
658 string = StringValue(string);
659 char *src = RSTRING_PTR(string);
660 char *start = src; // remember this so we can check if we're at the start
662 char *non_space = src; // remember last non-space character output
663 long len = RSTRING_LEN(string);
664 char *end = src + len;
676 if (left == start && non_space + 1 == end)
679 return rb_str_new(left, (non_space + 1) - left);
682 // - non-printable (non-ASCII) characters converted to numeric entities
683 // - QUOT and AMP characters converted to named entities
684 // - if rollback is Qtrue, there is no special treatment of spaces
685 // - if rollback is Qfalse, leading and trailing whitespace trimmed
686 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, VALUE rollback)
688 VALUE string = StringValue(parser->link_target); // raises if string is nil or doesn't quack like a string
689 char *src = RSTRING_PTR(string);
690 char *start = src; // remember this so we can check if we're at the start
691 long len = RSTRING_LEN(string);
692 char *end = src + len;
694 // start with a destination buffer twice the size of the source, will realloc if necessary
695 // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
696 // this efficiently handles the most common case (where the size of the buffer doesn't change much)
697 char *dest = ALLOC_N(char, len * 2);
698 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
699 char *non_space = dest; // remember last non-space character output
702 // need at most 8 characters (8 bytes) to display each character
703 if (dest + 8 > dest_ptr + len) // outgrowing buffer, must reallocate
705 char *old_dest = dest;
706 char *old_dest_ptr = dest_ptr;
707 len = len + (end - src) * 8; // allocate enough for worst case
708 dest = realloc(dest_ptr, len); // will never have to realloc more than once
711 // would have used reallocf, but this has to run on Linux too, not just Darwin
713 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
716 dest = dest_ptr + (old_dest - old_dest_ptr);
717 non_space = dest_ptr + (non_space - old_dest_ptr);
720 if (*src == '"') // QUOT
722 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
723 memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
724 dest += sizeof(quot_entity_literal);
726 else if (*src == '&') // AMP
728 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
729 memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
730 dest += sizeof(amp_entity_literal);
732 else if (*src == '<') // LESS_THAN
735 rb_raise(rb_eRangeError, "invalid link text (\"<\" may not appear in link text)");
737 else if (*src == '>') // GREATER_THAN
740 rb_raise(rb_eRangeError, "invalid link text (\">\" may not appear in link text)");
742 else if (*src == ' ' && src == start && rollback == Qfalse)
743 start++; // we eat leading space
744 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
749 else // all others: must convert to entities
752 VALUE entity = _Wikitext_utf32_char_to_entity(_Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
753 char *entity_src = RSTRING_PTR(entity);
754 long entity_len = RSTRING_LEN(entity); // should always be 8 characters (8 bytes)
755 memcpy(dest, entity_src, entity_len);
766 // trim trailing space if necessary
767 if (rollback == Qfalse && non_space > dest_ptr && dest != non_space)
768 len = non_space - dest_ptr;
770 len = dest - dest_ptr;
771 VALUE out = rb_str_new(dest_ptr, len);
776 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
779 parser.link_target = string;
780 return _Wikitext_parser_sanitize_link_target(&parser, Qfalse);
783 // encodes the input string according to RFCs 2396 and 2718
784 // leading and trailing whitespace trimmed
785 // note that the first character of the target link is not case-sensitive
786 // (this is a recommended application-level constraint; it is not imposed at this level)
787 // this is to allow links like:
788 // ...the [[foo]] is...
789 // to be equivalent to:
790 // thing. [[Foo]] was...
791 static void _Wikitext_parser_encode_link_target(parser_t *parser)
793 VALUE in = StringValue(parser->link_target);
794 char *input = RSTRING_PTR(in);
795 char *start = input; // remember this so we can check if we're at the start
796 long len = RSTRING_LEN(in);
799 char *end = input + len;
800 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
802 // to avoid most reallocations start with a destination buffer twice the size of the source
803 // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
804 // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
805 // the worst case is where _every_ byte must be written out using 3 bytes
806 long dest_len = len * 2;
807 char *dest = ALLOC_N(char, dest_len);
808 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
809 char *non_space = dest; // remember last non-space character output
810 for (; input < end; input++)
812 if ((dest + 3) > (dest_ptr + dest_len)) // worst case: a single character may grow to 3 characters once encoded
814 // outgrowing buffer, must reallocate
815 char *old_dest = dest;
816 char *old_dest_ptr = dest_ptr;
818 dest = realloc(dest_ptr, dest_len);
821 // would have used reallocf, but this has to run on Linux too, not just Darwin
823 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
826 dest = dest_ptr + (old_dest - old_dest_ptr);
827 non_space = dest_ptr + (non_space - old_dest_ptr);
830 // pass through unreserved characters
831 if (((*input >= 'a') && (*input <= 'z')) ||
832 ((*input >= 'A') && (*input <= 'Z')) ||
833 ((*input >= '0') && (*input <= '9')) ||
842 else if (*input == ' ' && input == start)
843 start++; // we eat leading space
844 else if (*input == ' ' && parser->space_to_underscore)
846 else // everything else gets URL-encoded
849 *dest++ = hex[(unsigned char)(*input) / 16]; // left
850 *dest++ = hex[(unsigned char)(*input) % 16]; // right
856 // trim trailing space if necessary
857 if (non_space > dest_ptr && dest != non_space)
858 dest_len = non_space - dest_ptr;
860 dest_len = dest - dest_ptr;
861 parser->link_target = rb_str_new(dest_ptr, dest_len);
865 VALUE Wikitext_parser_encode_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 // this method exposed for testing only
875 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
878 parser.link_target = in;
879 parser.space_to_underscore = FALSE;
880 _Wikitext_parser_encode_link_target(&parser);
881 return parser.link_target;
884 // returns 1 (TRUE) if supplied string is blank (nil, empty, or all whitespace)
885 // returns 0 (FALSE) otherwise
886 int _Wikitext_blank(VALUE str)
888 if (NIL_P(str) || RSTRING_LEN(str) == 0)
890 for (char *ptr = RSTRING_PTR(str),
891 *end = RSTRING_PTR(str) + RSTRING_LEN(str);
900 void _Wikitext_rollback_failed_internal_link(parser_t *parser)
903 return; // nothing to do!
904 int scope_includes_separator = IN(SEPARATOR);
905 _Wikitext_pop_from_stack_up_to(parser, Qnil, LINK_START, Qtrue);
906 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
907 if (!NIL_P(parser->link_target))
909 VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, Qtrue);
910 rb_str_append(parser->output, sanitized);
911 if (scope_includes_separator)
913 rb_str_cat(parser->output, separator, sizeof(separator) - 1);
914 if (!NIL_P(parser->link_text))
915 rb_str_append(parser->output, parser->link_text);
918 parser->capture = Qnil;
919 parser->link_target = Qnil;
920 parser->link_text = Qnil;
923 void _Wikitext_rollback_failed_external_link(parser_t *parser)
925 if (!IN(EXT_LINK_START))
926 return; // nothing to do!
928 // store a couple of values before popping
929 int scope_includes_space = IN(SPACE);
930 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
931 _Wikitext_pop_from_stack_up_to(parser, Qnil, EXT_LINK_START, Qtrue);
933 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
934 if (!NIL_P(parser->link_target))
936 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, Qnil, link_class, Qtrue);
937 if (scope_includes_space)
939 rb_str_cat(parser->output, space, sizeof(space) - 1);
940 if (!NIL_P(parser->link_text))
941 rb_str_append(parser->output, parser->link_text);
944 parser->capture = Qnil;
945 parser->link_target = Qnil;
946 parser->link_text = Qnil;
949 void _Wikitext_rollback_failed_link(parser_t *parser)
951 _Wikitext_rollback_failed_internal_link(parser);
952 _Wikitext_rollback_failed_external_link(parser);
955 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
959 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
963 VALUE autolink = Qtrue;
964 VALUE line_ending = rb_str_new2("\n");
965 VALUE external_link_class = rb_str_new2("external");
966 VALUE mailto_class = rb_str_new2("mailto");
967 VALUE internal_link_prefix = rb_str_new2("/wiki/");
968 VALUE img_prefix = rb_str_new2("/images/");
969 VALUE space_to_underscore = Qtrue;
970 VALUE minimum_fulltext_token_length = INT2NUM(3);
971 VALUE base_heading_level = INT2NUM(0);
973 // process options hash (override defaults)
974 if (!NIL_P(options) && TYPE(options) == T_HASH)
976 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
977 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
978 autolink = OVERRIDE_IF_SET(autolink);
979 line_ending = OVERRIDE_IF_SET(line_ending);
980 external_link_class = OVERRIDE_IF_SET(external_link_class);
981 mailto_class = OVERRIDE_IF_SET(mailto_class);
982 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
983 img_prefix = OVERRIDE_IF_SET(img_prefix);
984 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
985 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
986 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
989 // no need to call super here; rb_call_super()
990 rb_iv_set(self, "@autolink", autolink);
991 rb_iv_set(self, "@line_ending", line_ending);
992 rb_iv_set(self, "@external_link_class", external_link_class);
993 rb_iv_set(self, "@mailto_class", mailto_class);
994 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
995 rb_iv_set(self, "@img_prefix", img_prefix);
996 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
997 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
998 rb_iv_set(self, "@base_heading_level", base_heading_level);
1002 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1004 for (int i = 0; i < 100000; i++)
1005 Wikitext_parser_parse(1, &string, self);
1009 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1011 // process arguments
1012 VALUE string, options;
1013 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1017 string = StringValue(string);
1019 // process options hash
1020 int base_indent = 0;
1021 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1022 if (!NIL_P(options) && TYPE(options) == T_HASH)
1024 // :indent => 0 (or more)
1025 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1027 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1028 if (indent == Qfalse)
1029 base_indent = -1; // indentation disabled
1032 base_indent = NUM2INT(indent);
1033 if (base_indent < 0)
1038 // :base_heading_level => 0/1/2/3/4/5/6
1039 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1040 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1043 // normalize, regardless of whether this came from instance variable or override
1044 if (base_heading_level < 0)
1045 base_heading_level = 0;
1046 if (base_heading_level > 6)
1047 base_heading_level = 6;
1050 char *p = RSTRING_PTR(string);
1051 long len = RSTRING_LEN(string);
1054 // access these once per parse
1055 VALUE line_ending = rb_iv_get(self, "@line_ending");
1056 line_ending = StringValue(line_ending);
1057 VALUE link_class = rb_iv_get(self, "@external_link_class");
1058 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1059 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1060 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1061 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1063 // set up parser struct to make passing parameters a little easier
1064 // eventually this will encapsulate most or all of the variables above
1066 parser_t *parser = &_parser;
1067 parser->output = rb_str_new2("");
1068 parser->capture = Qnil;
1069 parser->link_target = Qnil;
1070 parser->link_text = Qnil;
1071 parser->external_link_class = link_class;
1072 parser->mailto_class = mailto_class;
1073 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1074 parser->scope = ary_new();
1075 GC_WRAP_ARY(parser->scope, scope_gc);
1076 parser->line = ary_new();
1077 GC_WRAP_ARY(parser->line, line_gc);
1078 parser->line_buffer = ary_new();
1079 GC_WRAP_ARY(parser->line_buffer, line_buffer_gc);
1080 parser->pending_crlf = FALSE;
1081 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? TRUE : FALSE;
1082 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? TRUE : FALSE;
1083 parser->line_ending = str_new_from_string(line_ending);
1084 GC_WRAP_STR(parser->line_ending, line_ending_gc);
1085 parser->base_indent = base_indent;
1086 parser->current_indent = 0;
1087 parser->tabulation = str_new();
1088 GC_WRAP_STR(parser->tabulation, tabulation_gc);
1089 parser->base_heading_level = base_heading_level;
1091 // this simple looping design leads to a single enormous function,
1092 // but it's faster than doing actual recursive descent and also secure in the face of
1093 // malicious input that seeks to overflow the stack
1094 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1095 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1096 // than a straightforward looping translator like this one anyway
1098 _token.type = NO_TOKEN;
1099 token_t *token = NULL;
1102 // note that whenever we grab a token we push it into the line buffer
1103 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1104 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1106 // check to see if we have a token hanging around from a previous iteration of this loop
1109 if (_token.type == NO_TOKEN)
1111 // first time here (haven't started scanning yet)
1113 next_token(token, NULL, p, pe);
1114 ary_push(parser->line_buffer, token->type);
1120 int type = token->type;
1122 // can't declare new variables inside a switch statement, so predeclare them here
1123 long remove_strong = -1;
1124 long remove_em = -1;
1126 // general purpose counters and flags
1131 // The following giant switch statement contains cases for all the possible token types.
1132 // In the most basic sense we are emitting the HTML that corresponds to each token,
1133 // but some tokens require context information in order to decide what to output.
1134 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1135 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1137 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1138 // - the line buffer (records tokens seen so far on the current line)
1139 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1141 // Although this is fairly complicated, there is one key simplifying factor:
1142 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1143 // scope stack (up to the current token) is valid; our translator can take this as a given.
1144 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1145 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1149 if (IN(NO_WIKI_START) || IN(PRE_START))
1151 rb_str_cat(parser->output, space, sizeof(space) - 1);
1154 else if (IN(BLOCKQUOTE_START))
1156 // this kind of nesting not allowed (to avoid user confusion)
1157 _Wikitext_pop_excess_elements(parser);
1158 _Wikitext_start_para_if_necessary(parser);
1159 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1160 rb_str_cat(i, space, sizeof(space) - 1);
1164 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1165 ary_push(parser->line, PRE);
1166 i = ary_count(parser->line, BLOCKQUOTE);
1167 j = ary_count(parser->scope, BLOCKQUOTE);
1170 // must pop (reduce nesting level)
1171 for (i = j - i; i > 0; i--)
1172 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1177 parser->pending_crlf = FALSE;
1178 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1179 _Wikitext_indent(parser);
1180 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1181 ary_push(parser->scope, PRE);
1186 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1188 _Wikitext_emit_pending_crlf_if_necessary(parser);
1189 rb_str_cat(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1191 else if (IN(BLOCKQUOTE_START))
1193 _Wikitext_rollback_failed_link(parser); // if any
1194 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1195 _Wikitext_indent(parser);
1196 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1197 ary_push(parser->scope, PRE_START);
1198 ary_push(parser->line, PRE_START);
1200 else if (IN(BLOCKQUOTE))
1202 if (token->column_start == 1) // only allowed in first column
1204 _Wikitext_rollback_failed_link(parser); // if any
1205 _Wikitext_pop_all_from_stack(parser);
1206 _Wikitext_indent(parser);
1207 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1208 ary_push(parser->scope, PRE_START);
1209 ary_push(parser->line, PRE_START);
1211 else // PRE_START illegal here
1213 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1214 _Wikitext_pop_excess_elements(parser);
1215 _Wikitext_start_para_if_necessary(parser);
1216 rb_str_cat(i, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1221 _Wikitext_rollback_failed_link(parser); // if any
1222 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1223 _Wikitext_indent(parser);
1224 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1225 ary_push(parser->scope, PRE_START);
1226 ary_push(parser->line, PRE_START);
1231 if (IN(NO_WIKI_START) || IN(PRE))
1233 _Wikitext_emit_pending_crlf_if_necessary(parser);
1234 rb_str_cat(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1239 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, Qtrue);
1242 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1243 _Wikitext_pop_excess_elements(parser);
1244 _Wikitext_start_para_if_necessary(parser);
1245 rb_str_cat(i, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1251 if (IN(NO_WIKI_START) || IN(PRE_START))
1252 // no need to check for <pre>; can never appear inside it
1253 rb_str_cat(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1254 else if (IN(BLOCKQUOTE_START))
1256 // this kind of nesting not allowed (to avoid user confusion)
1257 _Wikitext_pop_excess_elements(parser);
1258 _Wikitext_start_para_if_necessary(parser);
1259 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1260 rb_str_cat(i, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1265 ary_push(parser->line, BLOCKQUOTE);
1267 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1268 i = ary_count(parser->line, BLOCKQUOTE);
1269 j = ary_count(parser->scope, BLOCKQUOTE);
1271 // 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
1272 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1274 ary_push(parser->line, BLOCKQUOTE);
1278 // now decide whether to push, pop or do nothing
1281 // must push (increase nesting level)
1282 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1283 for (i = i - j; i > 0; i--)
1285 _Wikitext_indent(parser);
1286 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1287 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1288 ary_push(parser->scope, BLOCKQUOTE);
1293 // must pop (reduce nesting level)
1294 for (i = j - i; i > 0; i--)
1295 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1298 // jump to top of the loop to process token we scanned during lookahead
1303 case BLOCKQUOTE_START:
1304 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1306 _Wikitext_emit_pending_crlf_if_necessary(parser);
1307 rb_str_cat(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1309 else if (IN(BLOCKQUOTE_START))
1311 // nesting is fine here
1312 _Wikitext_rollback_failed_link(parser); // if any
1313 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
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 if (IN(BLOCKQUOTE))
1322 if (token->column_start == 1) // only allowed in first column
1324 _Wikitext_rollback_failed_link(parser); // if any
1325 _Wikitext_pop_all_from_stack(parser);
1326 _Wikitext_indent(parser);
1327 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1328 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1329 ary_push(parser->scope, BLOCKQUOTE_START);
1330 ary_push(parser->line, BLOCKQUOTE_START);
1332 else // BLOCKQUOTE_START illegal here
1334 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1335 _Wikitext_pop_excess_elements(parser);
1336 _Wikitext_start_para_if_necessary(parser);
1337 rb_str_cat(i, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1342 // would be nice to eliminate the repetition here but it's probably the clearest way
1343 _Wikitext_rollback_failed_link(parser); // if any
1344 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1345 _Wikitext_indent(parser);
1346 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1347 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1348 ary_push(parser->scope, BLOCKQUOTE_START);
1349 ary_push(parser->line, BLOCKQUOTE_START);
1353 case BLOCKQUOTE_END:
1354 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1356 _Wikitext_emit_pending_crlf_if_necessary(parser);
1357 rb_str_cat(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1361 if (IN(BLOCKQUOTE_START))
1362 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, Qtrue);
1365 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1366 _Wikitext_pop_excess_elements(parser);
1367 _Wikitext_start_para_if_necessary(parser);
1368 rb_str_cat(i, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1374 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1376 _Wikitext_emit_pending_crlf_if_necessary(parser);
1377 rb_str_cat(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1381 _Wikitext_pop_excess_elements(parser);
1382 _Wikitext_start_para_if_necessary(parser);
1383 ary_push(parser->scope, NO_WIKI_START);
1384 ary_push(parser->line, NO_WIKI_START);
1389 if (IN(NO_WIKI_START))
1390 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1391 _Wikitext_pop_from_stack_up_to(parser, Qnil, NO_WIKI_START, Qtrue);
1394 _Wikitext_pop_excess_elements(parser);
1395 _Wikitext_start_para_if_necessary(parser);
1396 rb_str_cat(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1401 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1403 _Wikitext_emit_pending_crlf_if_necessary(parser);
1404 rb_str_cat(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1408 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1409 _Wikitext_pop_excess_elements(parser);
1411 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1412 // otherwise, must open them
1415 j = parser->scope->count;
1416 for (j = j - 1; j >= 0; j--)
1418 int val = ary_entry(parser->scope, j);
1419 if (val == STRONG || val == STRONG_START)
1421 rb_str_cat(i, strong_end, sizeof(strong_end) - 1);
1424 else if (val == EM || val == EM_START)
1426 rb_str_cat(i, em_end, sizeof(em_end) - 1);
1431 if (remove_strong > remove_em) // must remove strong first
1433 ary_pop(parser->scope);
1435 ary_pop(parser->scope);
1436 else // there was no em to remove!, so consider this an opening em tag
1438 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1439 ary_push(parser->scope, EM);
1440 ary_push(parser->line, EM);
1443 else if (remove_em > remove_strong) // must remove em first
1445 ary_pop(parser->scope);
1446 if (remove_strong > -1)
1447 ary_pop(parser->scope);
1448 else // there was no strong to remove!, so consider this an opening strong tag
1450 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1451 ary_push(parser->scope, STRONG);
1452 ary_push(parser->line, STRONG);
1455 else // no strong or em to remove, so this must be a new opening of both
1457 _Wikitext_start_para_if_necessary(parser);
1458 rb_str_cat(i, strong_em_start, sizeof(strong_em_start) - 1);
1459 ary_push(parser->scope, STRONG);
1460 ary_push(parser->line, STRONG);
1461 ary_push(parser->scope, EM);
1462 ary_push(parser->line, EM);
1467 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1469 _Wikitext_emit_pending_crlf_if_necessary(parser);
1470 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1474 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1475 if (IN(STRONG_START))
1476 // already in span started with <strong>, no choice but to emit this literally
1477 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1478 else if (IN(STRONG))
1479 // STRONG already seen, this is a closing tag
1480 _Wikitext_pop_from_stack_up_to(parser, i, STRONG, Qtrue);
1483 // this is a new opening
1484 _Wikitext_pop_excess_elements(parser);
1485 _Wikitext_start_para_if_necessary(parser);
1486 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1487 ary_push(parser->scope, STRONG);
1488 ary_push(parser->line, STRONG);
1494 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1496 _Wikitext_emit_pending_crlf_if_necessary(parser);
1497 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1501 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1502 if (IN(STRONG_START) || IN(STRONG))
1503 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1506 _Wikitext_pop_excess_elements(parser);
1507 _Wikitext_start_para_if_necessary(parser);
1508 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1509 ary_push(parser->scope, STRONG_START);
1510 ary_push(parser->line, STRONG_START);
1516 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1518 _Wikitext_emit_pending_crlf_if_necessary(parser);
1519 rb_str_cat(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1523 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1524 if (IN(STRONG_START))
1525 _Wikitext_pop_from_stack_up_to(parser, i, STRONG_START, Qtrue);
1528 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1529 _Wikitext_pop_excess_elements(parser);
1530 _Wikitext_start_para_if_necessary(parser);
1531 rb_str_cat(i, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1537 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1539 _Wikitext_emit_pending_crlf_if_necessary(parser);
1540 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1544 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1546 // already in span started with <em>, no choice but to emit this literally
1547 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1549 // EM already seen, this is a closing tag
1550 _Wikitext_pop_from_stack_up_to(parser, i, EM, Qtrue);
1553 // this is a new opening
1554 _Wikitext_pop_excess_elements(parser);
1555 _Wikitext_start_para_if_necessary(parser);
1556 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1557 ary_push(parser->scope, EM);
1558 ary_push(parser->line, EM);
1564 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1566 _Wikitext_emit_pending_crlf_if_necessary(parser);
1567 rb_str_cat(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1571 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1572 if (IN(EM_START) || IN(EM))
1573 rb_str_cat(i, escaped_em_start, sizeof(escaped_em_start) - 1);
1576 _Wikitext_pop_excess_elements(parser);
1577 _Wikitext_start_para_if_necessary(parser);
1578 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1579 ary_push(parser->scope, EM_START);
1580 ary_push(parser->line, EM_START);
1586 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1588 _Wikitext_emit_pending_crlf_if_necessary(parser);
1589 rb_str_cat(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1593 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1595 _Wikitext_pop_from_stack_up_to(parser, i, EM_START, Qtrue);
1598 // no EM_START in scope, so must interpret the TT_END without any special meaning
1599 _Wikitext_pop_excess_elements(parser);
1600 _Wikitext_start_para_if_necessary(parser);
1601 rb_str_cat(i, escaped_em_end, sizeof(escaped_em_end) - 1);
1607 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1609 _Wikitext_emit_pending_crlf_if_necessary(parser);
1610 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1614 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1616 // already in span started with <tt>, no choice but to emit this literally
1617 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1619 // TT (`) already seen, this is a closing tag
1620 _Wikitext_pop_from_stack_up_to(parser, i, TT, Qtrue);
1623 // this is a new opening
1624 _Wikitext_pop_excess_elements(parser);
1625 _Wikitext_start_para_if_necessary(parser);
1626 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1627 ary_push(parser->scope, TT);
1628 ary_push(parser->line, TT);
1634 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1636 _Wikitext_emit_pending_crlf_if_necessary(parser);
1637 rb_str_cat(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1641 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1642 if (IN(TT_START) || IN(TT))
1643 rb_str_cat(i, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1646 _Wikitext_pop_excess_elements(parser);
1647 _Wikitext_start_para_if_necessary(parser);
1648 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1649 ary_push(parser->scope, TT_START);
1650 ary_push(parser->line, TT_START);
1656 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1658 _Wikitext_emit_pending_crlf_if_necessary(parser);
1659 rb_str_cat(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1663 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1665 _Wikitext_pop_from_stack_up_to(parser, i, TT_START, Qtrue);
1668 // no TT_START in scope, so must interpret the TT_END without any special meaning
1669 _Wikitext_pop_excess_elements(parser);
1670 _Wikitext_start_para_if_necessary(parser);
1671 rb_str_cat(i, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1678 if (IN(NO_WIKI_START) || IN(PRE_START))
1680 // no need to check for PRE; can never appear inside it
1681 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1685 // count number of tokens in line and scope stacks
1686 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1687 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1688 j = parser->scope->count - bq_count;
1691 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1695 if (type == OL || type == UL)
1698 if (i - k >= 2) // already seen at least one OL or UL
1700 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1705 ary_push(parser->line, type);
1706 ary_push(parser->line, LI);
1708 // want to compare line with scope but can only do so if scope has enough items on it
1711 if (ary_entry(parser->scope, i + bq_count - 2) == type && ary_entry(parser->scope, i + bq_count - 1) == LI)
1713 // line and scope match at this point: do nothing yet
1717 // item just pushed onto line does not match corresponding slot of scope!
1718 for (; j >= i - 2; j--)
1719 // must pop back before emitting
1720 _Wikitext_pop_from_stack(parser, Qnil);
1722 // will emit UL or OL, then LI
1726 else // line stack size now exceeds scope stack size: must increase nesting level
1727 break; // will emit UL or OL, then LI
1731 // not a OL or UL token!
1733 // must close existing LI and re-open new one
1734 _Wikitext_pop_from_stack(parser, Qnil);
1737 // item just pushed onto line does not match corresponding slot of scope!
1739 // must pop back before emitting
1740 _Wikitext_pop_from_stack(parser, Qnil);
1748 if (type == OL || type == UL)
1750 // if LI is at the top of a stack this is the start of a nested list
1751 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1753 // so we should precede it with a CRLF, and indicate that it's a nested list
1754 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1755 ary_push(parser->scope, NESTED_LIST);
1759 // this is a new list
1760 if (IN(BLOCKQUOTE_START))
1761 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1763 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1767 _Wikitext_indent(parser);
1769 rb_str_cat(parser->output, ol_start, sizeof(ol_start) - 1);
1770 else if (type == UL)
1771 rb_str_cat(parser->output, ul_start, sizeof(ul_start) - 1);
1772 ary_push(parser->scope, type);
1773 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1775 else if (type == SPACE)
1776 // silently throw away the optional SPACE token after final list marker
1779 _Wikitext_indent(parser);
1780 rb_str_cat(parser->output, li_start, sizeof(li_start) - 1);
1781 ary_push(parser->scope, LI);
1783 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1784 if (type == OL || type == UL)
1787 while (k++, NEXT_TOKEN(), (type = token->type))
1789 if (type == OL || type == UL)
1790 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1791 else if (type == SPACE && k == 1)
1793 // silently throw away the optional SPACE token after final list marker
1802 // jump to top of the loop to process token we scanned during lookahead
1811 if (IN(NO_WIKI_START) || IN(PRE_START))
1813 // no need to check for PRE; can never appear inside it
1814 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1818 // pop up to but not including the last BLOCKQUOTE on the scope stack
1819 if (IN(BLOCKQUOTE_START))
1820 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1822 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1824 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1825 ary_push(parser->line, type);
1826 i = ary_count(parser->line, BLOCKQUOTE);
1827 j = ary_count(parser->scope, BLOCKQUOTE);
1829 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1832 // must pop (reduce nesting level)
1833 for (i = j - i; i > 0; i--)
1834 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1837 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1838 while (NEXT_TOKEN(), (token->type == SPACE))
1841 ary_push(parser->scope, type);
1842 _Wikitext_indent(parser);
1844 // take base_heading_level into account
1845 type += base_heading_level;
1846 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1849 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1850 if (type == H6_START)
1851 rb_str_cat(parser->output, h6_start, sizeof(h6_start) - 1);
1852 else if (type == H5_START)
1853 rb_str_cat(parser->output, h5_start, sizeof(h5_start) - 1);
1854 else if (type == H4_START)
1855 rb_str_cat(parser->output, h4_start, sizeof(h4_start) - 1);
1856 else if (type == H3_START)
1857 rb_str_cat(parser->output, h3_start, sizeof(h3_start) - 1);
1858 else if (type == H2_START)
1859 rb_str_cat(parser->output, h2_start, sizeof(h2_start) - 1);
1860 else if (type == H1_START)
1861 rb_str_cat(parser->output, h1_start, sizeof(h1_start) - 1);
1863 // jump to top of the loop to process token we scanned during lookahead
1867 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1869 _Wikitext_emit_pending_crlf_if_necessary(parser);
1870 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1874 _Wikitext_rollback_failed_external_link(parser); // if any
1877 // literal output only if not in h6 scope (we stay silent in that case)
1878 _Wikitext_start_para_if_necessary(parser);
1879 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1885 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1887 _Wikitext_emit_pending_crlf_if_necessary(parser);
1888 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1892 _Wikitext_rollback_failed_external_link(parser); // if any
1895 // literal output only if not in h5 scope (we stay silent in that case)
1896 _Wikitext_start_para_if_necessary(parser);
1897 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1903 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1905 _Wikitext_emit_pending_crlf_if_necessary(parser);
1906 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1910 _Wikitext_rollback_failed_external_link(parser); // if any
1913 // literal output only if not in h4 scope (we stay silent in that case)
1914 _Wikitext_start_para_if_necessary(parser);
1915 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1921 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1923 _Wikitext_emit_pending_crlf_if_necessary(parser);
1924 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1928 _Wikitext_rollback_failed_external_link(parser); // if any
1931 // literal output only if not in h3 scope (we stay silent in that case)
1932 _Wikitext_start_para_if_necessary(parser);
1933 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1939 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1941 _Wikitext_emit_pending_crlf_if_necessary(parser);
1942 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1946 _Wikitext_rollback_failed_external_link(parser); // if any
1949 // literal output only if not in h2 scope (we stay silent in that case)
1950 _Wikitext_start_para_if_necessary(parser);
1951 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1957 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1959 _Wikitext_emit_pending_crlf_if_necessary(parser);
1960 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1964 _Wikitext_rollback_failed_external_link(parser); // if any
1967 // literal output only if not in h1 scope (we stay silent in that case)
1968 _Wikitext_start_para_if_necessary(parser);
1969 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1975 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1977 _Wikitext_emit_pending_crlf_if_necessary(parser);
1978 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1982 _Wikitext_pop_excess_elements(parser);
1983 _Wikitext_start_para_if_necessary(parser);
1984 _Wikitext_append_hyperlink(parser, rb_str_new2("mailto:"), TOKEN_TEXT(token), Qnil, mailto_class, Qtrue);
1989 if (IN(NO_WIKI_START))
1990 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1991 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1992 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1993 else if (IN(LINK_START))
1995 // if the URI were allowed it would have been handled already in LINK_START
1996 _Wikitext_rollback_failed_internal_link(parser);
1997 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
1999 else if (IN(EXT_LINK_START))
2001 if (NIL_P(parser->link_target))
2003 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2004 i = TOKEN_TEXT(token);
2006 if (token->type == SPACE)
2008 ary_push(parser->scope, SPACE);
2009 parser->link_target = i;
2010 parser->link_text = rb_str_new2("");
2011 parser->capture = parser->link_text;
2012 token = NULL; // silently consume space
2016 // didn't see the space! this must be an error
2017 _Wikitext_pop_from_stack(parser, Qnil);
2018 _Wikitext_pop_excess_elements(parser);
2019 _Wikitext_start_para_if_necessary(parser);
2020 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2021 _Wikitext_append_hyperlink(parser, Qnil, i, Qnil, parser->external_link_class, Qtrue);
2026 if (NIL_P(parser->link_text))
2027 // this must be the first part of our link text
2028 parser->link_text = TOKEN_TEXT(token);
2030 // add to existing link text
2031 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2036 _Wikitext_pop_excess_elements(parser);
2037 _Wikitext_start_para_if_necessary(parser);
2038 _Wikitext_append_hyperlink(parser, Qnil, TOKEN_TEXT(token), Qnil, parser->external_link_class, Qtrue);
2043 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2044 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2045 else if (IN(EXT_LINK_START))
2047 if (NIL_P(parser->link_target))
2049 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2050 i = TOKEN_TEXT(token);
2052 if (token->type == SPACE)
2054 ary_push(parser->scope, PATH);
2055 ary_push(parser->scope, SPACE);
2056 parser->link_target = i;
2057 parser->link_text = rb_str_new2("");
2058 parser->capture = parser->link_text;
2059 token = NULL; // silently consume space
2063 // didn't see the space! this must be an error
2064 _Wikitext_pop_from_stack(parser, Qnil);
2065 _Wikitext_pop_excess_elements(parser);
2066 _Wikitext_start_para_if_necessary(parser);
2067 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2068 rb_str_append(parser->output, i);
2073 if (NIL_P(parser->link_text))
2074 // this must be the first part of our link text
2075 parser->link_text = TOKEN_TEXT(token);
2077 // add to existing link text
2078 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2083 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2084 _Wikitext_pop_excess_elements(parser);
2085 _Wikitext_start_para_if_necessary(parser);
2086 rb_str_cat(i, token->start, TOKEN_LEN(token));
2090 // internal links (links to other wiki articles) look like this:
2091 // [[another article]] (would point at, for example, "/wiki/another_article")
2092 // [[the other article|the link text we'll use for it]]
2093 // [[the other article | the link text we'll use for it]]
2094 // MediaWiki has strict requirements about what it will accept as a link target:
2095 // all wikitext markup is disallowed:
2096 // example [[foo ''bar'' baz]]
2097 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2098 // example [[foo <em>bar</em> baz]]
2099 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2100 // example [[foo <nowiki>''</nowiki> baz]]
2101 // renders [[foo '' baz]] (ie. not a link)
2102 // example [[foo <bar> baz]]
2103 // renders [[foo <bar> baz]] (ie. not a link)
2104 // HTML entities and non-ASCII, however, make it through:
2105 // example [[foo €]]
2106 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2107 // example [[foo €]]
2108 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2109 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2110 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2111 // everything else will be rejected
2113 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2114 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2116 _Wikitext_emit_pending_crlf_if_necessary(parser);
2117 rb_str_cat(i, link_start, sizeof(link_start) - 1);
2119 else if (IN(EXT_LINK_START))
2120 // already in external link scope! (and in fact, must be capturing link_text right now)
2121 rb_str_cat(i, link_start, sizeof(link_start) - 1);
2122 else if (IN(LINK_START))
2124 // already in internal link scope! this is a syntax error
2125 _Wikitext_rollback_failed_internal_link(parser);
2126 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
2128 else if (IN(SEPARATOR))
2130 // scanning internal link text
2132 else // not in internal link scope yet
2134 // will either emit a link, or the rollback of a failed link, so start the para now
2135 _Wikitext_pop_excess_elements(parser);
2136 _Wikitext_start_para_if_necessary(parser);
2137 ary_push(parser->scope, LINK_START);
2139 // look ahead and try to gobble up link target
2140 while (NEXT_TOKEN(), (type = token->type))
2142 if (type == SPACE ||
2143 type == SPECIAL_URI_CHARS ||
2145 type == PRINTABLE ||
2149 type == QUOT_ENTITY ||
2151 type == AMP_ENTITY ||
2152 type == IMG_START ||
2154 type == LEFT_CURLY ||
2155 type == RIGHT_CURLY)
2157 // accumulate these tokens into link_target
2158 if (NIL_P(parser->link_target))
2160 parser->link_target = rb_str_new2("");
2161 parser->capture = parser->link_target;
2163 if (type == QUOT_ENTITY)
2164 // don't insert the entity, insert the literal quote
2165 rb_str_cat(parser->link_target, quote, sizeof(quote) - 1);
2166 else if (type == AMP_ENTITY)
2167 // don't insert the entity, insert the literal ampersand
2168 rb_str_cat(parser->link_target, ampersand, sizeof(ampersand) - 1);
2170 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2172 else if (type == LINK_END)
2174 if (NIL_P(parser->link_target)) // bail for inputs like "[[]]"
2175 _Wikitext_rollback_failed_internal_link(parser);
2176 break; // jump back to top of loop (will handle this in LINK_END case below)
2178 else if (type == SEPARATOR)
2180 if (NIL_P(parser->link_target)) // bail for inputs like "[[|"
2181 _Wikitext_rollback_failed_internal_link(parser);
2184 ary_push(parser->scope, SEPARATOR);
2185 parser->link_text = rb_str_new2("");
2186 parser->capture = parser->link_text;
2191 else // unexpected token (syntax error)
2193 _Wikitext_rollback_failed_internal_link(parser);
2194 break; // jump back to top of loop to handle unexpected token
2198 // jump to top of the loop to process token we scanned during lookahead (if any)
2204 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2205 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2207 _Wikitext_emit_pending_crlf_if_necessary(parser);
2208 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2210 else if (IN(EXT_LINK_START))
2211 // already in external link scope! (and in fact, must be capturing link_text right now)
2212 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2213 else if (IN(LINK_START)) // in internal link scope!
2215 if (_Wikitext_blank(parser->link_target))
2217 // special case for inputs like "[[ ]]"
2218 _Wikitext_rollback_failed_internal_link(parser);
2219 rb_str_cat(parser->output, link_end, sizeof(link_end) - 1);
2222 if (NIL_P(parser->link_text) ||
2223 RSTRING_LEN(parser->link_text) == 0 ||
2224 _Wikitext_blank(parser->link_text))
2225 // use link target as link text
2226 parser->link_text = _Wikitext_parser_sanitize_link_target(parser, Qfalse);
2228 parser->link_text = _Wikitext_parser_trim_link_target(parser->link_text);
2229 _Wikitext_parser_encode_link_target(parser);
2230 _Wikitext_pop_from_stack_up_to(parser, i, LINK_START, Qtrue);
2231 parser->capture = Qnil;
2232 _Wikitext_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, Qfalse);
2233 parser->link_target = Qnil;
2234 parser->link_text = Qnil;
2236 else // wasn't in internal link scope
2238 _Wikitext_pop_excess_elements(parser);
2239 _Wikitext_start_para_if_necessary(parser);
2240 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2244 // external links look like this:
2245 // [http://google.com/ the link text]
2246 // [/other/page/on/site see this page]
2247 // strings in square brackets which don't match this syntax get passed through literally; eg:
2248 // he was very angery [sic] about the turn of events
2249 case EXT_LINK_START:
2250 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2251 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2253 _Wikitext_emit_pending_crlf_if_necessary(parser);
2254 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2256 else if (IN(EXT_LINK_START))
2257 // already in external link scope! (and in fact, must be capturing link_text right now)
2258 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2259 else if (IN(LINK_START))
2261 // already in internal link scope!
2262 i = rb_str_new(ext_link_start, sizeof(ext_link_start) - 1);
2263 if (NIL_P(parser->link_target))
2264 // this must be the first character of our link target
2265 parser->link_target = i;
2268 // link target has already been scanned
2269 if (NIL_P(parser->link_text))
2270 // this must be the first character of our link text
2271 parser->link_text = i;
2273 // add to existing link text
2274 rb_str_append(parser->link_text, i);
2277 // add to existing link target
2278 rb_str_append(parser->link_target, i);
2280 else // not in external link scope yet
2282 // will either emit a link, or the rollback of a failed link, so start the para now
2283 _Wikitext_pop_excess_elements(parser);
2284 _Wikitext_start_para_if_necessary(parser);
2286 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2288 if (token->type == URI || token->type == PATH)
2289 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2291 // only get here if there was a syntax error (missing URI)
2292 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2293 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2298 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2299 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2301 _Wikitext_emit_pending_crlf_if_necessary(parser);
2302 rb_str_cat(i, ext_link_end, sizeof(ext_link_end) - 1);
2304 else if (IN(EXT_LINK_START))
2306 if (NIL_P(parser->link_text))
2307 // syntax error: external link with no link text
2308 _Wikitext_rollback_failed_external_link(parser);
2312 j = IN(PATH) ? Qnil : parser->external_link_class;
2313 _Wikitext_pop_from_stack_up_to(parser, i, EXT_LINK_START, Qtrue);
2314 parser->capture = Qnil;
2315 _Wikitext_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, Qfalse);
2317 parser->link_target = Qnil;
2318 parser->link_text = Qnil;
2322 _Wikitext_pop_excess_elements(parser);
2323 _Wikitext_start_para_if_necessary(parser);
2324 rb_str_cat(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2329 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2330 _Wikitext_pop_excess_elements(parser);
2331 _Wikitext_start_para_if_necessary(parser);
2332 rb_str_cat(i, separator, sizeof(separator) - 1);
2336 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2337 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2339 _Wikitext_emit_pending_crlf_if_necessary(parser);
2340 rb_str_cat(i, token->start, TOKEN_LEN(token));
2344 // peek ahead to see next token
2345 char *token_ptr = token->start;
2346 int token_len = TOKEN_LEN(token);
2349 if (((type == H6_END) && IN(H6_START)) ||
2350 ((type == H5_END) && IN(H5_START)) ||
2351 ((type == H4_END) && IN(H4_START)) ||
2352 ((type == H3_END) && IN(H3_START)) ||
2353 ((type == H2_END) && IN(H2_START)) ||
2354 ((type == H1_END) && IN(H1_START)))
2356 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2361 _Wikitext_pop_excess_elements(parser);
2362 _Wikitext_start_para_if_necessary(parser);
2363 rb_str_cat(i, token_ptr, token_len);
2366 // jump to top of the loop to process token we scanned during lookahead
2374 case DECIMAL_ENTITY:
2375 // pass these through unaltered as they are case sensitive
2376 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2377 _Wikitext_pop_excess_elements(parser);
2378 _Wikitext_start_para_if_necessary(parser);
2379 rb_str_cat(i, token->start, TOKEN_LEN(token));
2383 // normalize hex entities (downcase them)
2384 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2385 _Wikitext_pop_excess_elements(parser);
2386 _Wikitext_start_para_if_necessary(parser);
2387 rb_str_append(i, _Wikitext_downcase_bang(TOKEN_TEXT(token)));
2391 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2392 _Wikitext_pop_excess_elements(parser);
2393 _Wikitext_start_para_if_necessary(parser);
2394 rb_str_cat(i, quot_entity, sizeof(quot_entity) - 1);
2398 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2399 _Wikitext_pop_excess_elements(parser);
2400 _Wikitext_start_para_if_necessary(parser);
2401 rb_str_cat(i, amp_entity, sizeof(amp_entity) - 1);
2405 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2406 _Wikitext_pop_excess_elements(parser);
2407 _Wikitext_start_para_if_necessary(parser);
2408 rb_str_cat(i, lt_entity, sizeof(lt_entity) - 1);
2412 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2413 _Wikitext_pop_excess_elements(parser);
2414 _Wikitext_start_para_if_necessary(parser);
2415 rb_str_cat(i, gt_entity, sizeof(gt_entity) - 1);
2419 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2421 _Wikitext_emit_pending_crlf_if_necessary(parser);
2422 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2424 else if (!NIL_P(parser->capture))
2425 rb_str_cat(parser->capture, token->start, TOKEN_LEN(token));
2428 // not currently capturing: will be emitting something on success or failure, so get ready
2429 _Wikitext_pop_excess_elements(parser);
2430 _Wikitext_start_para_if_necessary(parser);
2432 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2433 // will cheat here and abuse the link_target capture buffer to accumulate text
2434 if (NIL_P(parser->link_target))
2435 parser->link_target = rb_str_new2("");
2436 while (NEXT_TOKEN(), (type = token->type))
2438 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2439 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2440 else if (type == IMG_END && RSTRING_LEN(parser->link_target) > 0)
2443 _Wikitext_append_img(parser, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2447 else // unexpected token or zero-length target (syntax error)
2450 rb_str_cat(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2451 rb_str_cat(parser->output, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2456 // jump to top of the loop to process token we scanned during lookahead
2457 parser->link_target = Qnil;
2463 i = parser->pending_crlf;
2464 parser->pending_crlf = FALSE;
2465 _Wikitext_rollback_failed_link(parser); // if any
2466 if (IN(NO_WIKI_START) || IN(PRE_START))
2468 ary_clear(parser->line_buffer);
2469 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2474 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2475 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2476 // don't emit in this case
2477 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2480 if (ary_entry(parser->line_buffer, -2) == PRE)
2482 // only thing on line is the PRE: emit pending line ending (if we had one)
2484 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2487 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2488 ary_clear(parser->line);
2489 ary_clear(parser->line_buffer);
2491 // peek ahead to see if this is definitely the end of the PRE block
2494 if (type != BLOCKQUOTE && type != PRE)
2495 // this is definitely the end of the block, so don't emit
2496 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2498 // potentially will emit
2499 parser->pending_crlf = TRUE;
2501 continue; // jump back to top of loop to handle token grabbed via lookahead
2506 parser->pending_crlf = TRUE;
2508 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2509 // as a side effect, this handles any open span-level elements and unclosed blocks
2510 // (with special handling for P blocks and LI elements)
2511 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2512 for (j = parser->scope->count; j > i; j--)
2514 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2516 parser->pending_crlf = FALSE;
2520 // special handling on last iteration through the loop if the top item on the scope is a P block
2521 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2523 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2524 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2525 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2526 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2527 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2529 parser->pending_crlf = FALSE;
2531 // not a paragraph break!
2534 _Wikitext_pop_from_stack(parser, Qnil);
2538 // delete the entire contents of the line scope stack and buffer
2539 ary_clear(parser->line);
2540 ary_clear(parser->line_buffer);
2543 case SPECIAL_URI_CHARS:
2549 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2550 _Wikitext_pop_excess_elements(parser);
2551 _Wikitext_start_para_if_necessary(parser);
2552 rb_str_cat(i, token->start, TOKEN_LEN(token));
2556 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2557 _Wikitext_pop_excess_elements(parser);
2558 _Wikitext_start_para_if_necessary(parser);
2559 rb_str_append(i, _Wikitext_utf32_char_to_entity(token->code_point)); // convert to entity
2563 // special case for input like " foo\n " (see pre_spec.rb)
2565 ary_entry(parser->line_buffer, -2) == PRE &&
2566 parser->pending_crlf)
2567 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2569 // close any open scopes on hitting EOF
2570 _Wikitext_rollback_failed_link(parser); // if any
2571 _Wikitext_pop_all_from_stack(parser);
2572 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2578 // reset current token; forcing lexer to return another token at the top of the loop
2582 return parser->output;