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;
66 const char null_str[] = { 0 };
67 const char escaped_no_wiki_start[] = "<nowiki>";
68 const char escaped_no_wiki_end[] = "</nowiki>";
69 const char literal_strong_em[] = "'''''";
70 const char literal_strong[] = "'''";
71 const char literal_em[] = "''";
72 const char escaped_em_start[] = "<em>";
73 const char escaped_em_end[] = "</em>";
74 const char escaped_strong_start[] = "<strong>";
75 const char escaped_strong_end[] = "</strong>";
76 const char escaped_tt_start[] = "<tt>";
77 const char escaped_tt_end[] = "</tt>";
78 const char pre_start[] = "<pre>";
79 const char pre_end[] = "</pre>";
80 const char escaped_pre_start[] = "<pre>";
81 const char escaped_pre_end[] = "</pre>";
82 const char blockquote_start[] = "<blockquote>";
83 const char blockquote_end[] = "</blockquote>";
84 const char escaped_blockquote_start[] = "<blockquote>";
85 const char escaped_blockquote_end[] = "</blockquote>";
86 const char strong_em_start[] = "<strong><em>";
87 const char strong_start[] = "<strong>";
88 const char strong_end[] = "</strong>";
89 const char em_start[] = "<em>";
90 const char em_end[] = "</em>";
91 const char code_start[] = "<code>";
92 const char code_end[] = "</code>";
93 const char ol_start[] = "<ol>";
94 const char ol_end[] = "</ol>";
95 const char ul_start[] = "<ul>";
96 const char ul_end[] = "</ul>";
97 const char li_start[] = "<li>";
98 const char li_end[] = "</li>";
99 const char h6_start[] = "<h6>";
100 const char h6_end[] = "</h6>";
101 const char h5_start[] = "<h5>";
102 const char h5_end[] = "</h5>";
103 const char h4_start[] = "<h4>";
104 const char h4_end[] = "</h4>";
105 const char h3_start[] = "<h3>";
106 const char h3_end[] = "</h3>";
107 const char h2_start[] = "<h2>";
108 const char h2_end[] = "</h2>";
109 const char h1_start[] = "<h1>";
110 const char h1_end[] = "</h1>";
111 const char p_start[] = "<p>";
112 const char p_end[] = "</p>";
113 const char space[] = " ";
114 const char a_start[] = "<a href=\"";
115 const char a_class[] = "\" class=\"";
116 const char a_rel[] = "\" rel=\"";
117 const char a_start_close[] = "\">";
118 const char a_end[] = "</a>";
119 const char link_start[] = "[[";
120 const char link_end[] = "]]";
121 const char separator[] = "|";
122 const char ext_link_start[] = "[";
123 const char backtick[] = "`";
124 const char quote[] = "\"";
125 const char ampersand[] = "&";
126 const char quot_entity[] = """;
127 const char amp_entity[] = "&";
128 const char lt_entity[] = "<";
129 const char gt_entity[] = ">";
130 const char escaped_blockquote[] = "> ";
131 const char ext_link_end[] = "]";
132 const char literal_img_start[] = "{{";
133 const char img_start[] = "<img src=\"";
134 const char img_end_xml[] = "\" />";
135 const char img_end_html[] = "\">";
136 const char img_alt[] = "\" alt=\"";
137 const char pre_class_start[] = "<pre class=\"";
138 const char pre_class_end[] = "-syntax\">";
140 // Mark the parser struct designated by ptr as a participant in Ruby's
141 // mark-and-sweep garbage collection scheme. A variable named name is placed on
142 // the C stack to prevent the structure from being prematurely collected.
143 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
145 parser_t *parser_new(void)
147 parser_t *parser = ALLOC_N(parser_t, 1);
148 parser->capture = NULL; // not a real instance, pointer to other member's instance
149 parser->output = str_new();
150 parser->link_target = str_new();
151 parser->link_text = str_new();
152 parser->line_ending = NULL; // caller should set up
153 parser->tabulation = str_new();
154 parser->scope = ary_new();
155 parser->line = ary_new();
156 parser->line_buffer = ary_new();
157 parser->external_link_class = Qnil; // caller should set up
158 parser->external_link_rel = Qnil; // caller should set up
159 parser->mailto_class = Qnil; // caller should set up
160 parser->img_prefix = Qnil; // caller should set up
161 parser->output_style = HTML_OUTPUT;
162 parser->base_indent = 0;
163 parser->current_indent = 0;
164 parser->base_heading_level = 0;
165 parser->pending_crlf = false;
166 parser->autolink = true;
167 parser->space_to_underscore = true;
171 void parser_free(parser_t *parser)
173 // we don't free parser->capture; it's just a redundant pointer
174 if (parser->output) str_free(parser->output);
175 if (parser->link_target) str_free(parser->link_target);
176 if (parser->link_text) str_free(parser->link_text);
177 if (parser->line_ending) str_free(parser->line_ending);
178 if (parser->tabulation) str_free(parser->tabulation);
179 if (parser->scope) ary_free(parser->scope);
180 if (parser->line) ary_free(parser->line);
181 if (parser->line_buffer) ary_free(parser->line_buffer);
185 // for testing and debugging only
186 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
190 string = StringValue(string);
191 VALUE tokens = rb_ary_new();
192 char *p = RSTRING_PTR(string);
193 long len = RSTRING_LEN(string);
196 next_token(&token, NULL, p, pe);
197 rb_ary_push(tokens, wiki_token(&token));
198 while (token.type != END_OF_FILE)
200 next_token(&token, &token, NULL, pe);
201 rb_ary_push(tokens, wiki_token(&token));
206 // for benchmarking raw tokenization speed only
207 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
211 string = StringValue(string);
212 char *p = RSTRING_PTR(string);
213 long len = RSTRING_LEN(string);
216 next_token(&token, NULL, p, pe);
217 while (token.type != END_OF_FILE)
218 next_token(&token, &token, NULL, pe);
222 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
225 VALUE string, options;
226 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
230 string = StringValue(string);
231 VALUE tokens = rb_ary_new();
233 // check instance variables
234 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
236 // process options hash (can override instance variables)
237 if (!NIL_P(options) && TYPE(options) == T_HASH)
239 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
240 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
242 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
247 char *p = RSTRING_PTR(string);
248 long len = RSTRING_LEN(string);
251 token_t *_token = &token;
252 next_token(&token, NULL, p, pe);
253 while (token.type != END_OF_FILE)
260 if (TOKEN_LEN(_token) >= min_len)
261 rb_ary_push(tokens, TOKEN_TEXT(_token));
264 // ignore everything else
267 next_token(&token, &token, NULL, pe);
272 // we downcase "in place", overwriting the original contents of the buffer
273 void wiki_downcase_bang(char *ptr, long len)
275 for (long i = 0; i < len; i++)
277 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
282 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
284 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
285 char scratch = (character & 0xf000) >> 12;
286 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
287 scratch = (character & 0x0f00) >> 8;
288 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
289 scratch = (character & 0x00f0) >> 4;
290 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
291 scratch = character & 0x000f;
292 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
293 str_append(output, hex_string, sizeof(hex_string));
296 // Convert a single UTF-8 codepoint to UTF-32
298 // Expects an input buffer, src, containing a UTF-8 encoded character (which
299 // may be multi-byte). The end of the input buffer, end, is also passed in to
300 // allow the detection of invalidly truncated codepoints. The number of bytes
301 // in the UTF-8 character (between 1 and 4) is returned by reference in
304 // Raises a RangeError if the supplied character is invalid UTF-8.
305 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
308 if ((unsigned char)src[0] <= 0x7f)
314 else if ((src[0] & 0xe0) == 0xc0)
316 // byte starts with 110..... : this should be a two-byte sequence
319 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
320 else if (((unsigned char)src[0] == 0xc0) ||
321 ((unsigned char)src[0] == 0xc1))
322 // overlong encoding: lead byte of 110..... but code point <= 127
323 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
324 else if ((src[1] & 0xc0) != 0x80 )
325 // should have second byte starting with 10......
326 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
329 ((uint32_t)(src[0] & 0x1f)) << 6 |
333 else if ((src[0] & 0xf0) == 0xe0)
335 // byte starts with 1110.... : this should be a three-byte sequence
337 // missing second or third byte
338 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
339 else if (((src[1] & 0xc0) != 0x80 ) ||
340 ((src[2] & 0xc0) != 0x80 ))
341 // should have second and third bytes starting with 10......
342 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
345 ((uint32_t)(src[0] & 0x0f)) << 12 |
346 ((uint32_t)(src[1] & 0x3f)) << 6 |
350 else if ((src[0] & 0xf8) == 0xf0)
352 // bytes starts with 11110... : this should be a four-byte sequence
354 // missing second, third, or fourth byte
355 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
356 else if ((unsigned char)src[0] >= 0xf5 &&
357 (unsigned char)src[0] <= 0xf7)
358 // disallowed by RFC 3629 (codepoints above 0x10ffff)
359 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
360 else if (((src[1] & 0xc0) != 0x80 ) ||
361 ((src[2] & 0xc0) != 0x80 ) ||
362 ((src[3] & 0xc0) != 0x80 ))
363 // should have second and third bytes starting with 10......
364 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
367 ((uint32_t)(src[0] & 0x07)) << 18 |
368 ((uint32_t)(src[1] & 0x3f)) << 12 |
369 ((uint32_t)(src[1] & 0x3f)) << 6 |
374 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
378 // - non-printable (non-ASCII) characters converted to numeric entities
379 // - QUOT and AMP characters converted to named entities
380 // - if trim is true, leading and trailing whitespace trimmed
381 // - if trim is false, there is no special treatment of spaces
382 void wiki_append_sanitized_link_target(str_t *link_target, str_t *output, bool trim)
384 char *src = link_target->ptr;
385 char *start = src; // remember this so we can check if we're at the start
386 char *non_space = output->ptr + output->len; // remember last non-space character output
387 char *end = src + link_target->len;
390 // need at most 8 bytes to display each input character (�)
391 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
393 char *old_ptr = output->ptr;
394 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
395 if (old_ptr != output->ptr) // may have moved
396 non_space += output->ptr - old_ptr;
401 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
402 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
404 else if (*src == '&')
406 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
407 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
409 else if (*src == '<' || *src == '>')
410 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
411 else if (*src == ' ' && src == start && trim)
412 start++; // we eat leading space
413 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
415 *(output->ptr + output->len) = *src;
418 else // all others: must convert to entities
421 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
423 non_space = output->ptr + output->len;
427 non_space = output->ptr + output->len;
431 // trim trailing space if necessary
432 if (trim && output->ptr + output->len != non_space)
433 output->len -= (output->ptr + output->len) - non_space;
436 // prepare hyperlink and append it to parser->output
437 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
438 // or merely the literal link target
439 // if link_text is Qnil, the link_target is re-used for the link text
440 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)
442 if (check_autolink && !parser->autolink)
443 wiki_append_sanitized_link_target(link_target, parser->output, true);
446 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
447 if (!NIL_P(link_prefix))
448 str_append_string(parser->output, link_prefix);
449 wiki_append_sanitized_link_target(link_target, parser->output, true);
451 // special handling for mailto URIs
452 const char *mailto = "mailto:";
453 long mailto_len = (long)sizeof(mailto) - 1; // don't count NUL byte
454 if ((link_target->len >= mailto_len &&
455 strncmp(mailto, link_target->ptr, mailto_len) == 0) ||
456 (!NIL_P(link_prefix) &&
457 RSTRING_LEN(link_prefix) >= mailto_len &&
458 strncmp(mailto, RSTRING_PTR(link_prefix), mailto_len) == 0))
459 link_class = parser->mailto_class; // use mailto_class from parser
460 if (link_class != Qnil)
462 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
463 str_append_string(parser->output, link_class);
465 if (link_rel != Qnil)
467 str_append(parser->output, a_rel, sizeof(a_rel) - 1); // " rel="
468 str_append_string(parser->output, link_rel);
470 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
471 if (!link_text || link_text->len == 0) // re-use link_target
472 wiki_append_sanitized_link_target(link_target, parser->output, true);
474 str_append_str(parser->output, link_text);
475 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
479 void wiki_append_img(parser_t *parser, char *token_ptr, long token_len)
481 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
482 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
483 str_append_string(parser->output, parser->img_prefix);
484 str_append(parser->output, token_ptr, token_len);
485 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
486 str_append(parser->output, token_ptr, token_len);
487 if (parser->output_style == XML_OUTPUT)
488 str_append(parser->output, img_end_xml, sizeof(img_end_xml) - 1); // " />
490 str_append(parser->output, img_end_html, sizeof(img_end_html) - 1); // ">
493 // will emit indentation only if we are about to emit any of:
494 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
495 // each time we enter one of those spans must ++ the indentation level
496 void wiki_indent(parser_t *parser)
498 if (parser->base_indent == -1) // indentation disabled
500 int space_count = parser->current_indent + parser->base_indent;
503 char *old_end, *new_end;
504 if (parser->tabulation->len < space_count)
505 str_grow(parser->tabulation, space_count); // reallocates if necessary
506 old_end = parser->tabulation->ptr + parser->tabulation->len;
507 new_end = parser->tabulation->ptr + space_count;
508 while (old_end < new_end)
510 if (space_count > parser->tabulation->len)
511 parser->tabulation->len = space_count;
512 str_append(parser->output, parser->tabulation->ptr, space_count);
514 parser->current_indent += 2;
517 void wiki_append_pre_start(parser_t *parser, token_t *token)
520 if ((size_t)TOKEN_LEN(token) > sizeof(pre_start) - 1)
522 str_append(parser->output, pre_class_start, sizeof(pre_class_start) - 1); // <pre class="
523 str_append(parser->output, token->start + 11, TOKEN_LEN(token) - 13); // (the "lang" substring)
524 str_append(parser->output, pre_class_end, sizeof(pre_class_end) - 1); // -syntax">
527 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
528 ary_push(parser->scope, PRE_START);
529 ary_push(parser->line, PRE_START);
532 void wiki_dedent(parser_t *parser, bool emit)
534 if (parser->base_indent == -1) // indentation disabled
536 parser->current_indent -= 2;
539 int space_count = parser->current_indent + parser->base_indent;
541 str_append(parser->output, parser->tabulation->ptr, space_count);
544 // Pops a single item off the parser's scope stack.
545 // A corresponding closing tag is written to the target string.
546 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
547 void wiki_pop_from_stack(parser_t *parser, str_t *target)
549 int top = ary_entry(parser->scope, -1);
553 target = parser->output;
555 // for headings, take base_heading_level into account
556 if (top >= H1_START && top <= H6_START)
558 top += parser->base_heading_level;
559 // no need to check for underflow (base_heading_level is never negative)
568 str_append(target, pre_end, sizeof(pre_end) - 1);
569 str_append_str(target, parser->line_ending);
570 wiki_dedent(parser, false);
574 case BLOCKQUOTE_START:
575 wiki_dedent(parser, true);
576 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
577 str_append_str(target, parser->line_ending);
581 // not a real HTML tag; so nothing to pop
586 str_append(target, strong_end, sizeof(strong_end) - 1);
591 str_append(target, em_end, sizeof(em_end) - 1);
596 str_append(target, code_end, sizeof(code_end) - 1);
600 wiki_dedent(parser, true);
601 str_append(target, ol_end, sizeof(ol_end) - 1);
602 str_append_str(target, parser->line_ending);
606 wiki_dedent(parser, true);
607 str_append(target, ul_end, sizeof(ul_end) - 1);
608 str_append_str(target, parser->line_ending);
612 // next token to pop will be a LI
613 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
614 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
615 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
616 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
617 wiki_dedent(parser, true); // we really only want to emit the spaces
618 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
622 str_append(target, li_end, sizeof(li_end) - 1);
623 str_append_str(target, parser->line_ending);
624 wiki_dedent(parser, false);
628 str_append(target, h6_end, sizeof(h6_end) - 1);
629 str_append_str(target, parser->line_ending);
630 wiki_dedent(parser, false);
634 str_append(target, h5_end, sizeof(h5_end) - 1);
635 str_append_str(target, parser->line_ending);
636 wiki_dedent(parser, false);
640 str_append(target, h4_end, sizeof(h4_end) - 1);
641 str_append_str(target, parser->line_ending);
642 wiki_dedent(parser, false);
646 str_append(target, h3_end, sizeof(h3_end) - 1);
647 str_append_str(target, parser->line_ending);
648 wiki_dedent(parser, false);
652 str_append(target, h2_end, sizeof(h2_end) - 1);
653 str_append_str(target, parser->line_ending);
654 wiki_dedent(parser, false);
658 str_append(target, h1_end, sizeof(h1_end) - 1);
659 str_append_str(target, parser->line_ending);
660 wiki_dedent(parser, false);
664 // not an HTML tag; so nothing to emit
668 // not an HTML tag; so nothing to emit
672 // not an HTML tag; so nothing to emit
676 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
680 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
684 str_append(target, p_end, sizeof(p_end) - 1);
685 str_append_str(target, parser->line_ending);
686 wiki_dedent(parser, false);
694 // should probably raise an exception here
697 ary_pop(parser->scope);
700 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
701 // If including is true then the item itself is also popped.
702 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
703 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
705 int continue_looping = 1;
708 int top = ary_entry(parser->scope, -1);
715 continue_looping = 0;
717 wiki_pop_from_stack(parser, target);
718 } while (continue_looping);
721 void wiki_pop_all_from_stack(parser_t *parser)
723 for (int i = 0, max = parser->scope->count; i < max; i++)
724 wiki_pop_from_stack(parser, NULL);
727 void wiki_start_para_if_necessary(parser_t *parser)
732 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
733 if (parser->scope->count == 0 ||
734 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
735 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
738 str_append(parser->output, p_start, sizeof(p_start) - 1);
739 ary_push(parser->scope, P);
740 ary_push(parser->line, P);
742 else if (parser->pending_crlf)
745 // already in a paragraph block; convert pending CRLF into a space
746 str_append(parser->output, space, sizeof(space) - 1);
748 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
749 str_append_str(parser->output, parser->line_ending);
751 parser->pending_crlf = false;
754 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
756 if (parser->pending_crlf)
758 str_append_str(parser->output, parser->line_ending);
759 parser->pending_crlf = false;
763 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
764 // For example, given input like:
769 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
770 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
775 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
776 // but not on the line scope:
781 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
782 // on the line scope.
783 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
784 // entering the for loop.
785 void wiki_pop_excess_elements(parser_t *parser)
789 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
791 // special case for last item on scope
794 // don't auto-pop P if it is only item on scope
795 if (ary_entry(parser->scope, -1) == P)
797 // add P to the line scope to prevent us entering the loop at all next time around
798 ary_push(parser->line, P);
802 wiki_pop_from_stack(parser, NULL);
806 // trim parser->link_text in place
807 void wiki_trim_link_text(parser_t *parser)
809 char *src = parser->link_text->ptr;
810 char *start = src; // remember this so we can check if we're at the start
812 char *non_space = src; // remember last non-space character output
813 char *end = src + parser->link_text->len;
825 if (left != start || non_space + 1 != end)
827 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
828 parser->link_text->len = (non_space + 1) - left;
829 memmove(parser->link_text->ptr, left, parser->link_text->len);
833 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
835 str_t *link_target = str_new_from_string(string);
836 GC_WRAP_STR(link_target, link_target_gc);
837 str_t *output = str_new();
838 GC_WRAP_STR(output, output_gc);
839 wiki_append_sanitized_link_target(link_target, output, true);
840 return string_from_str(output);
843 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
845 // Leading and trailing whitespace trimmed. Spaces are converted to
846 // underscores if the parser space_to_underscore member is true.
847 static void wiki_encode_link_target(parser_t *parser)
849 char *src = parser->link_target->ptr;
850 char *start = src; // remember this so we can check if we're at the start
851 long len = parser->link_target->len;
854 char *end = src + len;
855 long dest_len = len * 2;
856 char *dest = ALLOC_N(char, dest_len);
857 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
858 char *non_space = dest; // remember last non-space character output
859 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
860 for (; src < end; src++)
862 // worst case: a single character may grow to 3 characters once encoded
863 if ((dest + 3) > (dest_ptr + dest_len))
865 // outgrowing buffer, must reallocate
866 char *old_dest = dest;
867 char *old_dest_ptr = dest_ptr;
869 dest = realloc(dest_ptr, dest_len);
872 // would have used reallocf, but this has to run on Linux too, not just Darwin
874 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
877 dest = dest_ptr + (old_dest - old_dest_ptr);
878 non_space = dest_ptr + (non_space - old_dest_ptr);
881 // pass through unreserved characters
882 if ((*src >= 'a' && *src <= 'z') ||
883 (*src >= 'A' && *src <= 'Z') ||
884 (*src >= '0' && *src <= '9') ||
893 else if (*src == ' ' && src == start)
894 start++; // we eat leading space
895 else if (*src == ' ' && parser->space_to_underscore)
897 else // everything else gets URL-encoded
900 *dest++ = hex[(unsigned char)(*src) / 16]; // left
901 *dest++ = hex[(unsigned char)(*src) % 16]; // right
907 // trim trailing space if necessary
908 if (non_space > dest_ptr && dest != non_space)
909 dest_len = non_space - dest_ptr;
911 dest_len = dest - dest_ptr;
912 str_clear(parser->link_target);
913 str_append(parser->link_target, dest_ptr, dest_len);
917 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
920 parser.space_to_underscore = false;
921 parser.link_target = str_new_from_string(in);
922 GC_WRAP_STR(parser.link_target, link_target_gc);
923 wiki_encode_link_target(&parser);
924 return string_from_str(parser.link_target);
927 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
928 // returns 0 (false) otherwise
929 bool wiki_blank(str_t *str)
933 for (char *ptr = str->ptr,
934 *end = str->ptr + str->len;
943 void wiki_rollback_failed_internal_link(parser_t *parser)
946 return; // nothing to do!
947 int scope_includes_separator = IN(SEPARATOR);
948 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
949 str_append(parser->output, link_start, sizeof(link_start) - 1);
950 if (parser->link_target->len > 0)
952 wiki_append_sanitized_link_target(parser->link_target, parser->output, false);
953 if (scope_includes_separator)
955 str_append(parser->output, separator, sizeof(separator) - 1);
956 if (parser->link_text->len > 0)
957 str_append_str(parser->output, parser->link_text);
960 parser->capture = NULL;
961 str_clear(parser->link_target);
962 str_clear(parser->link_text);
965 void wiki_rollback_failed_external_link(parser_t *parser)
967 if (!IN(EXT_LINK_START))
968 return; // nothing to do!
970 // store a couple of values before popping
971 int scope_includes_space = IN(SPACE);
972 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
973 VALUE link_rel = IN(PATH) ? Qnil : parser->external_link_rel;
974 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
976 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
977 if (parser->link_target->len > 0)
979 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, link_rel, true);
980 if (scope_includes_space)
982 str_append(parser->output, space, sizeof(space) - 1);
983 if (parser->link_text->len > 0)
984 str_append_str(parser->output, parser->link_text);
987 parser->capture = NULL;
988 str_clear(parser->link_target);
989 str_clear(parser->link_text);
992 void wiki_rollback_failed_link(parser_t *parser)
994 wiki_rollback_failed_internal_link(parser);
995 wiki_rollback_failed_external_link(parser);
998 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
1000 // process arguments
1002 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
1006 VALUE autolink = Qtrue;
1007 VALUE line_ending = rb_str_new2("\n");
1008 VALUE external_link_class = rb_str_new2("external");
1009 VALUE external_link_rel = Qnil;
1010 VALUE mailto_class = rb_str_new2("mailto");
1011 VALUE link_proc = Qnil;
1012 VALUE internal_link_prefix = rb_str_new2("/wiki/");
1013 VALUE img_prefix = rb_str_new2("/images/");
1014 VALUE output_style = ID2SYM(rb_intern("html"));
1015 VALUE space_to_underscore = Qtrue;
1016 VALUE minimum_fulltext_token_length = INT2NUM(3);
1017 VALUE base_heading_level = INT2NUM(0);
1019 // process options hash (override defaults)
1020 if (!NIL_P(options) && TYPE(options) == T_HASH)
1022 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1023 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1024 autolink = OVERRIDE_IF_SET(autolink);
1025 line_ending = OVERRIDE_IF_SET(line_ending);
1026 external_link_class = OVERRIDE_IF_SET(external_link_class);
1027 external_link_rel = OVERRIDE_IF_SET(external_link_rel);
1028 mailto_class = OVERRIDE_IF_SET(mailto_class);
1029 link_proc = OVERRIDE_IF_SET(link_proc);
1030 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1031 img_prefix = OVERRIDE_IF_SET(img_prefix);
1032 output_style = OVERRIDE_IF_SET(output_style);
1033 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1034 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1035 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1038 // no need to call super here; rb_call_super()
1039 rb_iv_set(self, "@autolink", autolink);
1040 rb_iv_set(self, "@line_ending", line_ending);
1041 rb_iv_set(self, "@external_link_class", external_link_class);
1042 rb_iv_set(self, "@external_link_rel", external_link_rel);
1043 rb_iv_set(self, "@mailto_class", mailto_class);
1044 rb_iv_set(self, "@link_proc", link_proc);
1045 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1046 rb_iv_set(self, "@img_prefix", img_prefix);
1047 rb_iv_set(self, "@output_style", output_style);
1048 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1049 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1050 rb_iv_set(self, "@base_heading_level", base_heading_level);
1054 // convert a Ruby object (:xml, :html etc) into an int output style
1055 int Wikitext_output_style(VALUE output)
1057 if (TYPE(output) == T_SYMBOL)
1059 if (SYM2ID(output) == rb_intern("xml"))
1062 return HTML_OUTPUT; // fall back to default
1065 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1067 // process arguments
1068 VALUE string, options;
1069 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1073 string = StringValue(string);
1075 // access these once per parse
1076 VALUE line_ending = rb_iv_get(self, "@line_ending");
1077 line_ending = StringValue(line_ending);
1078 VALUE link_class = rb_iv_get(self, "@external_link_class");
1079 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1080 VALUE link_rel = rb_iv_get(self, "@external_link_rel");
1081 link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
1082 VALUE link_proc = rb_iv_get(self, "@link_proc");
1083 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1084 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1085 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1086 int output_style = Wikitext_output_style(rb_iv_get(self, "@output_style"));
1088 // process options hash
1089 int base_indent = 0;
1090 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1091 if (!NIL_P(options) && TYPE(options) == T_HASH)
1093 // :indent => 0 (or more)
1094 ID has_key = rb_intern("has_key?");
1095 ID id = ID2SYM(rb_intern("indent"));
1096 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1098 VALUE indent = rb_hash_aref(options, id);
1099 if (indent == Qfalse)
1100 base_indent = -1; // indentation disabled
1103 base_indent = NUM2INT(indent);
1104 if (base_indent < 0)
1109 // :base_heading_level => 0/1/2/3/4/5/6
1110 id = ID2SYM(rb_intern("base_heading_level"));
1111 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1112 base_heading_level = NUM2INT(rb_hash_aref(options, id));
1114 // :external_link_rel => 'nofollow'
1115 id = ID2SYM(rb_intern("external_link_rel"));
1116 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1118 link_rel = rb_hash_aref(options, id);
1119 link_rel = NIL_P(link_rel) ? Qnil : StringValue(link_rel);
1122 // :output_style => :html/:xml
1123 id = ID2SYM(rb_intern("output_style"));
1124 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1125 output_style = Wikitext_output_style(rb_hash_aref(options, id));
1127 // :link_proc => lambda { |link_target| ... }
1128 id = ID2SYM(rb_intern("link_proc"));
1129 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1130 link_proc = rb_hash_aref(options, id);
1133 // normalize, regardless of whether this came from instance variable or override
1134 if (base_heading_level < 0)
1135 base_heading_level = 0;
1136 if (base_heading_level > 6)
1137 base_heading_level = 6;
1140 char *p = RSTRING_PTR(string);
1141 long len = RSTRING_LEN(string);
1144 // set up parser struct to make passing parameters a little easier
1145 parser_t *parser = parser_new();
1146 GC_WRAP_PARSER(parser, parser_gc);
1147 parser->external_link_class = link_class;
1148 parser->external_link_rel = link_rel;
1149 parser->mailto_class = mailto_class;
1150 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1151 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1152 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1153 parser->line_ending = str_new_from_string(line_ending);
1154 parser->base_indent = base_indent;
1155 parser->base_heading_level = base_heading_level;
1156 parser->output_style = output_style;
1158 // this simple looping design leads to a single enormous function,
1159 // but it's faster than doing actual recursive descent and also secure in the face of
1160 // malicious input that seeks to overflow the stack
1161 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1162 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1163 // than a straightforward looping translator like this one anyway
1165 _token.type = NO_TOKEN;
1166 token_t *token = NULL;
1169 // note that whenever we grab a token we push it into the line buffer
1170 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1171 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1173 // check to see if we have a token hanging around from a previous iteration of this loop
1176 if (_token.type == NO_TOKEN)
1178 // first time here (haven't started scanning yet)
1180 next_token(token, NULL, p, pe);
1181 ary_push(parser->line_buffer, token->type);
1187 int type = token->type;
1189 // can't declare new variables inside a switch statement, so predeclare them here
1190 long remove_strong = -1;
1191 long remove_em = -1;
1193 // general purpose counters, flags and pointers
1197 str_t *output = NULL;
1199 str_t *token_str = &_token_str;
1201 // The following giant switch statement contains cases for all the possible token types.
1202 // In the most basic sense we are emitting the HTML that corresponds to each token,
1203 // but some tokens require context information in order to decide what to output.
1204 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1205 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1207 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1208 // - the line buffer (records tokens seen so far on the current line)
1209 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1211 // Although this is fairly complicated, there is one key simplifying factor:
1212 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1213 // scope stack (up to the current token) is valid; our translator can take this as a given.
1214 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1215 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1219 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1221 str_append(parser->output, space, sizeof(space) - 1);
1224 else if (IN(BLOCKQUOTE_START))
1226 // this kind of nesting not allowed (to avoid user confusion)
1227 wiki_pop_excess_elements(parser);
1228 wiki_start_para_if_necessary(parser);
1229 output = parser->capture ? parser->capture : parser->output;
1230 str_append(output, space, sizeof(space) - 1);
1234 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1235 ary_push(parser->line, PRE);
1236 i = ary_count(parser->line, BLOCKQUOTE);
1237 j = ary_count(parser->scope, BLOCKQUOTE);
1240 // must pop (reduce nesting level)
1241 for (i = j - i; i > 0; i--)
1242 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1247 parser->pending_crlf = false;
1248 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1249 wiki_indent(parser);
1250 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1251 ary_push(parser->scope, PRE);
1256 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1258 wiki_emit_pending_crlf_if_necessary(parser);
1259 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1261 else if (IN(BLOCKQUOTE_START))
1263 wiki_rollback_failed_link(parser); // if any
1264 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1265 wiki_append_pre_start(parser, token);
1267 else if (IN(BLOCKQUOTE))
1269 if (token->column_start == 1) // only allowed in first column
1271 wiki_rollback_failed_link(parser); // if any
1272 wiki_pop_all_from_stack(parser);
1273 wiki_append_pre_start(parser, token);
1275 else // PRE_START illegal here
1277 output = parser->capture ? parser->capture : parser->output;
1278 wiki_pop_excess_elements(parser);
1279 wiki_start_para_if_necessary(parser);
1280 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1285 wiki_rollback_failed_link(parser); // if any
1286 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1287 wiki_append_pre_start(parser, token);
1292 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1294 wiki_emit_pending_crlf_if_necessary(parser);
1295 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1300 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1303 output = parser->capture ? parser->capture : parser->output;
1304 wiki_pop_excess_elements(parser);
1305 wiki_start_para_if_necessary(parser);
1306 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1312 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1313 // no need to check for <pre>; can never appear inside it
1314 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1315 else if (IN(BLOCKQUOTE_START))
1317 // this kind of nesting not allowed (to avoid user confusion)
1318 wiki_pop_excess_elements(parser);
1319 wiki_start_para_if_necessary(parser);
1320 output = parser->capture ? parser->capture : parser->output;
1321 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1326 ary_push(parser->line, BLOCKQUOTE);
1328 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1329 i = ary_count(parser->line, BLOCKQUOTE);
1330 j = ary_count(parser->scope, BLOCKQUOTE);
1332 // 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
1333 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1335 ary_push(parser->line, BLOCKQUOTE);
1339 // now decide whether to push, pop or do nothing
1342 // must push (increase nesting level)
1343 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1344 for (i = i - j; i > 0; i--)
1346 wiki_indent(parser);
1347 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1348 str_append_str(parser->output, parser->line_ending);
1349 ary_push(parser->scope, BLOCKQUOTE);
1354 // must pop (reduce nesting level)
1355 for (i = j - i; i > 0; i--)
1356 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1359 // jump to top of the loop to process token we scanned during lookahead
1364 case BLOCKQUOTE_START:
1365 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1367 wiki_emit_pending_crlf_if_necessary(parser);
1368 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1370 else if (IN(BLOCKQUOTE_START))
1372 // nesting is fine here
1373 wiki_rollback_failed_link(parser); // if any
1374 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1375 wiki_indent(parser);
1376 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1377 str_append_str(parser->output, parser->line_ending);
1378 ary_push(parser->scope, BLOCKQUOTE_START);
1379 ary_push(parser->line, BLOCKQUOTE_START);
1381 else if (IN(BLOCKQUOTE))
1383 if (token->column_start == 1) // only allowed in first column
1385 wiki_rollback_failed_link(parser); // if any
1386 wiki_pop_all_from_stack(parser);
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 // BLOCKQUOTE_START illegal here
1395 output = parser->capture ? parser->capture : parser->output;
1396 wiki_pop_excess_elements(parser);
1397 wiki_start_para_if_necessary(parser);
1398 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1403 // would be nice to eliminate the repetition here but it's probably the clearest way
1404 wiki_rollback_failed_link(parser); // if any
1405 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1406 wiki_indent(parser);
1407 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1408 str_append_str(parser->output, parser->line_ending);
1409 ary_push(parser->scope, BLOCKQUOTE_START);
1410 ary_push(parser->line, BLOCKQUOTE_START);
1414 case BLOCKQUOTE_END:
1415 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1417 wiki_emit_pending_crlf_if_necessary(parser);
1418 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1422 if (IN(BLOCKQUOTE_START))
1423 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1426 output = parser->capture ? parser->capture : parser->output;
1427 wiki_pop_excess_elements(parser);
1428 wiki_start_para_if_necessary(parser);
1429 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1435 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1437 wiki_emit_pending_crlf_if_necessary(parser);
1438 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1442 wiki_pop_excess_elements(parser);
1443 wiki_start_para_if_necessary(parser);
1444 ary_push(parser->scope, NO_WIKI_START);
1445 ary_push(parser->line, NO_WIKI_START);
1450 if (IN(NO_WIKI_START))
1451 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1452 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1455 wiki_pop_excess_elements(parser);
1456 wiki_start_para_if_necessary(parser);
1457 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1462 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1464 wiki_emit_pending_crlf_if_necessary(parser);
1465 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1469 output = parser->capture ? parser->capture : parser->output;
1470 wiki_pop_excess_elements(parser);
1472 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1473 // otherwise, must open them
1476 j = parser->scope->count;
1477 for (j = j - 1; j >= 0; j--)
1479 int val = ary_entry(parser->scope, (int)j);
1480 if (val == STRONG || val == STRONG_START)
1482 str_append(output, strong_end, sizeof(strong_end) - 1);
1485 else if (val == EM || val == EM_START)
1487 str_append(output, em_end, sizeof(em_end) - 1);
1492 if (remove_strong > remove_em) // must remove strong first
1494 ary_pop(parser->scope);
1496 ary_pop(parser->scope);
1497 else // there was no em to remove!, so consider this an opening em tag
1499 str_append(output, em_start, sizeof(em_start) - 1);
1500 ary_push(parser->scope, EM);
1501 ary_push(parser->line, EM);
1504 else if (remove_em > remove_strong) // must remove em first
1506 ary_pop(parser->scope);
1507 if (remove_strong > -1)
1508 ary_pop(parser->scope);
1509 else // there was no strong to remove!, so consider this an opening strong tag
1511 str_append(output, strong_start, sizeof(strong_start) - 1);
1512 ary_push(parser->scope, STRONG);
1513 ary_push(parser->line, STRONG);
1516 else // no strong or em to remove, so this must be a new opening of both
1518 wiki_start_para_if_necessary(parser);
1519 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1520 ary_push(parser->scope, STRONG);
1521 ary_push(parser->line, STRONG);
1522 ary_push(parser->scope, EM);
1523 ary_push(parser->line, EM);
1528 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1530 wiki_emit_pending_crlf_if_necessary(parser);
1531 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1535 output = parser->capture ? parser->capture : parser->output;
1536 if (IN(STRONG_START))
1537 // already in span started with <strong>, no choice but to emit this literally
1538 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1539 else if (IN(STRONG))
1540 // STRONG already seen, this is a closing tag
1541 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1544 // this is a new opening
1545 wiki_pop_excess_elements(parser);
1546 wiki_start_para_if_necessary(parser);
1547 str_append(output, strong_start, sizeof(strong_start) - 1);
1548 ary_push(parser->scope, STRONG);
1549 ary_push(parser->line, STRONG);
1555 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1557 wiki_emit_pending_crlf_if_necessary(parser);
1558 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1562 output = parser->capture ? parser->capture : parser->output;
1563 if (IN_EITHER_OF(STRONG_START, STRONG))
1564 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1567 wiki_pop_excess_elements(parser);
1568 wiki_start_para_if_necessary(parser);
1569 str_append(output, strong_start, sizeof(strong_start) - 1);
1570 ary_push(parser->scope, STRONG_START);
1571 ary_push(parser->line, STRONG_START);
1577 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1579 wiki_emit_pending_crlf_if_necessary(parser);
1580 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1584 output = parser->capture ? parser->capture : parser->output;
1585 if (IN(STRONG_START))
1586 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1589 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1590 wiki_pop_excess_elements(parser);
1591 wiki_start_para_if_necessary(parser);
1592 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1598 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1600 wiki_emit_pending_crlf_if_necessary(parser);
1601 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1605 output = parser->capture ? parser->capture : parser->output;
1607 // already in span started with <em>, no choice but to emit this literally
1608 str_append(output, literal_em, sizeof(literal_em) - 1);
1610 // EM already seen, this is a closing tag
1611 wiki_pop_from_stack_up_to(parser, output, EM, true);
1614 // this is a new opening
1615 wiki_pop_excess_elements(parser);
1616 wiki_start_para_if_necessary(parser);
1617 str_append(output, em_start, sizeof(em_start) - 1);
1618 ary_push(parser->scope, EM);
1619 ary_push(parser->line, EM);
1625 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1627 wiki_emit_pending_crlf_if_necessary(parser);
1628 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1632 output = parser->capture ? parser->capture : parser->output;
1633 if (IN_EITHER_OF(EM_START, EM))
1634 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1637 wiki_pop_excess_elements(parser);
1638 wiki_start_para_if_necessary(parser);
1639 str_append(output, em_start, sizeof(em_start) - 1);
1640 ary_push(parser->scope, EM_START);
1641 ary_push(parser->line, EM_START);
1647 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1649 wiki_emit_pending_crlf_if_necessary(parser);
1650 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1654 output = parser->capture ? parser->capture : parser->output;
1656 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1659 // no EM_START in scope, so must interpret the EM_END without any special meaning
1660 wiki_pop_excess_elements(parser);
1661 wiki_start_para_if_necessary(parser);
1662 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1668 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1670 wiki_emit_pending_crlf_if_necessary(parser);
1671 str_append(parser->output, backtick, sizeof(backtick) - 1);
1675 output = parser->capture ? parser->capture : parser->output;
1677 // already in span started with <tt>, no choice but to emit this literally
1678 str_append(output, backtick, sizeof(backtick) - 1);
1680 // TT (`) already seen, this is a closing tag
1681 wiki_pop_from_stack_up_to(parser, output, TT, true);
1684 // this is a new opening
1685 wiki_pop_excess_elements(parser);
1686 wiki_start_para_if_necessary(parser);
1687 str_append(output, code_start, sizeof(code_start) - 1);
1688 ary_push(parser->scope, TT);
1689 ary_push(parser->line, TT);
1695 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1697 wiki_emit_pending_crlf_if_necessary(parser);
1698 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1702 output = parser->capture ? parser->capture : parser->output;
1703 if (IN_EITHER_OF(TT_START, TT))
1704 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1707 wiki_pop_excess_elements(parser);
1708 wiki_start_para_if_necessary(parser);
1709 str_append(output, code_start, sizeof(code_start) - 1);
1710 ary_push(parser->scope, TT_START);
1711 ary_push(parser->line, TT_START);
1717 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1719 wiki_emit_pending_crlf_if_necessary(parser);
1720 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1724 output = parser->capture ? parser->capture : parser->output;
1726 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1729 // no TT_START in scope, so must interpret the TT_END without any special meaning
1730 wiki_pop_excess_elements(parser);
1731 wiki_start_para_if_necessary(parser);
1732 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1739 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1741 // no need to check for PRE; can never appear inside it
1742 str_append(parser->output, token->start, TOKEN_LEN(token));
1746 // count number of tokens in line and scope stacks
1747 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1748 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1749 j = parser->scope->count - bq_count;
1752 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1756 if (type == OL || type == UL)
1759 if (i - k >= 2) // already seen at least one OL or UL
1761 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1766 ary_push(parser->line, type);
1767 ary_push(parser->line, LI);
1769 // want to compare line with scope but can only do so if scope has enough items on it
1772 if (ary_entry(parser->scope, (int)(i + bq_count - 2)) == type &&
1773 ary_entry(parser->scope, (int)(i + bq_count - 1)) == LI)
1775 // line and scope match at this point: do nothing yet
1779 // item just pushed onto line does not match corresponding slot of scope!
1780 for (; j >= i - 2; j--)
1781 // must pop back before emitting
1782 wiki_pop_from_stack(parser, NULL);
1784 // will emit UL or OL, then LI
1788 else // line stack size now exceeds scope stack size: must increase nesting level
1789 break; // will emit UL or OL, then LI
1793 // not a OL or UL token!
1795 // must close existing LI and re-open new one
1796 wiki_pop_from_stack(parser, NULL);
1799 // item just pushed onto line does not match corresponding slot of scope!
1801 // must pop back before emitting
1802 wiki_pop_from_stack(parser, NULL);
1810 if (type == OL || type == UL)
1812 // if LI is at the top of a stack this is the start of a nested list
1813 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1815 // so we should precede it with a CRLF, and indicate that it's a nested list
1816 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1817 ary_push(parser->scope, NESTED_LIST);
1821 // this is a new list
1822 if (IN(BLOCKQUOTE_START))
1823 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1825 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1829 wiki_indent(parser);
1831 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1832 else if (type == UL)
1833 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1834 ary_push(parser->scope, type);
1835 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1837 else if (type == SPACE)
1838 // silently throw away the optional SPACE token after final list marker
1841 wiki_indent(parser);
1842 str_append(parser->output, li_start, sizeof(li_start) - 1);
1843 ary_push(parser->scope, LI);
1845 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1846 if (type == OL || type == UL)
1849 while (k++, NEXT_TOKEN(), (type = token->type))
1851 if (type == OL || type == UL)
1852 str_append(parser->output, token->start, TOKEN_LEN(token));
1853 else if (type == SPACE && k == 1)
1855 // silently throw away the optional SPACE token after final list marker
1864 // jump to top of the loop to process token we scanned during lookahead
1873 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1875 // no need to check for PRE; can never appear inside it
1876 str_append(parser->output, token->start, TOKEN_LEN(token));
1880 // pop up to but not including the last BLOCKQUOTE on the scope stack
1881 if (IN(BLOCKQUOTE_START))
1882 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1884 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1886 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1887 ary_push(parser->line, type);
1888 i = ary_count(parser->line, BLOCKQUOTE);
1889 j = ary_count(parser->scope, BLOCKQUOTE);
1891 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1894 // must pop (reduce nesting level)
1895 for (i = j - i; i > 0; i--)
1896 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1899 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1900 while (NEXT_TOKEN(), (token->type == SPACE))
1903 ary_push(parser->scope, type);
1904 wiki_indent(parser);
1906 // take base_heading_level into account
1907 type += base_heading_level;
1908 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1911 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1912 if (type == H6_START)
1913 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1914 else if (type == H5_START)
1915 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1916 else if (type == H4_START)
1917 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1918 else if (type == H3_START)
1919 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1920 else if (type == H2_START)
1921 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1922 else if (type == H1_START)
1923 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1925 // jump to top of the loop to process token we scanned during lookahead
1934 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1936 wiki_emit_pending_crlf_if_necessary(parser);
1937 str_append(parser->output, token->start, TOKEN_LEN(token));
1941 wiki_rollback_failed_external_link(parser); // if any
1942 if ((type == H6_END && !IN(H6_START)) ||
1943 (type == H5_END && !IN(H5_START)) ||
1944 (type == H4_END && !IN(H4_START)) ||
1945 (type == H3_END && !IN(H3_START)) ||
1946 (type == H2_END && !IN(H2_START)) ||
1947 (type == H1_END && !IN(H1_START)))
1949 // literal output only if not in appropriate scope (we stay silent in that case)
1950 wiki_start_para_if_necessary(parser);
1951 str_append(parser->output, token->start, TOKEN_LEN(token));
1957 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1959 wiki_emit_pending_crlf_if_necessary(parser);
1960 str_append(parser->output, token->start, TOKEN_LEN(token));
1962 else if (IN(EXT_LINK_START))
1963 // must be capturing and this must be part of the link text
1964 str_append(parser->capture, token->start, TOKEN_LEN(token));
1967 wiki_pop_excess_elements(parser);
1968 wiki_start_para_if_necessary(parser);
1969 token_str->ptr = token->start;
1970 token_str->len = TOKEN_LEN(token);
1971 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, Qnil, true);
1976 if (IN(NO_WIKI_START))
1978 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1979 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1980 token_str->ptr = token->start;
1981 token_str->len = TOKEN_LEN(token);
1982 wiki_append_sanitized_link_target(token_str, parser->output, false);
1984 else if (IN(LINK_START))
1986 // if the URI were allowed it would have been handled already in LINK_START
1987 wiki_rollback_failed_internal_link(parser);
1988 token_str->ptr = token->start;
1989 token_str->len = TOKEN_LEN(token);
1990 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
1992 else if (IN(EXT_LINK_START))
1994 if (parser->link_target->len == 0)
1996 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1997 token_str->ptr = token->start;
1998 token_str->len = TOKEN_LEN(token);
2000 if (token->type == SPACE)
2002 ary_push(parser->scope, SPACE);
2003 str_append_str(parser->link_target, token_str);
2004 str_clear(parser->link_text);
2005 parser->capture = parser->link_text;
2006 token = NULL; // silently consume space
2010 // didn't see the space! this must be an error
2011 wiki_pop_from_stack(parser, NULL);
2012 wiki_pop_excess_elements(parser);
2013 wiki_start_para_if_necessary(parser);
2014 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2015 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2021 token_str->ptr = token->start;
2022 token_str->len = TOKEN_LEN(token);
2023 wiki_append_sanitized_link_target(token_str, parser->link_text, false);
2028 wiki_pop_excess_elements(parser);
2029 wiki_start_para_if_necessary(parser);
2030 token_str->ptr = token->start;
2031 token_str->len = TOKEN_LEN(token);
2032 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, parser->external_link_rel, true);
2037 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2039 wiki_emit_pending_crlf_if_necessary(parser);
2040 str_append(parser->output, token->start, TOKEN_LEN(token));
2042 else if (IN(EXT_LINK_START))
2044 if (parser->link_target->len == 0)
2046 // this must be our link target: look ahead to make sure we see the space we're expecting to see
2047 token_str->ptr = token->start;
2048 token_str->len = TOKEN_LEN(token);
2050 if (token->type == SPACE)
2052 ary_push(parser->scope, PATH);
2053 ary_push(parser->scope, SPACE);
2054 str_append_str(parser->link_target, token_str);
2055 str_clear(parser->link_text);
2056 parser->capture = parser->link_text;
2057 token = NULL; // silently consume space
2061 // didn't see the space! this must be an error
2062 wiki_pop_from_stack(parser, NULL);
2063 wiki_pop_excess_elements(parser);
2064 wiki_start_para_if_necessary(parser);
2065 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2066 str_append_str(parser->output, token_str);
2071 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2075 output = parser->capture ? parser->capture : parser->output;
2076 wiki_pop_excess_elements(parser);
2077 wiki_start_para_if_necessary(parser);
2078 str_append(output, token->start, TOKEN_LEN(token));
2082 // internal links (links to other wiki articles) look like this:
2083 // [[another article]] (would point at, for example, "/wiki/another_article")
2084 // [[the other article|the link text we'll use for it]]
2085 // [[the other article | the link text we'll use for it]]
2086 // MediaWiki has strict requirements about what it will accept as a link target:
2087 // all wikitext markup is disallowed:
2088 // example [[foo ''bar'' baz]]
2089 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2090 // example [[foo <em>bar</em> baz]]
2091 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2092 // example [[foo <nowiki>''</nowiki> baz]]
2093 // renders [[foo '' baz]] (ie. not a link)
2094 // example [[foo <bar> baz]]
2095 // renders [[foo <bar> baz]] (ie. not a link)
2096 // HTML entities and non-ASCII, however, make it through:
2097 // example [[foo €]]
2098 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2099 // example [[foo €]]
2100 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2101 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2102 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2103 // everything else will be rejected
2105 output = parser->capture ? parser->capture : parser->output;
2106 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2108 wiki_emit_pending_crlf_if_necessary(parser);
2109 str_append(output, link_start, sizeof(link_start) - 1);
2111 else if (IN(EXT_LINK_START))
2112 // already in external link scope! (and in fact, must be capturing link_text right now)
2113 str_append(output, link_start, sizeof(link_start) - 1);
2114 else if (IN(LINK_START))
2116 // already in internal link scope! this is a syntax error
2117 wiki_rollback_failed_internal_link(parser);
2118 str_append(parser->output, link_start, sizeof(link_start) - 1);
2120 else if (IN(SEPARATOR))
2122 // scanning internal link text
2124 else // not in internal link scope yet
2126 // will either emit a link, or the rollback of a failed link, so start the para now
2127 wiki_pop_excess_elements(parser);
2128 wiki_start_para_if_necessary(parser);
2129 ary_push(parser->scope, LINK_START);
2131 // look ahead and try to gobble up link target
2132 while (NEXT_TOKEN(), (type = token->type))
2134 if (type == SPACE ||
2135 type == SPECIAL_URI_CHARS ||
2137 type == PRINTABLE ||
2141 type == QUOT_ENTITY ||
2143 type == AMP_ENTITY ||
2144 type == IMG_START ||
2146 type == LEFT_CURLY ||
2147 type == RIGHT_CURLY)
2149 // accumulate these tokens into link_target
2150 if (parser->link_target->len == 0)
2152 str_clear(parser->link_target);
2153 parser->capture = parser->link_target;
2155 if (type == QUOT_ENTITY)
2156 // don't insert the entity, insert the literal quote
2157 str_append(parser->link_target, quote, sizeof(quote) - 1);
2158 else if (type == AMP_ENTITY)
2159 // don't insert the entity, insert the literal ampersand
2160 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2162 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2164 else if (type == LINK_END)
2166 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2167 wiki_rollback_failed_internal_link(parser);
2168 break; // jump back to top of loop (will handle this in LINK_END case below)
2170 else if (type == SEPARATOR)
2172 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2173 wiki_rollback_failed_internal_link(parser);
2176 ary_push(parser->scope, SEPARATOR);
2177 str_clear(parser->link_text);
2178 parser->capture = parser->link_text;
2183 else // unexpected token (syntax error)
2185 wiki_rollback_failed_internal_link(parser);
2186 break; // jump back to top of loop to handle unexpected token
2190 // jump to top of the loop to process token we scanned during lookahead (if any)
2196 output = parser->capture ? parser->capture : parser->output;
2197 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2199 wiki_emit_pending_crlf_if_necessary(parser);
2200 str_append(output, link_end, sizeof(link_end) - 1);
2202 else if (IN(EXT_LINK_START))
2203 // already in external link scope! (and in fact, must be capturing link_text right now)
2204 str_append(output, link_end, sizeof(link_end) - 1);
2205 else if (IN(LINK_START)) // in internal link scope!
2207 if (wiki_blank(parser->link_target))
2209 // special case for inputs like "[[ ]]"
2210 wiki_rollback_failed_internal_link(parser);
2211 str_append(parser->output, link_end, sizeof(link_end) - 1);
2214 if (parser->link_text->len == 0 ||
2215 wiki_blank(parser->link_text))
2217 // use link target as link text
2218 str_clear(parser->link_text);
2219 wiki_append_sanitized_link_target(parser->link_target, parser->link_text, true);
2222 wiki_trim_link_text(parser);
2224 // perform "redlink" check before manipulating link_target
2225 if (NIL_P(link_proc))
2229 j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
2232 VALUE l = j; // can't cast inside StringValue macro
2236 wiki_encode_link_target(parser);
2237 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2238 parser->capture = NULL;
2239 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, Qnil, false);
2240 str_clear(parser->link_target);
2241 str_clear(parser->link_text);
2243 else // wasn't in internal link scope
2245 wiki_pop_excess_elements(parser);
2246 wiki_start_para_if_necessary(parser);
2247 str_append(output, link_end, sizeof(link_end) - 1);
2251 // external links look like this:
2252 // [http://google.com/ the link text]
2253 // [/other/page/on/site see this page]
2254 // strings in square brackets which don't match this syntax get passed through literally; eg:
2255 // he was very angery [sic] about the turn of events
2256 case EXT_LINK_START:
2257 output = parser->capture ? parser->capture : parser->output;
2258 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2260 wiki_emit_pending_crlf_if_necessary(parser);
2261 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2263 else if (IN(EXT_LINK_START))
2264 // already in external link scope! (and in fact, must be capturing link_text right now)
2265 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2266 else if (IN(LINK_START))
2268 // already in internal link scope!
2269 if (parser->link_target->len == 0 || !IN(SPACE))
2270 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2271 else // link target has already been scanned
2272 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2274 else // not in external link scope yet
2276 // will either emit a link, or the rollback of a failed link, so start the para now
2277 wiki_pop_excess_elements(parser);
2278 wiki_start_para_if_necessary(parser);
2280 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2282 if (token->type == URI || token->type == PATH)
2283 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2285 // only get here if there was a syntax error (missing URI)
2286 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2287 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2292 output = parser->capture ? parser->capture : parser->output;
2293 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2295 wiki_emit_pending_crlf_if_necessary(parser);
2296 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2298 else if (IN(EXT_LINK_START))
2300 if (parser->link_text->len == 0)
2301 // syntax error: external link with no link text
2302 wiki_rollback_failed_external_link(parser);
2306 j = IN(PATH) ? Qnil : parser->external_link_class;
2307 k = IN(PATH) ? Qnil : parser->external_link_rel;
2308 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2309 parser->capture = NULL;
2310 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, k, false);
2312 str_clear(parser->link_target);
2313 str_clear(parser->link_text);
2317 wiki_pop_excess_elements(parser);
2318 wiki_start_para_if_necessary(parser);
2319 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2324 output = parser->capture ? parser->capture : parser->output;
2325 wiki_pop_excess_elements(parser);
2326 wiki_start_para_if_necessary(parser);
2327 str_append(output, separator, sizeof(separator) - 1);
2331 output = parser->capture ? parser->capture : parser->output;
2332 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2334 wiki_emit_pending_crlf_if_necessary(parser);
2335 str_append(output, token->start, TOKEN_LEN(token));
2339 // peek ahead to see next token
2340 char *token_ptr = token->start;
2341 long token_len = TOKEN_LEN(token);
2344 if ((type == H6_END && IN(H6_START)) ||
2345 (type == H5_END && IN(H5_START)) ||
2346 (type == H4_END && IN(H4_START)) ||
2347 (type == H3_END && IN(H3_START)) ||
2348 (type == H2_END && IN(H2_START)) ||
2349 (type == H1_END && IN(H1_START)))
2351 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2356 wiki_pop_excess_elements(parser);
2357 wiki_start_para_if_necessary(parser);
2358 str_append(output, token_ptr, token_len);
2361 // jump to top of the loop to process token we scanned during lookahead
2369 case DECIMAL_ENTITY:
2370 // pass these through unaltered as they are case sensitive
2371 output = parser->capture ? parser->capture : parser->output;
2372 wiki_pop_excess_elements(parser);
2373 wiki_start_para_if_necessary(parser);
2374 str_append(output, token->start, TOKEN_LEN(token));
2378 // normalize hex entities (downcase them)
2379 output = parser->capture ? parser->capture : parser->output;
2380 wiki_pop_excess_elements(parser);
2381 wiki_start_para_if_necessary(parser);
2382 str_append(output, token->start, TOKEN_LEN(token));
2383 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2387 output = parser->capture ? parser->capture : parser->output;
2388 wiki_pop_excess_elements(parser);
2389 wiki_start_para_if_necessary(parser);
2390 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2394 output = parser->capture ? parser->capture : parser->output;
2395 wiki_pop_excess_elements(parser);
2396 wiki_start_para_if_necessary(parser);
2397 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2401 output = parser->capture ? parser->capture : parser->output;
2402 wiki_pop_excess_elements(parser);
2403 wiki_start_para_if_necessary(parser);
2404 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2408 output = parser->capture ? parser->capture : parser->output;
2409 wiki_pop_excess_elements(parser);
2410 wiki_start_para_if_necessary(parser);
2411 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2415 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2417 wiki_emit_pending_crlf_if_necessary(parser);
2418 str_append(parser->output, token->start, TOKEN_LEN(token));
2420 else if (parser->capture)
2421 str_append(parser->capture, token->start, TOKEN_LEN(token));
2424 // not currently capturing: will be emitting something on success or failure, so get ready
2425 wiki_pop_excess_elements(parser);
2426 wiki_start_para_if_necessary(parser);
2428 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2429 // will cheat here and abuse the link_target capture buffer to accumulate text
2430 while (NEXT_TOKEN(), (type = token->type))
2432 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2433 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2434 else if (type == IMG_END && parser->link_target->len > 0)
2437 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2441 else // unexpected token or zero-length target (syntax error)
2444 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2445 if (parser->link_target->len > 0)
2446 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2451 // jump to top of the loop to process token we scanned during lookahead
2452 str_clear(parser->link_target);
2458 i = parser->pending_crlf;
2459 parser->pending_crlf = false;
2460 wiki_rollback_failed_link(parser); // if any
2461 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2463 ary_clear(parser->line_buffer);
2464 str_append_str(parser->output, parser->line_ending);
2469 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2470 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2471 // don't emit in this case
2472 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2475 if (ary_entry(parser->line_buffer, -2) == PRE)
2477 // only thing on line is the PRE: emit pending line ending (if we had one)
2479 str_append_str(parser->output, parser->line_ending);
2482 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2483 ary_clear(parser->line);
2484 ary_clear(parser->line_buffer);
2486 // peek ahead to see if this is definitely the end of the PRE block
2489 if (type != BLOCKQUOTE && type != PRE)
2490 // this is definitely the end of the block, so don't emit
2491 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2493 // potentially will emit
2494 parser->pending_crlf = true;
2496 continue; // jump back to top of loop to handle token grabbed via lookahead
2501 parser->pending_crlf = true;
2503 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2504 // as a side effect, this handles any open span-level elements and unclosed blocks
2505 // (with special handling for P blocks and LI elements)
2506 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2507 for (j = parser->scope->count; j > i; j--)
2509 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2511 parser->pending_crlf = false;
2515 // special handling on last iteration through the loop if the top item on the scope is a P block
2516 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2518 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2519 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2520 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2521 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2522 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2524 parser->pending_crlf = false;
2526 // not a paragraph break!
2529 wiki_pop_from_stack(parser, NULL);
2533 // delete the entire contents of the line scope stack and buffer
2534 ary_clear(parser->line);
2535 ary_clear(parser->line_buffer);
2538 case SPECIAL_URI_CHARS:
2544 output = parser->capture ? parser->capture : parser->output;
2545 wiki_pop_excess_elements(parser);
2546 wiki_start_para_if_necessary(parser);
2547 str_append(output, token->start, TOKEN_LEN(token));
2551 output = parser->capture ? parser->capture : parser->output;
2552 wiki_pop_excess_elements(parser);
2553 wiki_start_para_if_necessary(parser);
2554 wiki_append_entity_from_utf32_char(output, token->code_point);
2558 // special case for input like " foo\n " (see pre_spec.rb)
2560 ary_entry(parser->line_buffer, -2) == PRE &&
2561 parser->pending_crlf)
2562 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2564 // close any open scopes on hitting EOF
2565 wiki_rollback_failed_link(parser); // if any
2566 wiki_pop_all_from_stack(parser);
2567 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2573 // reset current token; forcing lexer to return another token at the top of the loop
2577 // nasty hack to avoid re-allocating our return value
2578 str_append(parser->output, null_str, 1); // null-terminate
2579 len = parser->output->len - 1; // don't count null termination
2581 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2582 free(RSTRING_PTR(out));
2583 RSTRING(out)->as.heap.aux.capa = len;
2584 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2585 RSTRING(out)->as.heap.len = len;
2586 parser->output->ptr = NULL; // don't double-free