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(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 VALUE _Wikitext_hyperlink(parser_t *parser, VALUE link_prefix, VALUE link_target, VALUE link_text, VALUE link_class)
235 VALUE string = rb_str_new(a_start, sizeof(a_start) - 1); // <a href="
236 if (!NIL_P(link_prefix))
237 rb_str_append(string, link_prefix);
238 rb_str_append(string, link_target);
240 /* special handling for mailto URIs */
241 const char *mailto = "mailto:";
242 if (NIL_P(link_prefix) &&
243 RSTRING_LEN(link_target) >= (long)sizeof(mailto) &&
244 strncmp(mailto, RSTRING_PTR(link_target), sizeof(mailto)) == 0)
245 link_class = parser->mailto_class; // use mailto_class from parser
247 if (link_class != Qnil)
249 rb_str_cat(string, a_class, sizeof(a_class) - 1); // " class="
250 rb_str_append(string, link_class);
252 rb_str_cat(string, a_start_close, sizeof(a_start_close) - 1); // ">
253 rb_str_append(string, link_text);
254 rb_str_cat(string, a_end, sizeof(a_end) - 1);
258 void _Wikitext_append_img(parser_t *parser, char *token_ptr, int token_len)
260 rb_str_cat(parser->output, img_start, sizeof(img_start) - 1); // <img src="
261 if (!NIL_P(parser->img_prefix))
262 rb_str_append(parser->output, parser->img_prefix);
263 rb_str_cat(parser->output, token_ptr, token_len);
264 rb_str_cat(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
265 rb_str_cat(parser->output, token_ptr, token_len);
266 rb_str_cat(parser->output, img_end, sizeof(img_end) - 1); // " />
269 // will emit indentation only if we are about to emit any of:
270 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
271 // each time we enter one of those spans must ++ the indentation level
272 void _Wikitext_indent(parser_t *parser)
274 int space_count = parser->current_indent + parser->base_indent;
277 char *old_end, *new_end;
278 if (parser->tabulation->len < space_count)
279 str_grow(parser->tabulation, space_count); // reallocates if necessary
280 old_end = parser->tabulation->ptr + parser->tabulation->len;
281 new_end = parser->tabulation->ptr + space_count;
282 while (old_end < new_end)
284 if (space_count > parser->tabulation->len)
285 parser->tabulation->len = space_count;
286 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
288 parser->current_indent += 2;
291 void _Wikitext_dedent(parser_t *parser, VALUE emit)
293 parser->current_indent -= 2;
296 int space_count = parser->current_indent + parser->base_indent;
298 rb_str_cat(parser->output, parser->tabulation->ptr, space_count);
301 // Pops a single item off the parser's scope stack.
302 // A corresponding closing tag is written to the target string.
303 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
304 void _Wikitext_pop_from_stack(parser_t *parser, VALUE target)
306 int top = ary_entry(parser->scope, -1);
310 target = parser->output;
312 // for headings, take base_heading_level into account
313 if (top >= H1_START && top <= H6_START)
315 top += parser->base_heading_level;
316 // no need to check for underflow (base_heading_level is never negative)
325 rb_str_cat(target, pre_end, sizeof(pre_end) - 1);
326 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
327 _Wikitext_dedent(parser, Qfalse);
331 case BLOCKQUOTE_START:
332 _Wikitext_dedent(parser, Qtrue);
333 rb_str_cat(target, blockquote_end, sizeof(blockquote_end) - 1);
334 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
338 // not a real HTML tag; so nothing to pop
343 rb_str_cat(target, strong_end, sizeof(strong_end) - 1);
348 rb_str_cat(target, em_end, sizeof(em_end) - 1);
353 rb_str_cat(target, tt_end, sizeof(tt_end) - 1);
357 _Wikitext_dedent(parser, Qtrue);
358 rb_str_cat(target, ol_end, sizeof(ol_end) - 1);
359 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
363 _Wikitext_dedent(parser, Qtrue);
364 rb_str_cat(target, ul_end, sizeof(ul_end) - 1);
365 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
369 // next token to pop will be a LI
370 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
371 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
372 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
373 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
374 _Wikitext_dedent(parser, Qtrue); // we really only want to emit the spaces
375 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
379 rb_str_cat(target, li_end, sizeof(li_end) - 1);
380 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
381 _Wikitext_dedent(parser, Qfalse);
385 rb_str_cat(target, h6_end, sizeof(h6_end) - 1);
386 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
387 _Wikitext_dedent(parser, Qfalse);
391 rb_str_cat(target, h5_end, sizeof(h5_end) - 1);
392 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
393 _Wikitext_dedent(parser, Qfalse);
397 rb_str_cat(target, h4_end, sizeof(h4_end) - 1);
398 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
399 _Wikitext_dedent(parser, Qfalse);
403 rb_str_cat(target, h3_end, sizeof(h3_end) - 1);
404 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
405 _Wikitext_dedent(parser, Qfalse);
409 rb_str_cat(target, h2_end, sizeof(h2_end) - 1);
410 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
411 _Wikitext_dedent(parser, Qfalse);
415 rb_str_cat(target, h1_end, sizeof(h1_end) - 1);
416 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
417 _Wikitext_dedent(parser, Qfalse);
421 // not an HTML tag; so nothing to emit
425 // not an HTML tag; so nothing to emit
429 // not an HTML tag; so nothing to emit
433 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
437 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
441 rb_str_cat(target, p_end, sizeof(p_end) - 1);
442 rb_str_cat(target, parser->line_ending->ptr, parser->line_ending->len);
443 _Wikitext_dedent(parser, Qfalse);
451 // should probably raise an exception here
454 ary_pop(parser->scope);
457 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
458 // If including is Qtrue then the item itself is also popped.
459 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
460 void _Wikitext_pop_from_stack_up_to(parser_t *parser, VALUE target, int item, VALUE including)
462 int continue_looping = 1;
465 int top = ary_entry(parser->scope, -1);
470 if (including != Qtrue)
472 continue_looping = 0;
474 _Wikitext_pop_from_stack(parser, target);
475 } while (continue_looping);
478 void _Wikitext_pop_all_from_stack(parser_t *parser, VALUE target)
480 while (!NO_ITEM(ary_entry(parser->scope, -1)))
481 _Wikitext_pop_from_stack(parser, target);
484 void _Wikitext_start_para_if_necessary(parser_t *parser)
486 if (!NIL_P(parser->capture)) // we don't do anything if in capturing mode
489 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
490 if (parser->scope->count == 0 ||
491 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
492 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
494 _Wikitext_indent(parser);
495 rb_str_cat(parser->output, p_start, sizeof(p_start) - 1);
496 ary_push(parser->scope, P);
497 ary_push(parser->line, P);
499 else if (parser->pending_crlf == Qtrue)
502 // already in a paragraph block; convert pending CRLF into a space
503 rb_str_cat(parser->output, space, sizeof(space) - 1);
505 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
506 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
508 parser->pending_crlf = Qfalse;
511 void _Wikitext_emit_pending_crlf_if_necessary(parser_t *parser)
513 if (parser->pending_crlf == Qtrue)
515 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
516 parser->pending_crlf = Qfalse;
520 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
521 // For example, given input like:
526 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
527 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
532 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
533 // but not on the line scope:
538 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
539 // on the line scope.
540 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
541 // entering the for loop.
542 void _Wikitext_pop_excess_elements(parser_t *parser)
544 if (!NIL_P(parser->capture)) // we don't pop anything if in capturing mode
546 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
548 // special case for last item on scope
551 // don't auto-pop P if it is only item on scope
552 if (ary_entry(parser->scope, -1) == P)
554 // add P to the line scope to prevent us entering the loop at all next time around
555 ary_push(parser->line, P);
559 _Wikitext_pop_from_stack(parser, parser->output);
563 #define INVALID_ENCODING(msg) do { if (dest_ptr) free(dest_ptr); rb_raise(eWikitextParserError, "invalid encoding: " msg); } while(0)
565 // convert a single UTF-8 codepoint to UTF-32
566 // expects an input buffer, src, containing a UTF-8 encoded character (which may be multi-byte)
567 // the end of the input buffer, end, is also passed in to allow the detection of invalidly truncated codepoints
568 // the number of bytes in the UTF-8 character (between 1 and 4) is returned by reference in width_out
569 // raises a RangeError if the supplied character is invalid UTF-8
570 // (in which case it also frees the block of memory indicated by dest_ptr if it is non-NULL)
571 uint32_t _Wikitext_utf8_to_utf32(char *src, char *end, long *width_out, void *dest_ptr)
574 if ((unsigned char)src[0] <= 0x7f) // ASCII
579 else if ((src[0] & 0xe0) == 0xc0) // byte starts with 110..... : this should be a two-byte sequence
582 INVALID_ENCODING("truncated byte sequence"); // no second byte
583 else if (((unsigned char)src[0] == 0xc0) || ((unsigned char)src[0] == 0xc1))
584 INVALID_ENCODING("overlong encoding"); // overlong encoding: lead byte of 110..... but code point <= 127
585 else if ((src[1] & 0xc0) != 0x80 )
586 INVALID_ENCODING("malformed byte sequence"); // should have second byte starting with 10......
587 dest = ((uint32_t)(src[0] & 0x1f)) << 6 | (src[1] & 0x3f);
590 else if ((src[0] & 0xf0) == 0xe0) // byte starts with 1110.... : this should be a three-byte sequence
593 INVALID_ENCODING("truncated byte sequence"); // missing second or third byte
594 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ))
595 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
596 dest = ((uint32_t)(src[0] & 0x0f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
599 else if ((src[0] & 0xf8) == 0xf0) // bytes starts with 11110... : this should be a four-byte sequence
602 INVALID_ENCODING("truncated byte sequence"); // missing second, third, or fourth byte
603 else if ((unsigned char)src[0] >= 0xf5 && (unsigned char)src[0] <= 0xf7)
604 INVALID_ENCODING("overlong encoding"); // disallowed by RFC 3629 (codepoints above 0x10ffff)
605 else if (((src[1] & 0xc0) != 0x80 ) || ((src[2] & 0xc0) != 0x80 ) || ((src[3] & 0xc0) != 0x80 ))
606 INVALID_ENCODING("malformed byte sequence"); // should have second and third bytes starting with 10......
607 dest = ((uint32_t)(src[0] & 0x07)) << 18 | ((uint32_t)(src[1] & 0x3f)) << 12 | ((uint32_t)(src[1] & 0x3f)) << 6 | (src[2] & 0x3f);
610 else // invalid input
611 INVALID_ENCODING("unexpected byte");
615 VALUE _Wikitext_utf32_char_to_entity(uint32_t character)
617 // TODO: consider special casing some entities (ie. quot, amp, lt, gt etc)?
618 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
619 char scratch = (character & 0xf000) >> 12;
620 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
621 scratch = (character & 0x0f00) >> 8;
622 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
623 scratch = (character & 0x00f0) >> 4;
624 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
625 scratch = character & 0x000f;
626 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
627 return rb_str_new((const char *)hex_string, sizeof(hex_string));
630 VALUE _Wikitext_parser_trim_link_target(VALUE string)
632 string = StringValue(string);
633 char *src = RSTRING_PTR(string);
634 char *start = src; // remember this so we can check if we're at the start
636 char *non_space = src; // remember last non-space character output
637 long len = RSTRING_LEN(string);
638 char *end = src + len;
650 if (left == start && non_space + 1 == end)
653 return rb_str_new(left, (non_space + 1) - left);
656 // - non-printable (non-ASCII) characters converted to numeric entities
657 // - QUOT and AMP characters converted to named entities
658 // - if rollback is Qtrue, there is no special treatment of spaces
659 // - if rollback is Qfalse, leading and trailing whitespace trimmed
660 VALUE _Wikitext_parser_sanitize_link_target(parser_t *parser, VALUE rollback)
662 VALUE string = StringValue(parser->link_target); // raises if string is nil or doesn't quack like a string
663 char *src = RSTRING_PTR(string);
664 char *start = src; // remember this so we can check if we're at the start
665 long len = RSTRING_LEN(string);
666 char *end = src + len;
668 // start with a destination buffer twice the size of the source, will realloc if necessary
669 // slop = (len / 8) * 8 (ie. one in every 8 characters can be converted into an entity, each entity requires 8 bytes)
670 // this efficiently handles the most common case (where the size of the buffer doesn't change much)
671 char *dest = ALLOC_N(char, len * 2);
672 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
673 char *non_space = dest; // remember last non-space character output
676 // need at most 8 characters (8 bytes) to display each character
677 if (dest + 8 > dest_ptr + len) // outgrowing buffer, must reallocate
679 char *old_dest = dest;
680 char *old_dest_ptr = dest_ptr;
681 len = len + (end - src) * 8; // allocate enough for worst case
682 dest = realloc(dest_ptr, len); // will never have to realloc more than once
685 // would have used reallocf, but this has to run on Linux too, not just Darwin
687 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
690 dest = dest_ptr + (old_dest - old_dest_ptr);
691 non_space = dest_ptr + (non_space - old_dest_ptr);
694 if (*src == '"') // QUOT
696 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
697 memcpy(dest, quot_entity_literal, sizeof(quot_entity_literal));
698 dest += sizeof(quot_entity_literal);
700 else if (*src == '&') // AMP
702 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
703 memcpy(dest, amp_entity_literal, sizeof(amp_entity_literal));
704 dest += sizeof(amp_entity_literal);
706 else if (*src == '<') // LESS_THAN
709 rb_raise(rb_eRangeError, "invalid link text (\"<\" may not appear in link text)");
711 else if (*src == '>') // GREATER_THAN
714 rb_raise(rb_eRangeError, "invalid link text (\">\" may not appear in link text)");
716 else if (*src == ' ' && src == start && rollback == Qfalse)
717 start++; // we eat leading space
718 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
723 else // all others: must convert to entities
726 VALUE entity = _Wikitext_utf32_char_to_entity(_Wikitext_utf8_to_utf32(src, end, &width, dest_ptr));
727 char *entity_src = RSTRING_PTR(entity);
728 long entity_len = RSTRING_LEN(entity); // should always be 8 characters (8 bytes)
729 memcpy(dest, entity_src, entity_len);
740 // trim trailing space if necessary
741 if (rollback == Qfalse && non_space > dest_ptr && dest != non_space)
742 len = non_space - dest_ptr;
744 len = dest - dest_ptr;
745 VALUE out = rb_str_new(dest_ptr, len);
750 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
753 parser.link_target = string;
754 return _Wikitext_parser_sanitize_link_target(&parser, Qfalse);
757 // encodes the input string according to RFCs 2396 and 2718
758 // leading and trailing whitespace trimmed
759 // note that the first character of the target link is not case-sensitive
760 // (this is a recommended application-level constraint; it is not imposed at this level)
761 // this is to allow links like:
762 // ...the [[foo]] is...
763 // to be equivalent to:
764 // thing. [[Foo]] was...
765 static void _Wikitext_parser_encode_link_target(parser_t *parser)
767 VALUE in = StringValue(parser->link_target);
768 char *input = RSTRING_PTR(in);
769 char *start = input; // remember this so we can check if we're at the start
770 long len = RSTRING_LEN(in);
773 char *end = input + len;
774 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
776 // to avoid most reallocations start with a destination buffer twice the size of the source
777 // this handles the most common case (where most chars are in the ASCII range and don't require more storage, but there are
778 // often quite a few spaces, which are encoded as "%20" and occupy 3 bytes)
779 // the worst case is where _every_ byte must be written out using 3 bytes
780 long dest_len = len * 2;
781 char *dest = ALLOC_N(char, dest_len);
782 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
783 char *non_space = dest; // remember last non-space character output
784 for (; input < end; input++)
786 if ((dest + 3) > (dest_ptr + dest_len)) // worst case: a single character may grow to 3 characters once encoded
788 // outgrowing buffer, must reallocate
789 char *old_dest = dest;
790 char *old_dest_ptr = dest_ptr;
792 dest = realloc(dest_ptr, dest_len);
795 // would have used reallocf, but this has to run on Linux too, not just Darwin
797 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
800 dest = dest_ptr + (old_dest - old_dest_ptr);
801 non_space = dest_ptr + (non_space - old_dest_ptr);
804 // pass through unreserved characters
805 if (((*input >= 'a') && (*input <= 'z')) ||
806 ((*input >= 'A') && (*input <= 'Z')) ||
807 ((*input >= '0') && (*input <= '9')) ||
816 else if (*input == ' ' && input == start)
817 start++; // we eat leading space
818 else if (*input == ' ' && parser->space_to_underscore == Qtrue)
820 else // everything else gets URL-encoded
823 *dest++ = hex[(unsigned char)(*input) / 16]; // left
824 *dest++ = hex[(unsigned char)(*input) % 16]; // right
830 // trim trailing space if necessary
831 if (non_space > dest_ptr && dest != non_space)
832 dest_len = non_space - dest_ptr;
834 dest_len = dest - dest_ptr;
835 parser->link_target = rb_str_new(dest_ptr, dest_len);
839 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
842 parser.link_target = in;
843 parser.space_to_underscore = Qfalse;
844 _Wikitext_parser_encode_link_target(&parser);
845 return parser.link_target;
848 // this method exposed for testing only
849 VALUE Wikitext_parser_encode_special_link_target(VALUE self, VALUE in)
852 parser.link_target = in;
853 parser.space_to_underscore = Qfalse;
854 _Wikitext_parser_encode_link_target(&parser);
855 return parser.link_target;
858 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
859 // returns 0 (false) otherwise
860 int _Wikitext_blank(VALUE str)
862 if (NIL_P(str) || RSTRING_LEN(str) == 0)
864 for (char *ptr = RSTRING_PTR(str),
865 *end = RSTRING_PTR(str) + RSTRING_LEN(str);
874 void _Wikitext_rollback_failed_link(parser_t *parser)
877 return; // nothing to do!
878 int scope_includes_separator = IN(SEPARATOR);
879 _Wikitext_pop_from_stack_up_to(parser, Qnil, LINK_START, Qtrue);
880 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
881 if (!NIL_P(parser->link_target))
883 VALUE sanitized = _Wikitext_parser_sanitize_link_target(parser, Qtrue);
884 rb_str_append(parser->output, sanitized);
885 if (scope_includes_separator)
887 rb_str_cat(parser->output, separator, sizeof(separator) - 1);
888 if (!NIL_P(parser->link_text))
889 rb_str_append(parser->output, parser->link_text);
892 parser->capture = Qnil;
893 parser->link_target = Qnil;
894 parser->link_text = Qnil;
897 void _Wikitext_rollback_failed_external_link(parser_t *parser)
899 if (!IN(EXT_LINK_START))
900 return; // nothing to do!
901 int scope_includes_space = IN(SPACE);
902 _Wikitext_pop_from_stack_up_to(parser, Qnil, EXT_LINK_START, Qtrue);
903 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
904 if (!NIL_P(parser->link_target))
906 if (parser->autolink == Qtrue)
907 parser->link_target = _Wikitext_hyperlink(parser, Qnil, parser->link_target, parser->link_target, parser->external_link_class);
908 rb_str_append(parser->output, parser->link_target);
909 if (scope_includes_space)
911 rb_str_cat(parser->output, space, sizeof(space) - 1);
912 if (!NIL_P(parser->link_text))
913 rb_str_append(parser->output, parser->link_text);
916 parser->capture = Qnil;
917 parser->link_target = Qnil;
918 parser->link_text = Qnil;
921 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
925 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
929 VALUE autolink = Qtrue;
930 VALUE line_ending = rb_str_new2("\n");
931 VALUE external_link_class = rb_str_new2("external");
932 VALUE mailto_class = rb_str_new2("mailto");
933 VALUE internal_link_prefix = rb_str_new2("/wiki/");
934 VALUE img_prefix = rb_str_new2("/images/");
935 VALUE space_to_underscore = Qtrue;
936 VALUE minimum_fulltext_token_length = INT2NUM(3);
937 VALUE base_heading_level = INT2NUM(0);
939 // process options hash (override defaults)
940 if (!NIL_P(options) && TYPE(options) == T_HASH)
942 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
943 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
944 autolink = OVERRIDE_IF_SET(autolink);
945 line_ending = OVERRIDE_IF_SET(line_ending);
946 external_link_class = OVERRIDE_IF_SET(external_link_class);
947 mailto_class = OVERRIDE_IF_SET(mailto_class);
948 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
949 img_prefix = OVERRIDE_IF_SET(img_prefix);
950 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
951 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
952 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
955 // no need to call super here; rb_call_super()
956 rb_iv_set(self, "@autolink", autolink);
957 rb_iv_set(self, "@line_ending", line_ending);
958 rb_iv_set(self, "@external_link_class", external_link_class);
959 rb_iv_set(self, "@mailto_class", mailto_class);
960 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
961 rb_iv_set(self, "@img_prefix", img_prefix);
962 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
963 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
964 rb_iv_set(self, "@base_heading_level", base_heading_level);
968 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
970 for (int i = 0; i < 100000; i++)
971 Wikitext_parser_parse(1, &string, self);
975 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
978 VALUE string, options;
979 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
983 string = StringValue(string);
985 // process options hash
987 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
988 if (!NIL_P(options) && TYPE(options) == T_HASH)
990 // :indent => 0 (or more)
991 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
993 base_indent = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("indent"))));
998 // :base_heading_level => 0/1/2/3/4/5/6
999 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1000 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1003 // normalize, regardless of whether this came from instance variable or override
1004 if (base_heading_level < 0)
1005 base_heading_level = 0;
1006 if (base_heading_level > 6)
1007 base_heading_level = 6;
1010 char *p = RSTRING_PTR(string);
1011 long len = RSTRING_LEN(string);
1014 // access these once per parse
1015 VALUE line_ending = rb_iv_get(self, "@line_ending");
1016 line_ending = StringValue(line_ending);
1017 VALUE link_class = rb_iv_get(self, "@external_link_class");
1018 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1019 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1020 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1021 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1023 // set up parser struct to make passing parameters a little easier
1024 // eventually this will encapsulate most or all of the variables above
1026 parser_t *parser = &_parser;
1027 parser->output = rb_str_new2("");
1028 parser->capture = Qnil;
1029 parser->link_target = Qnil;
1030 parser->link_text = Qnil;
1031 parser->external_link_class = link_class;
1032 parser->mailto_class = mailto_class;
1033 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1034 parser->scope = ary_new();
1035 GC_WRAP_ARY(parser->scope, scope_gc);
1036 parser->line = ary_new();
1037 GC_WRAP_ARY(parser->line, line_gc);
1038 parser->line_buffer = ary_new();
1039 GC_WRAP_ARY(parser->line_buffer, line_buffer_gc);
1040 parser->pending_crlf = Qfalse;
1041 parser->autolink = rb_iv_get(self, "@autolink");
1042 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore");
1043 parser->line_ending = str_new_from_string(line_ending);
1044 GC_WRAP_STR(parser->line_ending, line_ending_gc);
1045 parser->base_indent = base_indent;
1046 parser->current_indent = 0;
1047 parser->tabulation = str_new();
1048 GC_WRAP_STR(parser->tabulation, tabulation_gc);
1049 parser->base_heading_level = base_heading_level;
1051 // this simple looping design leads to a single enormous function,
1052 // but it's faster than doing actual recursive descent and also secure in the face of
1053 // malicious input that seeks to overflow the stack
1054 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1055 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1056 // than a straightforward looping translator like this one anyway
1058 _token.type = NO_TOKEN;
1059 token_t *token = NULL;
1062 // note that whenever we grab a token we push it into the line buffer
1063 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1064 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1066 // check to see if we have a token hanging around from a previous iteration of this loop
1069 if (_token.type == NO_TOKEN)
1071 // first time here (haven't started scanning yet)
1073 next_token(token, NULL, p, pe);
1074 ary_push(parser->line_buffer, token->type);
1080 int type = token->type;
1082 // can't declare new variables inside a switch statement, so predeclare them here
1083 long remove_strong = -1;
1084 long remove_em = -1;
1086 // general purpose counters and flags
1091 // The following giant switch statement contains cases for all the possible token types.
1092 // In the most basic sense we are emitting the HTML that corresponds to each token,
1093 // but some tokens require context information in order to decide what to output.
1094 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1095 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1097 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1098 // - the line buffer (records tokens seen so far on the current line)
1099 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1101 // Although this is fairly complicated, there is one key simplifying factor:
1102 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1103 // scope stack (up to the current token) is valid; our translator can take this as a given.
1104 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1105 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1109 if (IN(NO_WIKI_START) || IN(PRE_START))
1111 rb_str_cat(parser->output, space, sizeof(space) - 1);
1114 else if (IN(BLOCKQUOTE_START))
1116 // this kind of nesting not allowed (to avoid user confusion)
1117 _Wikitext_pop_excess_elements(parser);
1118 _Wikitext_start_para_if_necessary(parser);
1119 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1120 rb_str_cat(i, space, sizeof(space) - 1);
1124 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1125 ary_push(parser->line, PRE);
1126 i = ary_count(parser->line, BLOCKQUOTE);
1127 j = ary_count(parser->scope, BLOCKQUOTE);
1130 // must pop (reduce nesting level)
1131 for (i = j - i; i > 0; i--)
1132 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1137 parser->pending_crlf = Qfalse;
1138 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1139 _Wikitext_indent(parser);
1140 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1141 ary_push(parser->scope, PRE);
1146 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1148 _Wikitext_emit_pending_crlf_if_necessary(parser);
1149 rb_str_cat(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1151 else if (IN(BLOCKQUOTE_START))
1153 _Wikitext_rollback_failed_link(parser); // if any
1154 _Wikitext_rollback_failed_external_link(parser); // if any
1155 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1156 _Wikitext_indent(parser);
1157 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1158 ary_push(parser->scope, PRE_START);
1159 ary_push(parser->line, PRE_START);
1161 else if (IN(BLOCKQUOTE))
1163 if (token->column_start == 1) // only allowed in first column
1165 _Wikitext_rollback_failed_link(parser); // if any
1166 _Wikitext_rollback_failed_external_link(parser); // if any
1167 _Wikitext_pop_all_from_stack(parser, Qnil);
1168 _Wikitext_indent(parser);
1169 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1170 ary_push(parser->scope, PRE_START);
1171 ary_push(parser->line, PRE_START);
1173 else // PRE_START illegal here
1175 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1176 _Wikitext_pop_excess_elements(parser);
1177 _Wikitext_start_para_if_necessary(parser);
1178 rb_str_cat(i, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1183 _Wikitext_rollback_failed_link(parser); // if any
1184 _Wikitext_rollback_failed_external_link(parser); // if any
1185 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1186 _Wikitext_indent(parser);
1187 rb_str_cat(parser->output, pre_start, sizeof(pre_start) - 1);
1188 ary_push(parser->scope, PRE_START);
1189 ary_push(parser->line, PRE_START);
1194 if (IN(NO_WIKI_START) || IN(PRE))
1196 _Wikitext_emit_pending_crlf_if_necessary(parser);
1197 rb_str_cat(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1202 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE_START, Qtrue);
1205 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1206 _Wikitext_pop_excess_elements(parser);
1207 _Wikitext_start_para_if_necessary(parser);
1208 rb_str_cat(i, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1214 if (IN(NO_WIKI_START) || IN(PRE_START))
1215 // no need to check for <pre>; can never appear inside it
1216 rb_str_cat(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1217 else if (IN(BLOCKQUOTE_START))
1219 // this kind of nesting not allowed (to avoid user confusion)
1220 _Wikitext_pop_excess_elements(parser);
1221 _Wikitext_start_para_if_necessary(parser);
1222 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1223 rb_str_cat(i, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1228 ary_push(parser->line, BLOCKQUOTE);
1230 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1231 i = ary_count(parser->line, BLOCKQUOTE);
1232 j = ary_count(parser->scope, BLOCKQUOTE);
1234 // 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
1235 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1237 ary_push(parser->line, BLOCKQUOTE);
1241 // now decide whether to push, pop or do nothing
1244 // must push (increase nesting level)
1245 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1246 for (i = i - j; i > 0; i--)
1248 _Wikitext_indent(parser);
1249 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1250 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1251 ary_push(parser->scope, BLOCKQUOTE);
1256 // must pop (reduce nesting level)
1257 for (i = j - i; i > 0; i--)
1258 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1261 // jump to top of the loop to process token we scanned during lookahead
1266 case BLOCKQUOTE_START:
1267 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1269 _Wikitext_emit_pending_crlf_if_necessary(parser);
1270 rb_str_cat(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1272 else if (IN(BLOCKQUOTE_START))
1274 // nesting is fine here
1275 _Wikitext_rollback_failed_link(parser); // if any
1276 _Wikitext_rollback_failed_external_link(parser); // if any
1277 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1278 _Wikitext_indent(parser);
1279 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1280 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1281 ary_push(parser->scope, BLOCKQUOTE_START);
1282 ary_push(parser->line, BLOCKQUOTE_START);
1284 else if (IN(BLOCKQUOTE))
1286 if (token->column_start == 1) // only allowed in first column
1288 _Wikitext_rollback_failed_link(parser); // if any
1289 _Wikitext_rollback_failed_external_link(parser); // if any
1290 _Wikitext_pop_all_from_stack(parser, Qnil);
1291 _Wikitext_indent(parser);
1292 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1293 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1294 ary_push(parser->scope, BLOCKQUOTE_START);
1295 ary_push(parser->line, BLOCKQUOTE_START);
1297 else // BLOCKQUOTE_START illegal here
1299 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1300 _Wikitext_pop_excess_elements(parser);
1301 _Wikitext_start_para_if_necessary(parser);
1302 rb_str_cat(i, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1307 // would be nice to eliminate the repetition here but it's probably the clearest way
1308 _Wikitext_rollback_failed_link(parser); // if any
1309 _Wikitext_rollback_failed_external_link(parser); // if any
1310 _Wikitext_pop_from_stack_up_to(parser, Qnil, P, Qtrue);
1311 _Wikitext_indent(parser);
1312 rb_str_cat(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1313 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1314 ary_push(parser->scope, BLOCKQUOTE_START);
1315 ary_push(parser->line, BLOCKQUOTE_START);
1319 case BLOCKQUOTE_END:
1320 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1322 _Wikitext_emit_pending_crlf_if_necessary(parser);
1323 rb_str_cat(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1327 if (IN(BLOCKQUOTE_START))
1328 _Wikitext_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, Qtrue);
1331 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1332 _Wikitext_pop_excess_elements(parser);
1333 _Wikitext_start_para_if_necessary(parser);
1334 rb_str_cat(i, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1340 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1342 _Wikitext_emit_pending_crlf_if_necessary(parser);
1343 rb_str_cat(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1347 _Wikitext_pop_excess_elements(parser);
1348 _Wikitext_start_para_if_necessary(parser);
1349 ary_push(parser->scope, NO_WIKI_START);
1350 ary_push(parser->line, NO_WIKI_START);
1355 if (IN(NO_WIKI_START))
1356 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1357 _Wikitext_pop_from_stack_up_to(parser, Qnil, NO_WIKI_START, Qtrue);
1360 _Wikitext_pop_excess_elements(parser);
1361 _Wikitext_start_para_if_necessary(parser);
1362 rb_str_cat(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1367 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1369 _Wikitext_emit_pending_crlf_if_necessary(parser);
1370 rb_str_cat(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1374 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1375 _Wikitext_pop_excess_elements(parser);
1377 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1378 // otherwise, must open them
1381 j = parser->scope->count;
1382 for (j = j - 1; j >= 0; j--)
1384 int val = ary_entry(parser->scope, j);
1385 if (val == STRONG || val == STRONG_START)
1387 rb_str_cat(i, strong_end, sizeof(strong_end) - 1);
1390 else if (val == EM || val == EM_START)
1392 rb_str_cat(i, em_end, sizeof(em_end) - 1);
1397 if (remove_strong > remove_em) // must remove strong first
1399 ary_pop(parser->scope);
1401 ary_pop(parser->scope);
1402 else // there was no em to remove!, so consider this an opening em tag
1404 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1405 ary_push(parser->scope, EM);
1406 ary_push(parser->line, EM);
1409 else if (remove_em > remove_strong) // must remove em first
1411 ary_pop(parser->scope);
1412 if (remove_strong > -1)
1413 ary_pop(parser->scope);
1414 else // there was no strong to remove!, so consider this an opening strong tag
1416 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1417 ary_push(parser->scope, STRONG);
1418 ary_push(parser->line, STRONG);
1421 else // no strong or em to remove, so this must be a new opening of both
1423 _Wikitext_start_para_if_necessary(parser);
1424 rb_str_cat(i, strong_em_start, sizeof(strong_em_start) - 1);
1425 ary_push(parser->scope, STRONG);
1426 ary_push(parser->line, STRONG);
1427 ary_push(parser->scope, EM);
1428 ary_push(parser->line, EM);
1433 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1435 _Wikitext_emit_pending_crlf_if_necessary(parser);
1436 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1440 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1441 if (IN(STRONG_START))
1442 // already in span started with <strong>, no choice but to emit this literally
1443 rb_str_cat(parser->output, literal_strong, sizeof(literal_strong) - 1);
1444 else if (IN(STRONG))
1445 // STRONG already seen, this is a closing tag
1446 _Wikitext_pop_from_stack_up_to(parser, i, STRONG, Qtrue);
1449 // this is a new opening
1450 _Wikitext_pop_excess_elements(parser);
1451 _Wikitext_start_para_if_necessary(parser);
1452 rb_str_cat(i, strong_start, sizeof(strong_start) - 1);
1453 ary_push(parser->scope, STRONG);
1454 ary_push(parser->line, STRONG);
1460 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1462 _Wikitext_emit_pending_crlf_if_necessary(parser);
1463 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1467 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1468 if (IN(STRONG_START) || IN(STRONG))
1469 rb_str_cat(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
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_START);
1476 ary_push(parser->line, STRONG_START);
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_end, sizeof(escaped_strong_end) - 1);
1489 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1490 if (IN(STRONG_START))
1491 _Wikitext_pop_from_stack_up_to(parser, i, STRONG_START, Qtrue);
1494 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1495 _Wikitext_pop_excess_elements(parser);
1496 _Wikitext_start_para_if_necessary(parser);
1497 rb_str_cat(i, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1503 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1505 _Wikitext_emit_pending_crlf_if_necessary(parser);
1506 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1510 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1512 // already in span started with <em>, no choice but to emit this literally
1513 rb_str_cat(parser->output, literal_em, sizeof(literal_em) - 1);
1515 // EM already seen, this is a closing tag
1516 _Wikitext_pop_from_stack_up_to(parser, i, EM, Qtrue);
1519 // this is a new opening
1520 _Wikitext_pop_excess_elements(parser);
1521 _Wikitext_start_para_if_necessary(parser);
1522 rb_str_cat(i, em_start, sizeof(em_start) - 1);
1523 ary_push(parser->scope, EM);
1524 ary_push(parser->line, EM);
1530 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1532 _Wikitext_emit_pending_crlf_if_necessary(parser);
1533 rb_str_cat(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1537 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1538 if (IN(EM_START) || IN(EM))
1539 rb_str_cat(i, escaped_em_start, sizeof(escaped_em_start) - 1);
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_START);
1546 ary_push(parser->line, EM_START);
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_end, sizeof(escaped_em_end) - 1);
1559 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1561 _Wikitext_pop_from_stack_up_to(parser, i, EM_START, Qtrue);
1564 // no EM_START in scope, so must interpret the TT_END without any special meaning
1565 _Wikitext_pop_excess_elements(parser);
1566 _Wikitext_start_para_if_necessary(parser);
1567 rb_str_cat(i, escaped_em_end, sizeof(escaped_em_end) - 1);
1573 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1575 _Wikitext_emit_pending_crlf_if_necessary(parser);
1576 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1580 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1582 // already in span started with <tt>, no choice but to emit this literally
1583 rb_str_cat(parser->output, backtick, sizeof(backtick) - 1);
1585 // TT (`) already seen, this is a closing tag
1586 _Wikitext_pop_from_stack_up_to(parser, i, TT, Qtrue);
1589 // this is a new opening
1590 _Wikitext_pop_excess_elements(parser);
1591 _Wikitext_start_para_if_necessary(parser);
1592 rb_str_cat(i, tt_start, sizeof(tt_start) - 1);
1593 ary_push(parser->scope, TT);
1594 ary_push(parser->line, TT);
1600 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1602 _Wikitext_emit_pending_crlf_if_necessary(parser);
1603 rb_str_cat(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1607 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1608 if (IN(TT_START) || IN(TT))
1609 rb_str_cat(i, escaped_tt_start, sizeof(escaped_tt_start) - 1);
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_START);
1616 ary_push(parser->line, TT_START);
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_end, sizeof(escaped_tt_end) - 1);
1629 i = NIL_P(parser->capture) ? parser->output : parser->capture;
1631 _Wikitext_pop_from_stack_up_to(parser, i, TT_START, Qtrue);
1634 // no TT_START in scope, so must interpret the TT_END without any special meaning
1635 _Wikitext_pop_excess_elements(parser);
1636 _Wikitext_start_para_if_necessary(parser);
1637 rb_str_cat(i, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1644 if (IN(NO_WIKI_START) || IN(PRE_START))
1646 // no need to check for PRE; can never appear inside it
1647 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1651 // count number of tokens in line and scope stacks
1652 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1653 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1654 j = parser->scope->count - bq_count;
1657 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1661 if (type == OL || type == UL)
1664 if (i - k >= 2) // already seen at least one OL or UL
1666 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1671 ary_push(parser->line, type);
1672 ary_push(parser->line, LI);
1674 // want to compare line with scope but can only do so if scope has enough items on it
1677 if (ary_entry(parser->scope, i + bq_count - 2) == type && ary_entry(parser->scope, i + bq_count - 1) == LI)
1679 // line and scope match at this point: do nothing yet
1683 // item just pushed onto line does not match corresponding slot of scope!
1684 for (; j >= i - 2; j--)
1685 // must pop back before emitting
1686 _Wikitext_pop_from_stack(parser, Qnil);
1688 // will emit UL or OL, then LI
1692 else // line stack size now exceeds scope stack size: must increase nesting level
1693 break; // will emit UL or OL, then LI
1697 // not a OL or UL token!
1699 // must close existing LI and re-open new one
1700 _Wikitext_pop_from_stack(parser, Qnil);
1703 // item just pushed onto line does not match corresponding slot of scope!
1705 // must pop back before emitting
1706 _Wikitext_pop_from_stack(parser, Qnil);
1714 if (type == OL || type == UL)
1716 // if LI is at the top of a stack this is the start of a nested list
1717 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1719 // so we should precede it with a CRLF, and indicate that it's a nested list
1720 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1721 ary_push(parser->scope, NESTED_LIST);
1725 // this is a new list
1726 if (IN(BLOCKQUOTE_START))
1727 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1729 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1733 _Wikitext_indent(parser);
1735 rb_str_cat(parser->output, ol_start, sizeof(ol_start) - 1);
1736 else if (type == UL)
1737 rb_str_cat(parser->output, ul_start, sizeof(ul_start) - 1);
1738 ary_push(parser->scope, type);
1739 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1741 else if (type == SPACE)
1742 // silently throw away the optional SPACE token after final list marker
1745 _Wikitext_indent(parser);
1746 rb_str_cat(parser->output, li_start, sizeof(li_start) - 1);
1747 ary_push(parser->scope, LI);
1749 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1750 if (type == OL || type == UL)
1753 while (k++, NEXT_TOKEN(), (type = token->type))
1755 if (type == OL || type == UL)
1756 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1757 else if (type == SPACE && k == 1)
1759 // silently throw away the optional SPACE token after final list marker
1768 // jump to top of the loop to process token we scanned during lookahead
1777 if (IN(NO_WIKI_START) || IN(PRE_START))
1779 // no need to check for PRE; can never appear inside it
1780 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1784 // pop up to but not including the last BLOCKQUOTE on the scope stack
1785 if (IN(BLOCKQUOTE_START))
1786 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE_START, Qfalse);
1788 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qfalse);
1790 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1791 ary_push(parser->line, type);
1792 i = ary_count(parser->line, BLOCKQUOTE);
1793 j = ary_count(parser->scope, BLOCKQUOTE);
1795 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1798 // must pop (reduce nesting level)
1799 for (i = j - i; i > 0; i--)
1800 _Wikitext_pop_from_stack_up_to(parser, Qnil, BLOCKQUOTE, Qtrue);
1803 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1804 while (NEXT_TOKEN(), (token->type == SPACE))
1807 ary_push(parser->scope, type);
1808 _Wikitext_indent(parser);
1810 // take base_heading_level into account
1811 type += base_heading_level;
1812 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1815 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1816 if (type == H6_START)
1817 rb_str_cat(parser->output, h6_start, sizeof(h6_start) - 1);
1818 else if (type == H5_START)
1819 rb_str_cat(parser->output, h5_start, sizeof(h5_start) - 1);
1820 else if (type == H4_START)
1821 rb_str_cat(parser->output, h4_start, sizeof(h4_start) - 1);
1822 else if (type == H3_START)
1823 rb_str_cat(parser->output, h3_start, sizeof(h3_start) - 1);
1824 else if (type == H2_START)
1825 rb_str_cat(parser->output, h2_start, sizeof(h2_start) - 1);
1826 else if (type == H1_START)
1827 rb_str_cat(parser->output, h1_start, sizeof(h1_start) - 1);
1829 // jump to top of the loop to process token we scanned during lookahead
1833 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1835 _Wikitext_emit_pending_crlf_if_necessary(parser);
1836 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1840 _Wikitext_rollback_failed_external_link(parser); // if any
1843 // literal output only if not in h6 scope (we stay silent in that case)
1844 _Wikitext_start_para_if_necessary(parser);
1845 rb_str_cat(parser->output, literal_h6, sizeof(literal_h6) - 1);
1851 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1853 _Wikitext_emit_pending_crlf_if_necessary(parser);
1854 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1858 _Wikitext_rollback_failed_external_link(parser); // if any
1861 // literal output only if not in h5 scope (we stay silent in that case)
1862 _Wikitext_start_para_if_necessary(parser);
1863 rb_str_cat(parser->output, literal_h5, sizeof(literal_h5) - 1);
1869 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1871 _Wikitext_emit_pending_crlf_if_necessary(parser);
1872 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1876 _Wikitext_rollback_failed_external_link(parser); // if any
1879 // literal output only if not in h4 scope (we stay silent in that case)
1880 _Wikitext_start_para_if_necessary(parser);
1881 rb_str_cat(parser->output, literal_h4, sizeof(literal_h4) - 1);
1887 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1889 _Wikitext_emit_pending_crlf_if_necessary(parser);
1890 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1894 _Wikitext_rollback_failed_external_link(parser); // if any
1897 // literal output only if not in h3 scope (we stay silent in that case)
1898 _Wikitext_start_para_if_necessary(parser);
1899 rb_str_cat(parser->output, literal_h3, sizeof(literal_h3) - 1);
1905 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1907 _Wikitext_emit_pending_crlf_if_necessary(parser);
1908 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1912 _Wikitext_rollback_failed_external_link(parser); // if any
1915 // literal output only if not in h2 scope (we stay silent in that case)
1916 _Wikitext_start_para_if_necessary(parser);
1917 rb_str_cat(parser->output, literal_h2, sizeof(literal_h2) - 1);
1923 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1925 _Wikitext_emit_pending_crlf_if_necessary(parser);
1926 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1930 _Wikitext_rollback_failed_external_link(parser); // if any
1933 // literal output only if not in h1 scope (we stay silent in that case)
1934 _Wikitext_start_para_if_necessary(parser);
1935 rb_str_cat(parser->output, literal_h1, sizeof(literal_h1) - 1);
1941 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1943 _Wikitext_emit_pending_crlf_if_necessary(parser);
1944 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1948 // in plain scope, will turn into autolink (with appropriate, user-configurable CSS)
1949 _Wikitext_pop_excess_elements(parser);
1950 _Wikitext_start_para_if_necessary(parser);
1951 i = TOKEN_TEXT(token);
1952 if (parser->autolink == Qtrue)
1953 i = _Wikitext_hyperlink(parser, rb_str_new2("mailto:"), i, i, mailto_class);
1954 rb_str_append(parser->output, i);
1959 if (IN(NO_WIKI_START))
1960 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1961 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1962 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
1963 else if (IN(LINK_START))
1965 // if the URI were allowed it would have been handled already in LINK_START
1966 _Wikitext_rollback_failed_link(parser);
1967 i = TOKEN_TEXT(token);
1968 if (parser->autolink == Qtrue)
1969 i = _Wikitext_hyperlink(parser, Qnil, i, i, parser->external_link_class); // link target, link text
1970 rb_str_append(parser->output, i);
1972 else if (IN(EXT_LINK_START))
1974 if (NIL_P(parser->link_target))
1976 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1977 i = TOKEN_TEXT(token);
1979 if (token->type == SPACE)
1981 ary_push(parser->scope, SPACE);
1982 parser->link_target = i;
1983 parser->link_text = rb_str_new2("");
1984 parser->capture = parser->link_text;
1985 token = NULL; // silently consume space
1989 // didn't see the space! this must be an error
1990 _Wikitext_pop_from_stack(parser, Qnil);
1991 _Wikitext_pop_excess_elements(parser);
1992 _Wikitext_start_para_if_necessary(parser);
1993 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1994 if (parser->autolink == Qtrue)
1995 i = _Wikitext_hyperlink(parser, Qnil, i, i, parser->external_link_class); // link target, link text
1996 rb_str_append(parser->output, i);
2001 if (NIL_P(parser->link_text))
2002 // this must be the first part of our link text
2003 parser->link_text = TOKEN_TEXT(token);
2005 // add to existing link text
2006 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2011 // in plain scope, will turn into autolink (with appropriate, user-configurable CSS)
2012 _Wikitext_pop_excess_elements(parser);
2013 _Wikitext_start_para_if_necessary(parser);
2014 i = TOKEN_TEXT(token);
2015 if (parser->autolink == Qtrue)
2016 i = _Wikitext_hyperlink(parser, Qnil, i, i, parser->external_link_class); // link target, link text
2017 rb_str_append(parser->output, i);
2022 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2023 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2024 else if (IN(EXT_LINK_START))
2026 if (NIL_P(parser->link_target))
2028 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2029 i = TOKEN_TEXT(token);
2031 if (token->type == SPACE)
2033 ary_push(parser->scope, PATH);
2034 ary_push(parser->scope, SPACE);
2035 parser->link_target = i;
2036 parser->link_text = rb_str_new2("");
2037 parser->capture = parser->link_text;
2038 token = NULL; // silently consume space
2042 // didn't see the space! this must be an error
2043 _Wikitext_pop_from_stack(parser, Qnil);
2044 _Wikitext_pop_excess_elements(parser);
2045 _Wikitext_start_para_if_necessary(parser);
2046 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2047 rb_str_append(parser->output, i);
2052 if (NIL_P(parser->link_text))
2053 // this must be the first part of our link text
2054 parser->link_text = TOKEN_TEXT(token);
2056 // add to existing link text
2057 rb_str_cat(parser->link_text, token->start, TOKEN_LEN(token));
2062 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2063 _Wikitext_pop_excess_elements(parser);
2064 _Wikitext_start_para_if_necessary(parser);
2065 rb_str_cat(i, token->start, TOKEN_LEN(token));
2069 // internal links (links to other wiki articles) look like this:
2070 // [[another article]] (would point at, for example, "/wiki/another_article")
2071 // [[the other article|the link text we'll use for it]]
2072 // [[the other article | the link text we'll use for it]]
2073 // MediaWiki has strict requirements about what it will accept as a link target:
2074 // all wikitext markup is disallowed:
2075 // example [[foo ''bar'' baz]]
2076 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2077 // example [[foo <em>bar</em> baz]]
2078 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2079 // example [[foo <nowiki>''</nowiki> baz]]
2080 // renders [[foo '' baz]] (ie. not a link)
2081 // example [[foo <bar> baz]]
2082 // renders [[foo <bar> baz]] (ie. not a link)
2083 // HTML entities and non-ASCII, however, make it through:
2084 // example [[foo €]]
2085 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2086 // example [[foo €]]
2087 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2088 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2089 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2090 // everything else will be rejected
2092 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2093 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2095 _Wikitext_emit_pending_crlf_if_necessary(parser);
2096 rb_str_cat(i, link_start, sizeof(link_start) - 1);
2098 else if (IN(EXT_LINK_START))
2099 // already in external link scope! (and in fact, must be capturing link_text right now)
2100 rb_str_cat(i, link_start, sizeof(link_start) - 1);
2101 else if (IN(LINK_START))
2103 // already in internal link scope! this is a syntax error
2104 _Wikitext_rollback_failed_link(parser);
2105 rb_str_cat(parser->output, link_start, sizeof(link_start) - 1);
2107 else if (IN(SEPARATOR))
2109 // scanning internal link text
2111 else // not in internal link scope yet
2113 // will either emit a link, or the rollback of a failed link, so start the para now
2114 _Wikitext_pop_excess_elements(parser);
2115 _Wikitext_start_para_if_necessary(parser);
2116 ary_push(parser->scope, LINK_START);
2118 // look ahead and try to gobble up link target
2119 while (NEXT_TOKEN(), (type = token->type))
2121 if (type == SPACE ||
2122 type == SPECIAL_URI_CHARS ||
2124 type == PRINTABLE ||
2128 type == QUOT_ENTITY ||
2130 type == AMP_ENTITY ||
2131 type == IMG_START ||
2133 type == LEFT_CURLY ||
2134 type == RIGHT_CURLY)
2136 // accumulate these tokens into link_target
2137 if (NIL_P(parser->link_target))
2139 parser->link_target = rb_str_new2("");
2140 parser->capture = parser->link_target;
2142 if (type == QUOT_ENTITY)
2143 // don't insert the entity, insert the literal quote
2144 rb_str_cat(parser->link_target, quote, sizeof(quote) - 1);
2145 else if (type == AMP_ENTITY)
2146 // don't insert the entity, insert the literal ampersand
2147 rb_str_cat(parser->link_target, ampersand, sizeof(ampersand) - 1);
2149 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2151 else if (type == LINK_END)
2153 if (NIL_P(parser->link_target)) // bail for inputs like "[[]]"
2154 _Wikitext_rollback_failed_link(parser);
2155 break; // jump back to top of loop (will handle this in LINK_END case below)
2157 else if (type == SEPARATOR)
2159 if (NIL_P(parser->link_target)) // bail for inputs like "[[|"
2160 _Wikitext_rollback_failed_link(parser);
2163 ary_push(parser->scope, SEPARATOR);
2164 parser->link_text = rb_str_new2("");
2165 parser->capture = parser->link_text;
2170 else // unexpected token (syntax error)
2172 _Wikitext_rollback_failed_link(parser);
2173 break; // jump back to top of loop to handle unexpected token
2177 // jump to top of the loop to process token we scanned during lookahead (if any)
2183 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2184 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2186 _Wikitext_emit_pending_crlf_if_necessary(parser);
2187 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2189 else if (IN(EXT_LINK_START))
2190 // already in external link scope! (and in fact, must be capturing link_text right now)
2191 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2192 else if (IN(LINK_START)) // in internal link scope!
2194 if (_Wikitext_blank(parser->link_target))
2196 // special case for inputs like "[[ ]]"
2197 _Wikitext_rollback_failed_link(parser);
2198 rb_str_cat(parser->output, link_end, sizeof(link_end) - 1);
2201 if (NIL_P(parser->link_text) || RSTRING_LEN(parser->link_text) == 0)
2202 // use link target as link text
2203 parser->link_text = _Wikitext_parser_sanitize_link_target(parser, Qfalse);
2205 parser->link_text = _Wikitext_parser_trim_link_target(parser->link_text);
2206 _Wikitext_parser_encode_link_target(parser);
2207 _Wikitext_pop_from_stack_up_to(parser, i, LINK_START, Qtrue);
2208 parser->capture = Qnil;
2209 i = _Wikitext_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil);
2210 rb_str_append(parser->output, i);
2211 parser->link_target = Qnil;
2212 parser->link_text = Qnil;
2214 else // wasn't in internal link scope
2216 _Wikitext_pop_excess_elements(parser);
2217 _Wikitext_start_para_if_necessary(parser);
2218 rb_str_cat(i, link_end, sizeof(link_end) - 1);
2222 // external links look like this:
2223 // [http://google.com/ the link text]
2224 // [/other/page/on/site see this page]
2225 // strings in square brackets which don't match this syntax get passed through literally; eg:
2226 // he was very angery [sic] about the turn of events
2227 case EXT_LINK_START:
2228 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2229 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2231 _Wikitext_emit_pending_crlf_if_necessary(parser);
2232 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2234 else if (IN(EXT_LINK_START))
2235 // already in external link scope! (and in fact, must be capturing link_text right now)
2236 rb_str_cat(i, ext_link_start, sizeof(ext_link_start) - 1);
2237 else if (IN(LINK_START))
2239 // already in internal link scope!
2240 i = rb_str_new(ext_link_start, sizeof(ext_link_start) - 1);
2241 if (NIL_P(parser->link_target))
2242 // this must be the first character of our link target
2243 parser->link_target = i;
2246 // link target has already been scanned
2247 if (NIL_P(parser->link_text))
2248 // this must be the first character of our link text
2249 parser->link_text = i;
2251 // add to existing link text
2252 rb_str_append(parser->link_text, i);
2255 // add to existing link target
2256 rb_str_append(parser->link_target, i);
2258 else // not in external link scope yet
2260 // will either emit a link, or the rollback of a failed link, so start the para now
2261 _Wikitext_pop_excess_elements(parser);
2262 _Wikitext_start_para_if_necessary(parser);
2264 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2266 if (token->type == URI || token->type == PATH)
2267 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2269 // only get here if there was a syntax error (missing URI)
2270 rb_str_cat(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2271 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2276 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2277 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2279 _Wikitext_emit_pending_crlf_if_necessary(parser);
2280 rb_str_cat(i, ext_link_end, sizeof(ext_link_end) - 1);
2282 else if (IN(EXT_LINK_START))
2284 if (NIL_P(parser->link_text))
2285 // syntax error: external link with no link text
2286 _Wikitext_rollback_failed_external_link(parser);
2290 j = IN(PATH) ? Qnil : parser->external_link_class;
2291 _Wikitext_pop_from_stack_up_to(parser, i, EXT_LINK_START, Qtrue);
2292 parser->capture = Qnil;
2293 i = _Wikitext_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j);
2294 rb_str_append(parser->output, i);
2296 parser->link_target = Qnil;
2297 parser->link_text = Qnil;
2301 _Wikitext_pop_excess_elements(parser);
2302 _Wikitext_start_para_if_necessary(parser);
2303 rb_str_cat(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2308 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2309 _Wikitext_pop_excess_elements(parser);
2310 _Wikitext_start_para_if_necessary(parser);
2311 rb_str_cat(i, separator, sizeof(separator) - 1);
2315 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2316 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2318 _Wikitext_emit_pending_crlf_if_necessary(parser);
2319 rb_str_cat(i, token->start, TOKEN_LEN(token));
2323 // peek ahead to see next token
2324 char *token_ptr = token->start;
2325 int token_len = TOKEN_LEN(token);
2328 if (((type == H6_END) && IN(H6_START)) ||
2329 ((type == H5_END) && IN(H5_START)) ||
2330 ((type == H4_END) && IN(H4_START)) ||
2331 ((type == H3_END) && IN(H3_START)) ||
2332 ((type == H2_END) && IN(H2_START)) ||
2333 ((type == H1_END) && IN(H1_START)))
2335 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2340 _Wikitext_pop_excess_elements(parser);
2341 _Wikitext_start_para_if_necessary(parser);
2342 rb_str_cat(i, token_ptr, token_len);
2345 // jump to top of the loop to process token we scanned during lookahead
2353 case DECIMAL_ENTITY:
2354 // pass these through unaltered as they are case sensitive
2355 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2356 _Wikitext_pop_excess_elements(parser);
2357 _Wikitext_start_para_if_necessary(parser);
2358 rb_str_cat(i, token->start, TOKEN_LEN(token));
2362 // normalize hex entities (downcase them)
2363 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2364 _Wikitext_pop_excess_elements(parser);
2365 _Wikitext_start_para_if_necessary(parser);
2366 rb_str_append(i, _Wikitext_downcase(TOKEN_TEXT(token)));
2370 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2371 _Wikitext_pop_excess_elements(parser);
2372 _Wikitext_start_para_if_necessary(parser);
2373 rb_str_cat(i, quot_entity, sizeof(quot_entity) - 1);
2377 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2378 _Wikitext_pop_excess_elements(parser);
2379 _Wikitext_start_para_if_necessary(parser);
2380 rb_str_cat(i, amp_entity, sizeof(amp_entity) - 1);
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_cat(i, lt_entity, sizeof(lt_entity) - 1);
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, gt_entity, sizeof(gt_entity) - 1);
2398 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2400 _Wikitext_emit_pending_crlf_if_necessary(parser);
2401 rb_str_cat(parser->output, token->start, TOKEN_LEN(token));
2403 else if (!NIL_P(parser->capture))
2404 rb_str_cat(parser->capture, token->start, TOKEN_LEN(token));
2407 // not currently capturing: will be emitting something on success or failure, so get ready
2408 _Wikitext_pop_excess_elements(parser);
2409 _Wikitext_start_para_if_necessary(parser);
2411 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2412 // will cheat here and abuse the link_target capture buffer to accumulate text
2413 if (NIL_P(parser->link_target))
2414 parser->link_target = rb_str_new2("");
2415 while (NEXT_TOKEN(), (type = token->type))
2417 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2418 rb_str_cat(parser->link_target, token->start, TOKEN_LEN(token));
2419 else if (type == IMG_END && RSTRING_LEN(parser->link_target) > 0)
2422 _Wikitext_append_img(parser, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2426 else // unexpected token or zero-length target (syntax error)
2429 rb_str_cat(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2430 rb_str_cat(parser->output, RSTRING_PTR(parser->link_target), RSTRING_LEN(parser->link_target));
2435 // jump to top of the loop to process token we scanned during lookahead
2436 parser->link_target = Qnil;
2442 i = parser->pending_crlf;
2443 parser->pending_crlf = Qfalse;
2444 _Wikitext_rollback_failed_link(parser); // if any
2445 _Wikitext_rollback_failed_external_link(parser); // if any
2446 if (IN(NO_WIKI_START) || IN(PRE_START))
2448 ary_clear(parser->line_buffer);
2449 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2454 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2455 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2456 // don't emit in this case
2457 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2460 if (ary_entry(parser->line_buffer, -2) == PRE)
2462 // only thing on line is the PRE: emit pending line ending (if we had one)
2464 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2467 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2468 ary_clear(parser->line);
2469 ary_clear(parser->line_buffer);
2471 // peek ahead to see if this is definitely the end of the PRE block
2474 if (type != BLOCKQUOTE && type != PRE)
2475 // this is definitely the end of the block, so don't emit
2476 _Wikitext_pop_from_stack_up_to(parser, parser->output, PRE, Qtrue);
2478 // potentially will emit
2479 parser->pending_crlf = Qtrue;
2481 continue; // jump back to top of loop to handle token grabbed via lookahead
2486 parser->pending_crlf = Qtrue;
2488 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2489 // as a side effect, this handles any open span-level elements and unclosed blocks
2490 // (with special handling for P blocks and LI elements)
2491 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2492 for (j = parser->scope->count; j > i; j--)
2494 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2496 parser->pending_crlf = Qfalse;
2500 // special handling on last iteration through the loop if the top item on the scope is a P block
2501 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2503 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2504 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2505 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2506 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2507 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2509 parser->pending_crlf = Qfalse;
2511 // not a paragraph break!
2514 _Wikitext_pop_from_stack(parser, Qnil);
2518 // delete the entire contents of the line scope stack and buffer
2519 ary_clear(parser->line);
2520 ary_clear(parser->line_buffer);
2523 case SPECIAL_URI_CHARS:
2529 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2530 _Wikitext_pop_excess_elements(parser);
2531 _Wikitext_start_para_if_necessary(parser);
2532 rb_str_cat(i, token->start, TOKEN_LEN(token));
2536 i = NIL_P(parser->capture) ? parser->output : parser->capture;
2537 _Wikitext_pop_excess_elements(parser);
2538 _Wikitext_start_para_if_necessary(parser);
2539 rb_str_append(i, _Wikitext_utf32_char_to_entity(token->code_point)); // convert to entity
2543 // special case for input like " foo\n " (see pre_spec.rb)
2545 ary_entry(parser->line_buffer, -2) == PRE &&
2546 parser->pending_crlf == Qtrue)
2547 rb_str_cat(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2549 // close any open scopes on hitting EOF
2550 _Wikitext_rollback_failed_external_link(parser); // if any
2551 _Wikitext_rollback_failed_link(parser); // if any
2552 for (i = 0, j = parser->scope->count; i < j; i++)
2553 _Wikitext_pop_from_stack(parser, Qnil);
2554 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2560 // reset current token; forcing lexer to return another token at the top of the loop
2564 return parser->output;