1 // Copyright 2007-present Greg Hurrell. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are met:
6 // 1. Redistributions of source code must retain the above copyright notice,
7 // this list of conditions and the following disclaimer.
8 // 2. Redistributions in binary form must reproduce the above copyright notice,
9 // this list of conditions and the following disclaimer in the documentation
10 // and/or other materials provided with the distribution.
12 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
13 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
16 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
17 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
18 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
19 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
20 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
21 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
22 // POSSIBILITY OF SUCH DAMAGE.
30 #include "wikitext_ragel.h"
32 #define IN(type) ary_includes(parser->scope, type)
33 #define IN_EITHER_OF(type1, type2) ary_includes2(parser->scope, type1, type2)
34 #define IN_ANY_OF(type1, type2, type3) ary_includes3(parser->scope, type1, type2, type3)
37 enum { HTML_OUTPUT, XML_OUTPUT };
39 // poor man's object orientation in C:
40 // instead of passing around multiple parameters between functions in the parser
41 // we pack everything into a struct and pass around only a pointer to that
44 str_t *capture; // capturing to link_target, link_text, or NULL (direct to output, not capturing)
45 str_t *output; // for accumulating output to be returned
46 str_t *link_target; // short term "memory" for parsing links
47 str_t *link_text; // short term "memory" for parsing links
49 str_t *tabulation; // caching buffer for emitting indentation
50 ary_t *scope; // stack for tracking scope
51 ary_t *line; // stack for tracking scope as implied by current line
52 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
53 VALUE external_link_class; // CSS class applied to external links
54 VALUE external_link_rel; // rel attribute 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 int output_style; // HTML_OUTPUT (default) or XML_OUTPUT
58 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
59 int current_indent; // fluctuates according to currently nested structures
60 int base_heading_level;
63 bool space_to_underscore;
67 const char null_str[] = { 0 };
68 const char escaped_no_wiki_start[] = "<nowiki>";
69 const char escaped_no_wiki_end[] = "</nowiki>";
70 const char literal_strong_em[] = "'''''";
71 const char literal_strong[] = "'''";
72 const char literal_em[] = "''";
73 const char escaped_em_start[] = "<em>";
74 const char escaped_em_end[] = "</em>";
75 const char escaped_strong_start[] = "<strong>";
76 const char escaped_strong_end[] = "</strong>";
77 const char escaped_tt_start[] = "<tt>";
78 const char escaped_tt_end[] = "</tt>";
79 const char pre_start[] = "<pre>";
80 const char pre_end[] = "</pre>";
81 const char escaped_pre_start[] = "<pre>";
82 const char escaped_pre_end[] = "</pre>";
83 const char blockquote_start[] = "<blockquote>";
84 const char blockquote_end[] = "</blockquote>";
85 const char escaped_blockquote_start[] = "<blockquote>";
86 const char escaped_blockquote_end[] = "</blockquote>";
87 const char strong_em_start[] = "<strong><em>";
88 const char strong_start[] = "<strong>";
89 const char strong_end[] = "</strong>";
90 const char em_start[] = "<em>";
91 const char em_end[] = "</em>";
92 const char code_start[] = "<code>";
93 const char code_end[] = "</code>";
94 const char ol_start[] = "<ol>";
95 const char ol_end[] = "</ol>";
96 const char ul_start[] = "<ul>";
97 const char ul_end[] = "</ul>";
98 const char li_start[] = "<li>";
99 const char li_end[] = "</li>";
100 const char h6_start[] = "<h6>";
101 const char h6_end[] = "</h6>";
102 const char h5_start[] = "<h5>";
103 const char h5_end[] = "</h5>";
104 const char h4_start[] = "<h4>";
105 const char h4_end[] = "</h4>";
106 const char h3_start[] = "<h3>";
107 const char h3_end[] = "</h3>";
108 const char h2_start[] = "<h2>";
109 const char h2_end[] = "</h2>";
110 const char h1_start[] = "<h1>";
111 const char h1_end[] = "</h1>";
112 const char p_start[] = "<p>";
113 const char p_end[] = "</p>";
114 const char space[] = " ";
115 const char a_start[] = "<a href=\"";
116 const char a_class[] = "\" class=\"";
117 const char a_rel[] = "\" rel=\"";
118 const char a_start_close[] = "\">";
119 const char a_end[] = "</a>";
120 const char link_start[] = "[[";
121 const char link_end[] = "]]";
122 const char separator[] = "|";
123 const char ext_link_start[] = "[";
124 const char backtick[] = "`";
125 const char quote[] = "\"";
126 const char ampersand[] = "&";
127 const char quot_entity[] = """;
128 const char amp_entity[] = "&";
129 const char lt_entity[] = "<";
130 const char gt_entity[] = ">";
131 const char escaped_blockquote[] = "> ";
132 const char ext_link_end[] = "]";
133 const char literal_img_start[] = "{{";
134 const char img_start[] = "<img src=\"";
135 const char img_end_xml[] = "\" />";
136 const char img_end_html[] = "\">";
137 const char img_alt[] = "\" alt=\"";
138 const char pre_class_start[] = "<pre class=\"";
139 const char pre_class_end[] = "-syntax\">";
141 // Mark the parser struct designated by ptr as a participant in Ruby's
142 // mark-and-sweep garbage collection scheme. A variable named name is placed on
143 // the C stack to prevent the structure from being prematurely collected.
144 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
146 parser_t *parser_new(void)
148 parser_t *parser = ALLOC_N(parser_t, 1);
149 parser->capture = NULL; // not a real instance, pointer to other member's instance
150 parser->output = str_new();
151 parser->link_target = str_new();
152 parser->link_text = str_new();
153 parser->line_ending = NULL; // caller should set up
154 parser->tabulation = str_new();
155 parser->scope = ary_new();
156 parser->line = ary_new();
157 parser->line_buffer = ary_new();
158 parser->external_link_class = Qnil; // caller should set up
159 parser->external_link_rel = Qnil; // caller should set up
160 parser->mailto_class = Qnil; // caller should set up
161 parser->img_prefix = Qnil; // caller should set up
162 parser->output_style = HTML_OUTPUT;
163 parser->base_indent = 0;
164 parser->current_indent = 0;
165 parser->base_heading_level = 0;
166 parser->pending_crlf = false;
167 parser->autolink = true;
168 parser->space_to_underscore = true;
169 parser->pre_code = false;
173 void parser_free(parser_t *parser)
175 // we don't free parser->capture; it's just a redundant pointer
176 if (parser->output) str_free(parser->output);
177 if (parser->link_target) str_free(parser->link_target);
178 if (parser->link_text) str_free(parser->link_text);
179 if (parser->line_ending) str_free(parser->line_ending);
180 if (parser->tabulation) str_free(parser->tabulation);
181 if (parser->scope) ary_free(parser->scope);
182 if (parser->line) ary_free(parser->line);
183 if (parser->line_buffer) ary_free(parser->line_buffer);
187 // for testing and debugging only
188 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
192 string = StringValue(string);
193 VALUE tokens = rb_ary_new();
194 char *p = RSTRING_PTR(string);
195 long len = RSTRING_LEN(string);
198 next_token(&token, NULL, p, pe);
199 rb_ary_push(tokens, wiki_token(&token));
200 while (token.type != END_OF_FILE)
202 next_token(&token, &token, NULL, pe);
203 rb_ary_push(tokens, wiki_token(&token));
208 // for benchmarking raw tokenization speed only
209 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
213 string = StringValue(string);
214 char *p = RSTRING_PTR(string);
215 long len = RSTRING_LEN(string);
218 next_token(&token, NULL, p, pe);
219 while (token.type != END_OF_FILE)
220 next_token(&token, &token, NULL, pe);
224 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
227 VALUE string, options;
228 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
232 string = StringValue(string);
233 VALUE tokens = rb_ary_new();
235 // check instance variables
236 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
238 // process options hash (can override instance variables)
239 if (!NIL_P(options) && TYPE(options) == T_HASH)
241 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
242 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
244 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
249 char *p = RSTRING_PTR(string);
250 long len = RSTRING_LEN(string);
253 token_t *_token = &token;
254 next_token(&token, NULL, p, pe);
255 while (token.type != END_OF_FILE)
262 if (TOKEN_LEN(_token) >= min_len)
263 rb_ary_push(tokens, TOKEN_TEXT(_token));
266 // ignore everything else
269 next_token(&token, &token, NULL, pe);
274 // we downcase "in place", overwriting the original contents of the buffer
275 void wiki_downcase_bang(char *ptr, long len)
277 for (long i = 0; i < len; i++)
279 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
284 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
286 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
287 char scratch = (character & 0xf000) >> 12;
288 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
289 scratch = (character & 0x0f00) >> 8;
290 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
291 scratch = (character & 0x00f0) >> 4;
292 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
293 scratch = character & 0x000f;
294 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
295 str_append(output, hex_string, sizeof(hex_string));
298 // Convert a single UTF-8 codepoint to UTF-32
300 // Expects an input buffer, src, containing a UTF-8 encoded character (which
301 // may be multi-byte). The end of the input buffer, end, is also passed in to
302 // allow the detection of invalidly truncated codepoints. The number of bytes
303 // in the UTF-8 character (between 1 and 4) is returned by reference in
306 // Raises a RangeError if the supplied character is invalid UTF-8.
307 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
310 if ((unsigned char)src[0] <= 0x7f)
316 else if ((src[0] & 0xe0) == 0xc0)
318 // byte starts with 110..... : this should be a two-byte sequence
321 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
322 else if (((unsigned char)src[0] == 0xc0) ||
323 ((unsigned char)src[0] == 0xc1))
324 // overlong encoding: lead byte of 110..... but code point <= 127
325 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
326 else if ((src[1] & 0xc0) != 0x80 )
327 // should have second byte starting with 10......
328 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
331 ((uint32_t)(src[0] & 0x1f)) << 6 |
335 else if ((src[0] & 0xf0) == 0xe0)
337 // byte starts with 1110.... : this should be a three-byte sequence
339 // missing second or third byte
340 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
341 else if (((src[1] & 0xc0) != 0x80 ) ||
342 ((src[2] & 0xc0) != 0x80 ))
343 // should have second and third bytes starting with 10......
344 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
347 ((uint32_t)(src[0] & 0x0f)) << 12 |
348 ((uint32_t)(src[1] & 0x3f)) << 6 |
352 else if ((src[0] & 0xf8) == 0xf0)
354 // bytes starts with 11110... : this should be a four-byte sequence
356 // missing second, third, or fourth byte
357 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
358 else if ((unsigned char)src[0] >= 0xf5 &&
359 (unsigned char)src[0] <= 0xf7)
360 // disallowed by RFC 3629 (codepoints above 0x10ffff)
361 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
362 else if (((src[1] & 0xc0) != 0x80 ) ||
363 ((src[2] & 0xc0) != 0x80 ) ||
364 ((src[3] & 0xc0) != 0x80 ))
365 // should have second and third bytes starting with 10......
366 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
369 ((uint32_t)(src[0] & 0x07)) << 18 |
370 ((uint32_t)(src[1] & 0x3f)) << 12 |
371 ((uint32_t)(src[1] & 0x3f)) << 6 |
376 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
380 // - non-printable (non-ASCII) characters converted to numeric entities
381 // - QUOT and AMP characters converted to named entities
382 // - if trim is true, leading and trailing whitespace trimmed
383 // - if trim is false, there is no special treatment of spaces
384 void wiki_append_sanitized_link_target(str_t *link_target, str_t *output, bool trim)
386 char *src = link_target->ptr;
387 char *start = src; // remember this so we can check if we're at the start
388 char *non_space = output->ptr + output->len; // remember last non-space character output
389 char *end = src + link_target->len;
392 // need at most 8 bytes to display each input character (�)
393 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
395 char *old_ptr = output->ptr;
396 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
397 if (old_ptr != output->ptr) // may have moved
398 non_space += output->ptr - old_ptr;
403 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
404 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
406 else if (*src == '&')
408 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
409 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
411 else if (*src == '<' || *src == '>')
412 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
413 else if (*src == ' ' && src == start && trim)
414 start++; // we eat leading space
415 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
417 *(output->ptr + output->len) = *src;
420 else // all others: must convert to entities
423 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
425 non_space = output->ptr + output->len;
429 non_space = output->ptr + output->len;
433 // trim trailing space if necessary
434 if (trim && output->ptr + output->len != non_space)
435 output->len -= (output->ptr + output->len) - non_space;
438 // prepare hyperlink and append it to parser->output
439 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
440 // or merely the literal link target
441 // if link_text is Qnil, the link_target is re-used for the link text
442 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, VALUE link_rel, bool check_autolink)
444 if (check_autolink && !parser->autolink)
445 wiki_append_sanitized_link_target(link_target, parser->output, true);
448 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
449 if (!NIL_P(link_prefix))
450 str_append_string(parser->output, link_prefix);
451 wiki_append_sanitized_link_target(link_target, parser->output, true);
453 // special handling for mailto URIs
454 const char *mailto = "mailto:";
455 long mailto_len = (long)sizeof(mailto) - 1; // don't count NUL byte
456 if ((link_target->len >= mailto_len &&
457 strncmp(mailto, link_target->ptr, mailto_len) == 0) ||
458 (!NIL_P(link_prefix) &&
459 RSTRING_LEN(link_prefix) >= mailto_len &&
460 strncmp(mailto, RSTRING_PTR(link_prefix), mailto_len) == 0))
461 link_class = parser->mailto_class; // use mailto_class from parser
462 if (link_class != Qnil)
464 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
465 str_append_string(parser->output, link_class);
467 if (link_rel != Qnil)
469 str_append(parser->output, a_rel, sizeof(a_rel) - 1); // " rel="
470 str_append_string(parser->output, link_rel);
472 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
473 if (!link_text || link_text->len == 0) // re-use link_target
474 wiki_append_sanitized_link_target(link_target, parser->output, true);
476 str_append_str(parser->output, link_text);
477 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
481 void wiki_append_img(parser_t *parser, char *token_ptr, long token_len)
483 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
484 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
485 str_append_string(parser->output, parser->img_prefix);
486 str_append(parser->output, token_ptr, token_len);
487 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
488 str_append(parser->output, token_ptr, token_len);
489 if (parser->output_style == XML_OUTPUT)
490 str_append(parser->output, img_end_xml, sizeof(img_end_xml) - 1); // " />
492 str_append(parser->output, img_end_html, sizeof(img_end_html) - 1); // ">
495 // will emit indentation only if we are about to emit any of:
496 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
497 // each time we enter one of those spans must ++ the indentation level
498 void wiki_indent(parser_t *parser)
500 if (parser->base_indent == -1) // indentation disabled
502 int space_count = parser->current_indent + parser->base_indent;
505 char *old_end, *new_end;
506 if (parser->tabulation->len < space_count)
507 str_grow(parser->tabulation, space_count); // reallocates if necessary
508 old_end = parser->tabulation->ptr + parser->tabulation->len;
509 new_end = parser->tabulation->ptr + space_count;
510 while (old_end < new_end)
512 if (space_count > parser->tabulation->len)
513 parser->tabulation->len = space_count;
514 str_append(parser->output, parser->tabulation->ptr, space_count);
516 parser->current_indent += 2;
519 void wiki_append_pre_start(parser_t *parser, token_t *token)
522 if ((size_t)TOKEN_LEN(token) > sizeof(pre_start) - 1)
524 str_append(parser->output, pre_class_start, sizeof(pre_class_start) - 1); // <pre class="
525 str_append(parser->output, token->start + 11, TOKEN_LEN(token) - 13); // (the "lang" substring)
526 str_append(parser->output, pre_class_end, sizeof(pre_class_end) - 1); // -syntax">
529 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
530 if (parser->pre_code)
531 str_append(parser->output, code_start, sizeof(code_start) - 1);
532 ary_push(parser->scope, PRE_START);
533 ary_push(parser->line, PRE_START);
536 void wiki_dedent(parser_t *parser, bool emit)
538 if (parser->base_indent == -1) // indentation disabled
540 parser->current_indent -= 2;
543 int space_count = parser->current_indent + parser->base_indent;
545 str_append(parser->output, parser->tabulation->ptr, space_count);
548 // Pops a single item off the parser's scope stack.
549 // A corresponding closing tag is written to the target string.
550 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
551 void wiki_pop_from_stack(parser_t *parser, str_t *target)
553 int top = ary_entry(parser->scope, -1);
557 target = parser->output;
559 // for headings, take base_heading_level into account
560 if (top >= H1_START && top <= H6_START)
562 top += parser->base_heading_level;
563 // no need to check for underflow (base_heading_level is never negative)
572 if (parser->pre_code)
573 str_append(target, code_end, sizeof(code_end) - 1);
574 str_append(target, pre_end, sizeof(pre_end) - 1);
575 str_append_str(target, parser->line_ending);
576 wiki_dedent(parser, false);
580 case BLOCKQUOTE_START:
581 wiki_dedent(parser, true);
582 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
583 str_append_str(target, parser->line_ending);
587 // not a real HTML tag; so nothing to pop
592 str_append(target, strong_end, sizeof(strong_end) - 1);
597 str_append(target, em_end, sizeof(em_end) - 1);
602 str_append(target, code_end, sizeof(code_end) - 1);
606 wiki_dedent(parser, true);
607 str_append(target, ol_end, sizeof(ol_end) - 1);
608 str_append_str(target, parser->line_ending);
612 wiki_dedent(parser, true);
613 str_append(target, ul_end, sizeof(ul_end) - 1);
614 str_append_str(target, parser->line_ending);
618 // next token to pop will be a LI
619 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
620 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
621 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
622 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
623 wiki_dedent(parser, true); // we really only want to emit the spaces
624 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
628 str_append(target, li_end, sizeof(li_end) - 1);
629 str_append_str(target, parser->line_ending);
630 wiki_dedent(parser, false);
634 str_append(target, h6_end, sizeof(h6_end) - 1);
635 str_append_str(target, parser->line_ending);
636 wiki_dedent(parser, false);
640 str_append(target, h5_end, sizeof(h5_end) - 1);
641 str_append_str(target, parser->line_ending);
642 wiki_dedent(parser, false);
646 str_append(target, h4_end, sizeof(h4_end) - 1);
647 str_append_str(target, parser->line_ending);
648 wiki_dedent(parser, false);
652 str_append(target, h3_end, sizeof(h3_end) - 1);
653 str_append_str(target, parser->line_ending);
654 wiki_dedent(parser, false);
658 str_append(target, h2_end, sizeof(h2_end) - 1);
659 str_append_str(target, parser->line_ending);
660 wiki_dedent(parser, false);
664 str_append(target, h1_end, sizeof(h1_end) - 1);
665 str_append_str(target, parser->line_ending);
666 wiki_dedent(parser, false);
670 // not an HTML tag; so nothing to emit
674 // not an HTML tag; so nothing to emit
678 // not an HTML tag; so nothing to emit
682 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
686 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
690 str_append(target, p_end, sizeof(p_end) - 1);
691 str_append_str(target, parser->line_ending);
692 wiki_dedent(parser, false);
700 // should probably raise an exception here
703 ary_pop(parser->scope);
706 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
707 // If including is true then the item itself is also popped.
708 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
709 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
711 int continue_looping = 1;
714 int top = ary_entry(parser->scope, -1);
721 continue_looping = 0;
723 wiki_pop_from_stack(parser, target);
724 } while (continue_looping);
727 void wiki_pop_all_from_stack(parser_t *parser)
729 for (int i = 0, max = parser->scope->count; i < max; i++)
730 wiki_pop_from_stack(parser, NULL);
733 void wiki_start_para_if_necessary(parser_t *parser)
738 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
739 if (parser->scope->count == 0 ||
740 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
741 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
744 str_append(parser->output, p_start, sizeof(p_start) - 1);
745 ary_push(parser->scope, P);
746 ary_push(parser->line, P);
748 else if (parser->pending_crlf)
751 // already in a paragraph block; convert pending CRLF into a space
752 str_append(parser->output, space, sizeof(space) - 1);
754 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
755 str_append_str(parser->output, parser->line_ending);
757 parser->pending_crlf = false;
760 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
762 if (parser->pending_crlf)
764 str_append_str(parser->output, parser->line_ending);
765 parser->pending_crlf = false;
769 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
770 // For example, given input like:
775 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
776 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
781 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
782 // but not on the line scope:
787 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
788 // on the line scope.
789 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
790 // entering the for loop.
791 void wiki_pop_excess_elements(parser_t *parser)
795 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
797 // special case for last item on scope
800 // don't auto-pop P if it is only item on scope
801 if (ary_entry(parser->scope, -1) == P)
803 // add P to the line scope to prevent us entering the loop at all next time around
804 ary_push(parser->line, P);
808 wiki_pop_from_stack(parser, NULL);
812 // trim parser->link_text in place
813 void wiki_trim_link_text(parser_t *parser)
815 char *src = parser->link_text->ptr;
816 char *start = src; // remember this so we can check if we're at the start
818 char *non_space = src; // remember last non-space character output
819 char *end = src + parser->link_text->len;
831 if (left != start || non_space + 1 != end)
833 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
834 parser->link_text->len = (non_space + 1) - left;
835 memmove(parser->link_text->ptr, left, parser->link_text->len);
839 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
841 str_t *link_target = str_new_from_string(string);
842 GC_WRAP_STR(link_target, link_target_gc);
843 str_t *output = str_new();
844 GC_WRAP_STR(output, output_gc);
845 wiki_append_sanitized_link_target(link_target, output, true);
846 return string_from_str(output);
849 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
851 // Leading and trailing whitespace trimmed. Spaces are converted to
852 // underscores if the parser space_to_underscore member is true.
853 static void wiki_encode_link_target(parser_t *parser)
855 char *src = parser->link_target->ptr;
856 char *start = src; // remember this so we can check if we're at the start
857 long len = parser->link_target->len;
860 char *end = src + len;
861 long dest_len = len * 2;
862 char *dest = ALLOC_N(char, dest_len);
863 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
864 char *non_space = dest; // remember last non-space character output
865 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
866 for (; src < end; src++)
868 // worst case: a single character may grow to 3 characters once encoded
869 if ((dest + 3) > (dest_ptr + dest_len))
871 // outgrowing buffer, must reallocate
872 char *old_dest = dest;
873 char *old_dest_ptr = dest_ptr;
875 dest = realloc(dest_ptr, dest_len);
878 // would have used reallocf, but this has to run on Linux too, not just Darwin
880 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
883 dest = dest_ptr + (old_dest - old_dest_ptr);
884 non_space = dest_ptr + (non_space - old_dest_ptr);
887 // pass through unreserved characters
888 if ((*src >= 'a' && *src <= 'z') ||
889 (*src >= 'A' && *src <= 'Z') ||
890 (*src >= '0' && *src <= '9') ||
899 else if (*src == ' ' && src == start)
900 start++; // we eat leading space
901 else if (*src == ' ' && parser->space_to_underscore)
903 else // everything else gets URL-encoded
906 *dest++ = hex[(unsigned char)(*src) / 16]; // left
907 *dest++ = hex[(unsigned char)(*src) % 16]; // right
913 // trim trailing space if necessary
914 if (non_space > dest_ptr && dest != non_space)
915 dest_len = non_space - dest_ptr;
917 dest_len = dest - dest_ptr;
918 str_clear(parser->link_target);
919 str_append(parser->link_target, dest_ptr, dest_len);
923 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
926 parser.space_to_underscore = false;
927 parser.link_target = str_new_from_string(in);
928 GC_WRAP_STR(parser.link_target, link_target_gc);
929 wiki_encode_link_target(&parser);
930 return string_from_str(parser.link_target);
933 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
934 // returns 0 (false) otherwise
935 bool wiki_blank(str_t *str)
939 for (char *ptr = str->ptr,
940 *end = str->ptr + str->len;
949 void wiki_rollback_failed_internal_link(parser_t *parser)
952 return; // nothing to do!
953 int scope_includes_separator = IN(SEPARATOR);
954 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
955 str_append(parser->output, link_start, sizeof(link_start) - 1);
956 if (parser->link_target->len > 0)
958 wiki_append_sanitized_link_target(parser->link_target, parser->output, false);
959 if (scope_includes_separator)
961 str_append(parser->output, separator, sizeof(separator) - 1);
962 if (parser->link_text->len > 0)
963 str_append_str(parser->output, parser->link_text);
966 parser->capture = NULL;
967 str_clear(parser->link_target);
968 str_clear(parser->link_text);
971 void wiki_rollback_failed_external_link(parser_t *parser)
973 if (!IN(EXT_LINK_START))
974 return; // nothing to do!
976 // store a couple of values before popping
977 int scope_includes_space = IN(SPACE);
978 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
979 VALUE link_rel = IN(PATH) ? Qnil : parser->external_link_rel;
980 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
982 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
983 if (parser->link_target->len > 0)
985 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, link_rel, true);
986 if (scope_includes_space)
988 str_append(parser->output, space, sizeof(space) - 1);
989 if (parser->link_text->len > 0)
990 str_append_str(parser->output, parser->link_text);
993 parser->capture = NULL;
994 str_clear(parser->link_target);
995 str_clear(parser->link_text);
998 void wiki_rollback_failed_link(parser_t *parser)
1000 wiki_rollback_failed_internal_link(parser);
1001 wiki_rollback_failed_external_link(parser);
1004 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
1006 // process arguments
1008 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
1012 VALUE autolink = Qtrue;
1013 VALUE line_ending = rb_str_new2("\n");
1014 VALUE external_link_class = rb_str_new2("external");
1015 VALUE external_link_rel = Qnil;
1016 VALUE mailto_class = rb_str_new2("mailto");
1017 VALUE link_proc = Qnil;
1018 VALUE internal_link_prefix = rb_str_new2("/wiki/");
1019 VALUE img_prefix = rb_str_new2("/images/");
1020 VALUE output_style = ID2SYM(rb_intern("html"));
1021 VALUE space_to_underscore = Qtrue;
1022 VALUE pre_code = Qfalse;
1023 VALUE minimum_fulltext_token_length = INT2NUM(3);
1024 VALUE base_heading_level = INT2NUM(0);
1026 // process options hash (override defaults)
1027 if (!NIL_P(options) && TYPE(options) == T_HASH)
1029 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1030 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1031 autolink = OVERRIDE_IF_SET(autolink);
1032 line_ending = OVERRIDE_IF_SET(line_ending);
1033 external_link_class = OVERRIDE_IF_SET(external_link_class);
1034 external_link_rel = OVERRIDE_IF_SET(external_link_rel);
1035 mailto_class = OVERRIDE_IF_SET(mailto_class);
1036 link_proc = OVERRIDE_IF_SET(link_proc);
1037 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1038 img_prefix = OVERRIDE_IF_SET(img_prefix);
1039 output_style = OVERRIDE_IF_SET(output_style);
1040 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1041 pre_code = OVERRIDE_IF_SET(pre_code);
1042 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1043 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1046 // no need to call super here; rb_call_super()
1047 rb_iv_set(self, "@autolink", autolink);
1048 rb_iv_set(self, "@line_ending", line_ending);
1049 rb_iv_set(self, "@external_link_class", external_link_class);
1050 rb_iv_set(self, "@external_link_rel", external_link_rel);
1051 rb_iv_set(self, "@mailto_class", mailto_class);
1052 rb_iv_set(self, "@link_proc", link_proc);
1053 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1054 rb_iv_set(self, "@img_prefix", img_prefix);
1055 rb_iv_set(self, "@output_style", output_style);
1056 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1057 rb_iv_set(self, "@pre_code", pre_code);
1058 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1059 rb_iv_set(self, "@base_heading_level", base_heading_level);
1063 // convert a Ruby object (:xml, :html etc) into an int output style
1064 int Wikitext_output_style(VALUE output)
1066 if (TYPE(output) == T_SYMBOL)
1068 if (SYM2ID(output) == rb_intern("xml"))
1071 return HTML_OUTPUT; // fall back to default
1074 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1076 // process arguments
1077 VALUE string, options;
1078 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1082 string = StringValue(string);
1084 // access these once per parse
1085 VALUE line_ending = rb_iv_get(self, "@line_ending");
1086 line_ending = StringValue(line_ending);
1087 VALUE link_class = rb_iv_get(self, "@external_link_class");
1088 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1089 VALUE link_rel = rb_iv_get(self, "@external_link_rel");
1090 link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
1091 VALUE link_proc = rb_iv_get(self, "@link_proc");
1092 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1093 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1094 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1095 int output_style = Wikitext_output_style(rb_iv_get(self, "@output_style"));
1097 // process options hash
1098 int base_indent = 0;
1099 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1100 if (!NIL_P(options) && TYPE(options) == T_HASH)
1102 // :indent => 0 (or more)
1103 ID has_key = rb_intern("has_key?");
1104 ID id = ID2SYM(rb_intern("indent"));
1105 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1107 VALUE indent = rb_hash_aref(options, id);
1108 if (indent == Qfalse)
1109 base_indent = -1; // indentation disabled
1112 base_indent = NUM2INT(indent);
1113 if (base_indent < 0)
1118 // :base_heading_level => 0/1/2/3/4/5/6
1119 id = ID2SYM(rb_intern("base_heading_level"));
1120 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1121 base_heading_level = NUM2INT(rb_hash_aref(options, id));
1123 // :external_link_rel => 'nofollow'
1124 id = ID2SYM(rb_intern("external_link_rel"));
1125 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1127 link_rel = rb_hash_aref(options, id);
1128 link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
1131 // :output_style => :html/:xml
1132 id = ID2SYM(rb_intern("output_style"));
1133 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1134 output_style = Wikitext_output_style(rb_hash_aref(options, id));
1136 // :link_proc => lambda { |link_target| ... }
1137 id = ID2SYM(rb_intern("link_proc"));
1138 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1139 link_proc = rb_hash_aref(options, id);
1142 // normalize, regardless of whether this came from instance variable or override
1143 if (base_heading_level < 0)
1144 base_heading_level = 0;
1145 if (base_heading_level > 6)
1146 base_heading_level = 6;
1149 char *p = RSTRING_PTR(string);
1150 long len = RSTRING_LEN(string);
1153 // set up parser struct to make passing parameters a little easier
1154 parser_t *parser = parser_new();
1155 GC_WRAP_PARSER(parser, parser_gc);
1156 parser->external_link_class = link_class;
1157 parser->external_link_rel = link_rel;
1158 parser->mailto_class = mailto_class;
1159 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1160 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1161 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1162 parser->pre_code = rb_iv_get(self, "@pre_code") == Qtrue ? true : false;
1163 parser->line_ending = str_new_from_string(line_ending);
1164 parser->base_indent = base_indent;
1165 parser->base_heading_level = base_heading_level;
1166 parser->output_style = output_style;
1168 // this simple looping design leads to a single enormous function,
1169 // but it's faster than doing actual recursive descent and also secure in the face of
1170 // malicious input that seeks to overflow the stack
1171 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1172 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1173 // than a straightforward looping translator like this one anyway
1175 _token.type = NO_TOKEN;
1176 token_t *token = NULL;
1179 // note that whenever we grab a token we push it into the line buffer
1180 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1181 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1183 // check to see if we have a token hanging around from a previous iteration of this loop
1186 if (_token.type == NO_TOKEN)
1188 // first time here (haven't started scanning yet)
1190 next_token(token, NULL, p, pe);
1191 ary_push(parser->line_buffer, token->type);
1197 int type = token->type;
1199 // can't declare new variables inside a switch statement, so predeclare them here
1200 long remove_strong = -1;
1201 long remove_em = -1;
1203 // general purpose counters, flags and pointers
1207 str_t *output = NULL;
1209 str_t *token_str = &_token_str;
1211 // The following giant switch statement contains cases for all the possible token types.
1212 // In the most basic sense we are emitting the HTML that corresponds to each token,
1213 // but some tokens require context information in order to decide what to output.
1214 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1215 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1217 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1218 // - the line buffer (records tokens seen so far on the current line)
1219 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1221 // Although this is fairly complicated, there is one key simplifying factor:
1222 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1223 // scope stack (up to the current token) is valid; our translator can take this as a given.
1224 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1225 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1229 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1231 str_append(parser->output, space, sizeof(space) - 1);
1234 else if (IN(BLOCKQUOTE_START))
1236 // this kind of nesting not allowed (to avoid user confusion)
1237 wiki_pop_excess_elements(parser);
1238 wiki_start_para_if_necessary(parser);
1239 output = parser->capture ? parser->capture : parser->output;
1240 str_append(output, space, sizeof(space) - 1);
1244 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1245 ary_push(parser->line, PRE);
1246 i = ary_count(parser->line, BLOCKQUOTE);
1247 j = ary_count(parser->scope, BLOCKQUOTE);
1250 // must pop (reduce nesting level)
1251 for (i = j - i; i > 0; i--)
1252 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1257 parser->pending_crlf = false;
1258 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1259 wiki_indent(parser);
1260 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1261 if (parser->pre_code)
1262 str_append(parser->output, code_start, sizeof(code_start) - 1);
1263 ary_push(parser->scope, PRE);
1268 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1270 wiki_emit_pending_crlf_if_necessary(parser);
1271 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1273 else if (IN(BLOCKQUOTE_START))
1275 wiki_rollback_failed_link(parser); // if any
1276 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1277 wiki_append_pre_start(parser, token);
1279 else if (IN(BLOCKQUOTE))
1281 if (token->column_start == 1) // only allowed in first column
1283 wiki_rollback_failed_link(parser); // if any
1284 wiki_pop_all_from_stack(parser);
1285 wiki_append_pre_start(parser, token);
1287 else // PRE_START illegal here
1289 output = parser->capture ? parser->capture : parser->output;
1290 wiki_pop_excess_elements(parser);
1291 wiki_start_para_if_necessary(parser);
1292 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1297 wiki_rollback_failed_link(parser); // if any
1298 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1299 wiki_append_pre_start(parser, token);
1304 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1306 wiki_emit_pending_crlf_if_necessary(parser);
1307 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1312 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1315 output = parser->capture ? parser->capture : parser->output;
1316 wiki_pop_excess_elements(parser);
1317 wiki_start_para_if_necessary(parser);
1318 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1324 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1325 // no need to check for <pre>; can never appear inside it
1326 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1327 else if (IN(BLOCKQUOTE_START))
1329 // this kind of nesting not allowed (to avoid user confusion)
1330 wiki_pop_excess_elements(parser);
1331 wiki_start_para_if_necessary(parser);
1332 output = parser->capture ? parser->capture : parser->output;
1333 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1338 ary_push(parser->line, BLOCKQUOTE);
1340 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1341 i = ary_count(parser->line, BLOCKQUOTE);
1342 j = ary_count(parser->scope, BLOCKQUOTE);
1344 // 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
1345 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1347 ary_push(parser->line, BLOCKQUOTE);
1351 // now decide whether to push, pop or do nothing
1354 // must push (increase nesting level)
1355 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1356 for (i = i - j; i > 0; i--)
1358 wiki_indent(parser);
1359 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1360 str_append_str(parser->output, parser->line_ending);
1361 ary_push(parser->scope, BLOCKQUOTE);
1366 // must pop (reduce nesting level)
1367 for (i = j - i; i > 0; i--)
1368 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1371 // jump to top of the loop to process token we scanned during lookahead
1376 case BLOCKQUOTE_START:
1377 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1379 wiki_emit_pending_crlf_if_necessary(parser);
1380 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1382 else if (IN(BLOCKQUOTE_START))
1384 // nesting is fine here
1385 wiki_rollback_failed_link(parser); // if any
1386 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1387 wiki_indent(parser);
1388 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1389 str_append_str(parser->output, parser->line_ending);
1390 ary_push(parser->scope, BLOCKQUOTE_START);
1391 ary_push(parser->line, BLOCKQUOTE_START);
1393 else if (IN(BLOCKQUOTE))
1395 if (token->column_start == 1) // only allowed in first column
1397 wiki_rollback_failed_link(parser); // if any
1398 wiki_pop_all_from_stack(parser);
1399 wiki_indent(parser);
1400 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1401 str_append_str(parser->output, parser->line_ending);
1402 ary_push(parser->scope, BLOCKQUOTE_START);
1403 ary_push(parser->line, BLOCKQUOTE_START);
1405 else // BLOCKQUOTE_START illegal here
1407 output = parser->capture ? parser->capture : parser->output;
1408 wiki_pop_excess_elements(parser);
1409 wiki_start_para_if_necessary(parser);
1410 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1415 // would be nice to eliminate the repetition here but it's probably the clearest way
1416 wiki_rollback_failed_link(parser); // if any
1417 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1418 wiki_indent(parser);
1419 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1420 str_append_str(parser->output, parser->line_ending);
1421 ary_push(parser->scope, BLOCKQUOTE_START);
1422 ary_push(parser->line, BLOCKQUOTE_START);
1426 case BLOCKQUOTE_END:
1427 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1429 wiki_emit_pending_crlf_if_necessary(parser);
1430 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1434 if (IN(BLOCKQUOTE_START))
1435 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1438 output = parser->capture ? parser->capture : parser->output;
1439 wiki_pop_excess_elements(parser);
1440 wiki_start_para_if_necessary(parser);
1441 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1447 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1449 wiki_emit_pending_crlf_if_necessary(parser);
1450 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1454 wiki_pop_excess_elements(parser);
1455 wiki_start_para_if_necessary(parser);
1456 ary_push(parser->scope, NO_WIKI_START);
1457 ary_push(parser->line, NO_WIKI_START);
1462 if (IN(NO_WIKI_START))
1463 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1464 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1467 wiki_pop_excess_elements(parser);
1468 wiki_start_para_if_necessary(parser);
1469 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1474 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1476 wiki_emit_pending_crlf_if_necessary(parser);
1477 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1481 output = parser->capture ? parser->capture : parser->output;
1482 wiki_pop_excess_elements(parser);
1484 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1485 // otherwise, must open them
1488 j = parser->scope->count;
1489 for (j = j - 1; j >= 0; j--)
1491 int val = ary_entry(parser->scope, (int)j);
1492 if (val == STRONG || val == STRONG_START)
1494 str_append(output, strong_end, sizeof(strong_end) - 1);
1497 else if (val == EM || val == EM_START)
1499 str_append(output, em_end, sizeof(em_end) - 1);
1504 if (remove_strong > remove_em) // must remove strong first
1506 ary_pop(parser->scope);
1508 ary_pop(parser->scope);
1509 else // there was no em to remove!, so consider this an opening em tag
1511 str_append(output, em_start, sizeof(em_start) - 1);
1512 ary_push(parser->scope, EM);
1513 ary_push(parser->line, EM);
1516 else if (remove_em > remove_strong) // must remove em first
1518 ary_pop(parser->scope);
1519 if (remove_strong > -1)
1520 ary_pop(parser->scope);
1521 else // there was no strong to remove!, so consider this an opening strong tag
1523 str_append(output, strong_start, sizeof(strong_start) - 1);
1524 ary_push(parser->scope, STRONG);
1525 ary_push(parser->line, STRONG);
1528 else // no strong or em to remove, so this must be a new opening of both
1530 wiki_start_para_if_necessary(parser);
1531 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1532 ary_push(parser->scope, STRONG);
1533 ary_push(parser->line, STRONG);
1534 ary_push(parser->scope, EM);
1535 ary_push(parser->line, EM);
1540 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1542 wiki_emit_pending_crlf_if_necessary(parser);
1543 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1547 output = parser->capture ? parser->capture : parser->output;
1548 if (IN(STRONG_START))
1549 // already in span started with <strong>, no choice but to emit this literally
1550 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1551 else if (IN(STRONG))
1552 // STRONG already seen, this is a closing tag
1553 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1556 // this is a new opening
1557 wiki_pop_excess_elements(parser);
1558 wiki_start_para_if_necessary(parser);
1559 str_append(output, strong_start, sizeof(strong_start) - 1);
1560 ary_push(parser->scope, STRONG);
1561 ary_push(parser->line, STRONG);
1567 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1569 wiki_emit_pending_crlf_if_necessary(parser);
1570 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1574 output = parser->capture ? parser->capture : parser->output;
1575 if (IN_EITHER_OF(STRONG_START, STRONG))
1576 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1579 wiki_pop_excess_elements(parser);
1580 wiki_start_para_if_necessary(parser);
1581 str_append(output, strong_start, sizeof(strong_start) - 1);
1582 ary_push(parser->scope, STRONG_START);
1583 ary_push(parser->line, STRONG_START);
1589 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1591 wiki_emit_pending_crlf_if_necessary(parser);
1592 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1596 output = parser->capture ? parser->capture : parser->output;
1597 if (IN(STRONG_START))
1598 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1601 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1602 wiki_pop_excess_elements(parser);
1603 wiki_start_para_if_necessary(parser);
1604 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1610 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1612 wiki_emit_pending_crlf_if_necessary(parser);
1613 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1617 output = parser->capture ? parser->capture : parser->output;
1619 // already in span started with <em>, no choice but to emit this literally
1620 str_append(output, literal_em, sizeof(literal_em) - 1);
1622 // EM already seen, this is a closing tag
1623 wiki_pop_from_stack_up_to(parser, output, EM, true);
1626 // this is a new opening
1627 wiki_pop_excess_elements(parser);
1628 wiki_start_para_if_necessary(parser);
1629 str_append(output, em_start, sizeof(em_start) - 1);
1630 ary_push(parser->scope, EM);
1631 ary_push(parser->line, EM);
1637 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1639 wiki_emit_pending_crlf_if_necessary(parser);
1640 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1644 output = parser->capture ? parser->capture : parser->output;
1645 if (IN_EITHER_OF(EM_START, EM))
1646 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1649 wiki_pop_excess_elements(parser);
1650 wiki_start_para_if_necessary(parser);
1651 str_append(output, em_start, sizeof(em_start) - 1);
1652 ary_push(parser->scope, EM_START);
1653 ary_push(parser->line, EM_START);
1659 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1661 wiki_emit_pending_crlf_if_necessary(parser);
1662 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1666 output = parser->capture ? parser->capture : parser->output;
1668 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1671 // no EM_START in scope, so must interpret the EM_END without any special meaning
1672 wiki_pop_excess_elements(parser);
1673 wiki_start_para_if_necessary(parser);
1674 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1680 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1682 wiki_emit_pending_crlf_if_necessary(parser);
1683 str_append(parser->output, backtick, sizeof(backtick) - 1);
1687 output = parser->capture ? parser->capture : parser->output;
1689 // already in span started with <tt>, no choice but to emit this literally
1690 str_append(output, backtick, sizeof(backtick) - 1);
1692 // TT (`) already seen, this is a closing tag
1693 wiki_pop_from_stack_up_to(parser, output, TT, true);
1696 // this is a new opening
1697 wiki_pop_excess_elements(parser);
1698 wiki_start_para_if_necessary(parser);
1699 str_append(output, code_start, sizeof(code_start) - 1);
1700 ary_push(parser->scope, TT);
1701 ary_push(parser->line, TT);
1707 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1709 wiki_emit_pending_crlf_if_necessary(parser);
1710 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1714 output = parser->capture ? parser->capture : parser->output;
1715 if (IN_EITHER_OF(TT_START, TT))
1716 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1719 wiki_pop_excess_elements(parser);
1720 wiki_start_para_if_necessary(parser);
1721 str_append(output, code_start, sizeof(code_start) - 1);
1722 ary_push(parser->scope, TT_START);
1723 ary_push(parser->line, TT_START);
1729 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1731 wiki_emit_pending_crlf_if_necessary(parser);
1732 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1736 output = parser->capture ? parser->capture : parser->output;
1738 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1741 // no TT_START in scope, so must interpret the TT_END without any special meaning
1742 wiki_pop_excess_elements(parser);
1743 wiki_start_para_if_necessary(parser);
1744 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1751 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1753 // no need to check for PRE; can never appear inside it
1754 str_append(parser->output, token->start, TOKEN_LEN(token));
1758 // count number of tokens in line and scope stacks
1759 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1760 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1761 j = parser->scope->count - bq_count;
1764 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1768 if (type == OL || type == UL)
1771 if (i - k >= 2) // already seen at least one OL or UL
1773 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1778 ary_push(parser->line, type);
1779 ary_push(parser->line, LI);
1781 // want to compare line with scope but can only do so if scope has enough items on it
1784 if (ary_entry(parser->scope, (int)(i + bq_count - 2)) == type &&
1785 ary_entry(parser->scope, (int)(i + bq_count - 1)) == LI)
1787 // line and scope match at this point: do nothing yet
1791 // item just pushed onto line does not match corresponding slot of scope!
1792 for (; j >= i - 2; j--)
1793 // must pop back before emitting
1794 wiki_pop_from_stack(parser, NULL);
1796 // will emit UL or OL, then LI
1800 else // line stack size now exceeds scope stack size: must increase nesting level
1801 break; // will emit UL or OL, then LI
1805 // not a OL or UL token!
1807 // must close existing LI and re-open new one
1808 wiki_pop_from_stack(parser, NULL);
1811 // item just pushed onto line does not match corresponding slot of scope!
1813 // must pop back before emitting
1814 wiki_pop_from_stack(parser, NULL);
1822 if (type == OL || type == UL)
1824 // if LI is at the top of a stack this is the start of a nested list
1825 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1827 // so we should precede it with a CRLF, and indicate that it's a nested list
1828 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1829 ary_push(parser->scope, NESTED_LIST);
1833 // this is a new list
1834 if (IN(BLOCKQUOTE_START))
1835 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1837 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1841 wiki_indent(parser);
1843 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1844 else if (type == UL)
1845 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1846 ary_push(parser->scope, type);
1847 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1849 else if (type == SPACE)
1850 // silently throw away the optional SPACE token after final list marker
1853 wiki_indent(parser);
1854 str_append(parser->output, li_start, sizeof(li_start) - 1);
1855 ary_push(parser->scope, LI);
1857 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1858 if (type == OL || type == UL)
1861 while (k++, NEXT_TOKEN(), (type = token->type))
1863 if (type == OL || type == UL)
1864 str_append(parser->output, token->start, TOKEN_LEN(token));
1865 else if (type == SPACE && k == 1)
1867 // silently throw away the optional SPACE token after final list marker
1876 // jump to top of the loop to process token we scanned during lookahead
1885 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1887 // no need to check for PRE; can never appear inside it
1888 str_append(parser->output, token->start, TOKEN_LEN(token));
1892 // pop up to but not including the last BLOCKQUOTE on the scope stack
1893 if (IN(BLOCKQUOTE_START))
1894 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1896 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1898 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1899 ary_push(parser->line, type);
1900 i = ary_count(parser->line, BLOCKQUOTE);
1901 j = ary_count(parser->scope, BLOCKQUOTE);
1903 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1906 // must pop (reduce nesting level)
1907 for (i = j - i; i > 0; i--)
1908 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1911 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1912 while (NEXT_TOKEN(), (token->type == SPACE))
1915 ary_push(parser->scope, type);
1916 wiki_indent(parser);
1918 // take base_heading_level into account
1919 type += base_heading_level;
1920 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1923 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1924 if (type == H6_START)
1925 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1926 else if (type == H5_START)
1927 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1928 else if (type == H4_START)
1929 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1930 else if (type == H3_START)
1931 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1932 else if (type == H2_START)
1933 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1934 else if (type == H1_START)
1935 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1937 // jump to top of the loop to process token we scanned during lookahead
1946 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1948 wiki_emit_pending_crlf_if_necessary(parser);
1949 str_append(parser->output, token->start, TOKEN_LEN(token));
1953 wiki_rollback_failed_external_link(parser); // if any
1954 if ((type == H6_END && !IN(H6_START)) ||
1955 (type == H5_END && !IN(H5_START)) ||
1956 (type == H4_END && !IN(H4_START)) ||
1957 (type == H3_END && !IN(H3_START)) ||
1958 (type == H2_END && !IN(H2_START)) ||
1959 (type == H1_END && !IN(H1_START)))
1961 // literal output only if not in appropriate scope (we stay silent in that case)
1962 wiki_start_para_if_necessary(parser);
1963 str_append(parser->output, token->start, TOKEN_LEN(token));
1969 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1971 wiki_emit_pending_crlf_if_necessary(parser);
1972 str_append(parser->output, token->start, TOKEN_LEN(token));
1974 else if (IN(EXT_LINK_START))
1975 // must be capturing and this must be part of the link text
1976 str_append(parser->capture, token->start, TOKEN_LEN(token));
1979 wiki_pop_excess_elements(parser);
1980 wiki_start_para_if_necessary(parser);
1981 token_str->ptr = token->start;
1982 token_str->len = TOKEN_LEN(token);
1983 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, Qnil, true);
1988 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 token_str->ptr = token->start;
1993 token_str->len = TOKEN_LEN(token);
1994 wiki_append_sanitized_link_target(token_str, parser->output, false);
1996 else if (IN(LINK_START))
1998 // if the URI were allowed it would have been handled already in LINK_START
1999 wiki_rollback_failed_internal_link(parser);
2000 token_str->ptr = token->start;
2001 token_str->len = TOKEN_LEN(token);
2002 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2004 else if (IN(EXT_LINK_START))
2006 if (parser->link_target->len == 0)
2008 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2009 token_str->ptr = token->start;
2010 token_str->len = TOKEN_LEN(token);
2012 if (token->type == SPACE)
2014 ary_push(parser->scope, SPACE);
2015 str_append_str(parser->link_target, token_str);
2016 str_clear(parser->link_text);
2017 parser->capture = parser->link_text;
2018 token = NULL; // silently consume space
2022 // didn't see the space! this must be an error
2023 wiki_pop_from_stack(parser, NULL);
2024 wiki_pop_excess_elements(parser);
2025 wiki_start_para_if_necessary(parser);
2026 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2027 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2033 token_str->ptr = token->start;
2034 token_str->len = TOKEN_LEN(token);
2035 wiki_append_sanitized_link_target(token_str, parser->link_text, false);
2040 wiki_pop_excess_elements(parser);
2041 wiki_start_para_if_necessary(parser);
2042 token_str->ptr = token->start;
2043 token_str->len = TOKEN_LEN(token);
2044 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2049 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2051 wiki_emit_pending_crlf_if_necessary(parser);
2052 str_append(parser->output, token->start, TOKEN_LEN(token));
2054 else if (IN(EXT_LINK_START))
2056 if (parser->link_target->len == 0)
2058 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2059 token_str->ptr = token->start;
2060 token_str->len = TOKEN_LEN(token);
2062 if (token->type == SPACE)
2064 ary_push(parser->scope, PATH);
2065 ary_push(parser->scope, SPACE);
2066 str_append_str(parser->link_target, token_str);
2067 str_clear(parser->link_text);
2068 parser->capture = parser->link_text;
2069 token = NULL; // silently consume space
2073 // didn't see the space! this must be an error
2074 wiki_pop_from_stack(parser, NULL);
2075 wiki_pop_excess_elements(parser);
2076 wiki_start_para_if_necessary(parser);
2077 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2078 str_append_str(parser->output, token_str);
2083 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2087 output = parser->capture ? parser->capture : parser->output;
2088 wiki_pop_excess_elements(parser);
2089 wiki_start_para_if_necessary(parser);
2090 str_append(output, token->start, TOKEN_LEN(token));
2094 // internal links (links to other wiki articles) look like this:
2095 // [[another article]] (would point at, for example, "/wiki/another_article")
2096 // [[the other article|the link text we'll use for it]]
2097 // [[the other article | the link text we'll use for it]]
2098 // MediaWiki has strict requirements about what it will accept as a link target:
2099 // all wikitext markup is disallowed:
2100 // example [[foo ''bar'' baz]]
2101 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2102 // example [[foo <em>bar</em> baz]]
2103 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2104 // example [[foo <nowiki>''</nowiki> baz]]
2105 // renders [[foo '' baz]] (ie. not a link)
2106 // example [[foo <bar> baz]]
2107 // renders [[foo <bar> baz]] (ie. not a link)
2108 // HTML entities and non-ASCII, however, make it through:
2109 // example [[foo €]]
2110 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2111 // example [[foo €]]
2112 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2113 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2114 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2115 // everything else will be rejected
2117 output = parser->capture ? parser->capture : parser->output;
2118 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2120 wiki_emit_pending_crlf_if_necessary(parser);
2121 str_append(output, link_start, sizeof(link_start) - 1);
2123 else if (IN(EXT_LINK_START))
2124 // already in external link scope! (and in fact, must be capturing link_text right now)
2125 str_append(output, link_start, sizeof(link_start) - 1);
2126 else if (IN(LINK_START))
2128 // already in internal link scope! this is a syntax error
2129 wiki_rollback_failed_internal_link(parser);
2130 str_append(parser->output, link_start, sizeof(link_start) - 1);
2132 else if (IN(SEPARATOR))
2134 // scanning internal link text
2136 else // not in internal link scope yet
2138 // will either emit a link, or the rollback of a failed link, so start the para now
2139 wiki_pop_excess_elements(parser);
2140 wiki_start_para_if_necessary(parser);
2141 ary_push(parser->scope, LINK_START);
2143 // look ahead and try to gobble up link target
2144 while (NEXT_TOKEN(), (type = token->type))
2146 if (type == SPACE ||
2147 type == SPECIAL_URI_CHARS ||
2149 type == PRINTABLE ||
2153 type == QUOT_ENTITY ||
2155 type == AMP_ENTITY ||
2156 type == IMG_START ||
2158 type == LEFT_CURLY ||
2159 type == RIGHT_CURLY)
2161 // accumulate these tokens into link_target
2162 if (parser->link_target->len == 0)
2164 str_clear(parser->link_target);
2165 parser->capture = parser->link_target;
2167 if (type == QUOT_ENTITY)
2168 // don't insert the entity, insert the literal quote
2169 str_append(parser->link_target, quote, sizeof(quote) - 1);
2170 else if (type == AMP_ENTITY)
2171 // don't insert the entity, insert the literal ampersand
2172 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2174 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2176 else if (type == LINK_END)
2178 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2179 wiki_rollback_failed_internal_link(parser);
2180 break; // jump back to top of loop (will handle this in LINK_END case below)
2182 else if (type == SEPARATOR)
2184 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2185 wiki_rollback_failed_internal_link(parser);
2188 ary_push(parser->scope, SEPARATOR);
2189 str_clear(parser->link_text);
2190 parser->capture = parser->link_text;
2195 else // unexpected token (syntax error)
2197 wiki_rollback_failed_internal_link(parser);
2198 break; // jump back to top of loop to handle unexpected token
2202 // jump to top of the loop to process token we scanned during lookahead (if any)
2208 output = parser->capture ? parser->capture : parser->output;
2209 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2211 wiki_emit_pending_crlf_if_necessary(parser);
2212 str_append(output, link_end, sizeof(link_end) - 1);
2214 else if (IN(EXT_LINK_START))
2215 // already in external link scope! (and in fact, must be capturing link_text right now)
2216 str_append(output, link_end, sizeof(link_end) - 1);
2217 else if (IN(LINK_START)) // in internal link scope!
2219 if (wiki_blank(parser->link_target))
2221 // special case for inputs like "[[ ]]"
2222 wiki_rollback_failed_internal_link(parser);
2223 str_append(parser->output, link_end, sizeof(link_end) - 1);
2226 if (parser->link_text->len == 0 ||
2227 wiki_blank(parser->link_text))
2229 // use link target as link text
2230 str_clear(parser->link_text);
2231 wiki_append_sanitized_link_target(parser->link_target, parser->link_text, true);
2234 wiki_trim_link_text(parser);
2236 // perform "redlink" check before manipulating link_target
2237 if (NIL_P(link_proc))
2241 j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
2244 VALUE l = j; // can't cast inside StringValue macro
2248 wiki_encode_link_target(parser);
2249 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2250 parser->capture = NULL;
2251 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, Qnil, false);
2252 str_clear(parser->link_target);
2253 str_clear(parser->link_text);
2255 else // wasn't in internal link scope
2257 wiki_pop_excess_elements(parser);
2258 wiki_start_para_if_necessary(parser);
2259 str_append(output, link_end, sizeof(link_end) - 1);
2263 // external links look like this:
2264 // [http://google.com/ the link text]
2265 // [/other/page/on/site see this page]
2266 // strings in square brackets which don't match this syntax get passed through literally; eg:
2267 // he was very angery [sic] about the turn of events
2268 case EXT_LINK_START:
2269 output = parser->capture ? parser->capture : parser->output;
2270 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2272 wiki_emit_pending_crlf_if_necessary(parser);
2273 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2275 else if (IN(EXT_LINK_START))
2276 // already in external link scope! (and in fact, must be capturing link_text right now)
2277 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2278 else if (IN(LINK_START))
2280 // already in internal link scope!
2281 if (parser->link_target->len == 0 || !IN(SPACE))
2282 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2283 else // link target has already been scanned
2284 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2286 else // not in external link scope yet
2288 // will either emit a link, or the rollback of a failed link, so start the para now
2289 wiki_pop_excess_elements(parser);
2290 wiki_start_para_if_necessary(parser);
2292 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2294 if (token->type == URI || token->type == PATH)
2295 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2297 // only get here if there was a syntax error (missing URI)
2298 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2299 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2304 output = parser->capture ? parser->capture : parser->output;
2305 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2307 wiki_emit_pending_crlf_if_necessary(parser);
2308 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2310 else if (IN(EXT_LINK_START))
2312 if (parser->link_text->len == 0)
2313 // syntax error: external link with no link text
2314 wiki_rollback_failed_external_link(parser);
2318 j = IN(PATH) ? Qnil : parser->external_link_class;
2319 k = IN(PATH) ? Qnil : parser->external_link_rel;
2320 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2321 parser->capture = NULL;
2322 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, k, false);
2324 str_clear(parser->link_target);
2325 str_clear(parser->link_text);
2329 wiki_pop_excess_elements(parser);
2330 wiki_start_para_if_necessary(parser);
2331 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2336 output = parser->capture ? parser->capture : parser->output;
2337 wiki_pop_excess_elements(parser);
2338 wiki_start_para_if_necessary(parser);
2339 str_append(output, separator, sizeof(separator) - 1);
2343 output = parser->capture ? parser->capture : parser->output;
2344 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2346 wiki_emit_pending_crlf_if_necessary(parser);
2347 str_append(output, token->start, TOKEN_LEN(token));
2351 // peek ahead to see next token
2352 char *token_ptr = token->start;
2353 long token_len = TOKEN_LEN(token);
2356 if ((type == H6_END && IN(H6_START)) ||
2357 (type == H5_END && IN(H5_START)) ||
2358 (type == H4_END && IN(H4_START)) ||
2359 (type == H3_END && IN(H3_START)) ||
2360 (type == H2_END && IN(H2_START)) ||
2361 (type == H1_END && IN(H1_START)))
2363 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2368 wiki_pop_excess_elements(parser);
2369 wiki_start_para_if_necessary(parser);
2370 str_append(output, token_ptr, token_len);
2373 // jump to top of the loop to process token we scanned during lookahead
2381 case DECIMAL_ENTITY:
2382 // pass these through unaltered as they are case sensitive
2383 output = parser->capture ? parser->capture : parser->output;
2384 wiki_pop_excess_elements(parser);
2385 wiki_start_para_if_necessary(parser);
2386 str_append(output, token->start, TOKEN_LEN(token));
2390 // normalize hex entities (downcase them)
2391 output = parser->capture ? parser->capture : parser->output;
2392 wiki_pop_excess_elements(parser);
2393 wiki_start_para_if_necessary(parser);
2394 str_append(output, token->start, TOKEN_LEN(token));
2395 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2399 output = parser->capture ? parser->capture : parser->output;
2400 wiki_pop_excess_elements(parser);
2401 wiki_start_para_if_necessary(parser);
2402 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2406 output = parser->capture ? parser->capture : parser->output;
2407 wiki_pop_excess_elements(parser);
2408 wiki_start_para_if_necessary(parser);
2409 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2413 output = parser->capture ? parser->capture : parser->output;
2414 wiki_pop_excess_elements(parser);
2415 wiki_start_para_if_necessary(parser);
2416 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2420 output = parser->capture ? parser->capture : parser->output;
2421 wiki_pop_excess_elements(parser);
2422 wiki_start_para_if_necessary(parser);
2423 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2427 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2429 wiki_emit_pending_crlf_if_necessary(parser);
2430 str_append(parser->output, token->start, TOKEN_LEN(token));
2432 else if (parser->capture)
2433 str_append(parser->capture, token->start, TOKEN_LEN(token));
2436 // not currently capturing: will be emitting something on success or failure, so get ready
2437 wiki_pop_excess_elements(parser);
2438 wiki_start_para_if_necessary(parser);
2440 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2441 // will cheat here and abuse the link_target capture buffer to accumulate text
2442 while (NEXT_TOKEN(), (type = token->type))
2444 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2445 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2446 else if (type == IMG_END && parser->link_target->len > 0)
2449 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2453 else // unexpected token or zero-length target (syntax error)
2456 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2457 if (parser->link_target->len > 0)
2458 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2463 // jump to top of the loop to process token we scanned during lookahead
2464 str_clear(parser->link_target);
2470 i = parser->pending_crlf;
2471 parser->pending_crlf = false;
2472 wiki_rollback_failed_link(parser); // if any
2473 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2475 ary_clear(parser->line_buffer);
2476 str_append_str(parser->output, parser->line_ending);
2481 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2482 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2483 // don't emit in this case
2484 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2487 if (ary_entry(parser->line_buffer, -2) == PRE)
2489 // only thing on line is the PRE: emit pending line ending (if we had one)
2491 str_append_str(parser->output, parser->line_ending);
2494 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2495 ary_clear(parser->line);
2496 ary_clear(parser->line_buffer);
2498 // peek ahead to see if this is definitely the end of the PRE block
2501 if (type != BLOCKQUOTE && type != PRE)
2502 // this is definitely the end of the block, so don't emit
2503 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2505 // potentially will emit
2506 parser->pending_crlf = true;
2508 continue; // jump back to top of loop to handle token grabbed via lookahead
2513 parser->pending_crlf = true;
2515 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2516 // as a side effect, this handles any open span-level elements and unclosed blocks
2517 // (with special handling for P blocks and LI elements)
2518 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2519 for (j = parser->scope->count; j > i; j--)
2521 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2523 parser->pending_crlf = false;
2527 // special handling on last iteration through the loop if the top item on the scope is a P block
2528 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2530 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2531 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2532 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2533 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2534 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2536 parser->pending_crlf = false;
2538 // not a paragraph break!
2541 wiki_pop_from_stack(parser, NULL);
2545 // delete the entire contents of the line scope stack and buffer
2546 ary_clear(parser->line);
2547 ary_clear(parser->line_buffer);
2550 case SPECIAL_URI_CHARS:
2556 output = parser->capture ? parser->capture : parser->output;
2557 wiki_pop_excess_elements(parser);
2558 wiki_start_para_if_necessary(parser);
2559 str_append(output, token->start, TOKEN_LEN(token));
2563 output = parser->capture ? parser->capture : parser->output;
2564 wiki_pop_excess_elements(parser);
2565 wiki_start_para_if_necessary(parser);
2566 wiki_append_entity_from_utf32_char(output, token->code_point);
2570 // special case for input like " foo\n " (see pre_spec.rb)
2572 ary_entry(parser->line_buffer, -2) == PRE &&
2573 parser->pending_crlf)
2574 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2576 // close any open scopes on hitting EOF
2577 wiki_rollback_failed_link(parser); // if any
2578 wiki_pop_all_from_stack(parser);
2579 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2585 // reset current token; forcing lexer to return another token at the top of the loop
2589 // nasty hack to avoid re-allocating our return value
2590 str_append(parser->output, null_str, 1); // null-terminate
2591 len = parser->output->len - 1; // don't count null termination
2593 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2594 free(RSTRING_PTR(out));
2595 RSTRING(out)->as.heap.aux.capa = len;
2596 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2597 RSTRING(out)->as.heap.len = len;
2598 parser->output->ptr = NULL; // don't double-free