1 // Copyright 2007-2009 Wincent Colaiuta. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are met:
6 // 1. Redistributions of source code must retain the above copyright notice,
7 // this list of conditions and the following disclaimer.
8 // 2. Redistributions in binary form must reproduce the above copyright notice,
9 // this list of conditions and the following disclaimer in the documentation
10 // and/or other materials provided with the distribution.
12 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
13 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
16 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
17 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
18 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
19 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
20 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
21 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
22 // POSSIBILITY OF SUCH DAMAGE.
30 #include "wikitext_ragel.h"
32 #define IN(type) ary_includes(parser->scope, type)
34 // poor man's object orientation in C:
35 // instead of parsing around multiple parameters between functions in the parser
36 // we pack everything into a struct and pass around only a pointer to that
39 str_t *capture; // capturing to link_target, link_text, or NULL (direct to output, not capturing)
40 str_t *output; // for accumulating output to be returned
41 str_t *link_target; // short term "memory" for parsing links
42 str_t *link_text; // short term "memory" for parsing links
44 str_t *tabulation; // caching buffer for emitting indentation
45 ary_t *scope; // stack for tracking scope
46 ary_t *line; // stack for tracking scope as implied by current line
47 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
48 VALUE external_link_class; // CSS class applied to external links
49 VALUE mailto_class; // CSS class applied to email (mailto) links
50 VALUE img_prefix; // path prepended when emitting img tags
51 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
52 int current_indent; // fluctuates according to currently nested structures
53 int base_heading_level;
56 bool space_to_underscore;
59 const char null_str[] = { 0 };
60 const char escaped_no_wiki_start[] = "<nowiki>";
61 const char escaped_no_wiki_end[] = "</nowiki>";
62 const char literal_strong_em[] = "'''''";
63 const char literal_strong[] = "'''";
64 const char literal_em[] = "''";
65 const char escaped_em_start[] = "<em>";
66 const char escaped_em_end[] = "</em>";
67 const char escaped_strong_start[] = "<strong>";
68 const char escaped_strong_end[] = "</strong>";
69 const char escaped_tt_start[] = "<tt>";
70 const char escaped_tt_end[] = "</tt>";
71 const char pre_start[] = "<pre>";
72 const char pre_end[] = "</pre>";
73 const char escaped_pre_start[] = "<pre>";
74 const char escaped_pre_end[] = "</pre>";
75 const char blockquote_start[] = "<blockquote>";
76 const char blockquote_end[] = "</blockquote>";
77 const char escaped_blockquote_start[] = "<blockquote>";
78 const char escaped_blockquote_end[] = "</blockquote>";
79 const char strong_em_start[] = "<strong><em>";
80 const char strong_start[] = "<strong>";
81 const char strong_end[] = "</strong>";
82 const char em_start[] = "<em>";
83 const char em_end[] = "</em>";
84 const char tt_start[] = "<tt>";
85 const char tt_end[] = "</tt>";
86 const char ol_start[] = "<ol>";
87 const char ol_end[] = "</ol>";
88 const char ul_start[] = "<ul>";
89 const char ul_end[] = "</ul>";
90 const char li_start[] = "<li>";
91 const char li_end[] = "</li>";
92 const char h6_start[] = "<h6>";
93 const char h6_end[] = "</h6>";
94 const char h5_start[] = "<h5>";
95 const char h5_end[] = "</h5>";
96 const char h4_start[] = "<h4>";
97 const char h4_end[] = "</h4>";
98 const char h3_start[] = "<h3>";
99 const char h3_end[] = "</h3>";
100 const char h2_start[] = "<h2>";
101 const char h2_end[] = "</h2>";
102 const char h1_start[] = "<h1>";
103 const char h1_end[] = "</h1>";
104 const char p_start[] = "<p>";
105 const char p_end[] = "</p>";
106 const char space[] = " ";
107 const char a_start[] = "<a href=\"";
108 const char a_class[] = "\" class=\"";
109 const char a_start_close[] = "\">";
110 const char a_end[] = "</a>";
111 const char link_start[] = "[[";
112 const char link_end[] = "]]";
113 const char separator[] = "|";
114 const char ext_link_start[] = "[";
115 const char backtick[] = "`";
116 const char quote[] = "\"";
117 const char ampersand[] = "&";
118 const char quot_entity[] = """;
119 const char amp_entity[] = "&";
120 const char lt_entity[] = "<";
121 const char gt_entity[] = ">";
122 const char escaped_blockquote[] = "> ";
123 const char ext_link_end[] = "]";
124 const char literal_img_start[] = "{{";
125 const char img_start[] = "<img src=\"";
126 const char img_end[] = "\" />";
127 const char img_alt[] = "\" alt=\"";
129 // Mark the parser struct designated by ptr as a participant in Ruby's
130 // mark-and-sweep garbage collection scheme. A variable named name is placed on
131 // the C stack to prevent the structure from being prematurely collected.
132 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
134 parser_t *parser_new(void)
136 parser_t *parser = ALLOC_N(parser_t, 1);
137 parser->capture = NULL; // not a real instance, pointer to other member's instance
138 parser->output = str_new();
139 parser->link_target = str_new();
140 parser->link_text = str_new();
141 parser->line_ending = NULL; // caller should set up
142 parser->tabulation = str_new();
143 parser->scope = ary_new();
144 parser->line = ary_new();
145 parser->line_buffer = ary_new();
146 parser->external_link_class = Qnil; // caller should set up
147 parser->mailto_class = Qnil; // caller should set up
148 parser->img_prefix = Qnil; // caller should set up
149 parser->base_indent = 0;
150 parser->current_indent = 0;
151 parser->base_heading_level = 0;
152 parser->pending_crlf = false;
153 parser->autolink = true;
154 parser->space_to_underscore = true;
158 void parser_free(parser_t *parser)
160 // we don't free parser->capture; it's just a redundant pointer
161 if (parser->output) str_free(parser->output);
162 if (parser->link_target) str_free(parser->link_target);
163 if (parser->link_text) str_free(parser->link_text);
164 if (parser->line_ending) str_free(parser->line_ending);
165 if (parser->tabulation) str_free(parser->tabulation);
166 if (parser->scope) ary_free(parser->scope);
167 if (parser->line) ary_free(parser->line);
168 if (parser->line_buffer) ary_free(parser->line_buffer);
172 // for testing and debugging only
173 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
177 string = StringValue(string);
178 VALUE tokens = rb_ary_new();
179 char *p = RSTRING_PTR(string);
180 long len = RSTRING_LEN(string);
183 next_token(&token, NULL, p, pe);
184 rb_ary_push(tokens, _Wikitext_token(&token));
185 while (token.type != END_OF_FILE)
187 next_token(&token, &token, NULL, pe);
188 rb_ary_push(tokens, _Wikitext_token(&token));
193 // for benchmarking raw tokenization speed only
194 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
198 string = StringValue(string);
199 char *p = RSTRING_PTR(string);
200 long len = RSTRING_LEN(string);
203 next_token(&token, NULL, p, pe);
204 while (token.type != END_OF_FILE)
205 next_token(&token, &token, NULL, pe);
209 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
212 VALUE string, options;
213 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
217 string = StringValue(string);
218 VALUE tokens = rb_ary_new();
220 // check instance variables
221 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
223 // process options hash (can override instance variables)
224 if (!NIL_P(options) && TYPE(options) == T_HASH)
226 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
227 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
229 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
234 char *p = RSTRING_PTR(string);
235 long len = RSTRING_LEN(string);
238 token_t *_token = &token;
239 next_token(&token, NULL, p, pe);
240 while (token.type != END_OF_FILE)
247 if (TOKEN_LEN(_token) >= min_len)
248 rb_ary_push(tokens, TOKEN_TEXT(_token));
251 // ignore everything else
254 next_token(&token, &token, NULL, pe);
259 // we downcase "in place", overwriting the original contents of the buffer
260 void wiki_downcase_bang(char *ptr, long len)
262 for (long i = 0; i < len; i++)
264 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
269 // prepare hyperlink and append it to parser->output
270 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
271 // or merely the literal link target
272 // if link_text is Qnil, the link_target is re-used for the link text
273 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, bool check_autolink)
275 if (check_autolink && !parser->autolink)
276 str_append_str(parser->output, link_target);
279 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
280 if (!NIL_P(link_prefix))
281 str_append_string(parser->output, link_prefix);
282 str_append_str(parser->output, link_target);
284 // special handling for mailto URIs
285 const char *mailto = "mailto:";
286 if (NIL_P(link_prefix) &&
287 link_target->len >= (long)sizeof(mailto) &&
288 strncmp(mailto, link_target->ptr, sizeof(mailto)) == 0)
289 link_class = parser->mailto_class; // use mailto_class from parser
290 if (link_class != Qnil)
292 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
293 str_append_string(parser->output, link_class);
295 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
296 if (!link_text || link_text->len == 0) // re-use link_target
297 str_append_str(parser->output, link_target);
299 str_append_str(parser->output, link_text);
300 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
304 void wiki_append_img(parser_t *parser, char *token_ptr, int token_len)
306 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
307 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
308 str_append_string(parser->output, parser->img_prefix);
309 str_append(parser->output, token_ptr, token_len);
310 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
311 str_append(parser->output, token_ptr, token_len);
312 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
315 // will emit indentation only if we are about to emit any of:
316 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
317 // each time we enter one of those spans must ++ the indentation level
318 void wiki_indent(parser_t *parser)
320 if (parser->base_indent == -1) // indentation disabled
322 int space_count = parser->current_indent + parser->base_indent;
325 char *old_end, *new_end;
326 if (parser->tabulation->len < space_count)
327 str_grow(parser->tabulation, space_count); // reallocates if necessary
328 old_end = parser->tabulation->ptr + parser->tabulation->len;
329 new_end = parser->tabulation->ptr + space_count;
330 while (old_end < new_end)
332 if (space_count > parser->tabulation->len)
333 parser->tabulation->len = space_count;
334 str_append(parser->output, parser->tabulation->ptr, space_count);
336 parser->current_indent += 2;
339 void wiki_dedent(parser_t *parser, bool emit)
341 if (parser->base_indent == -1) // indentation disabled
343 parser->current_indent -= 2;
346 int space_count = parser->current_indent + parser->base_indent;
348 str_append(parser->output, parser->tabulation->ptr, space_count);
351 // Pops a single item off the parser's scope stack.
352 // A corresponding closing tag is written to the target string.
353 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
354 void wiki_pop_from_stack(parser_t *parser, str_t *target)
356 int top = ary_entry(parser->scope, -1);
360 target = parser->output;
362 // for headings, take base_heading_level into account
363 if (top >= H1_START && top <= H6_START)
365 top += parser->base_heading_level;
366 // no need to check for underflow (base_heading_level is never negative)
375 str_append(target, pre_end, sizeof(pre_end) - 1);
376 str_append_str(target, parser->line_ending);
377 wiki_dedent(parser, false);
381 case BLOCKQUOTE_START:
382 wiki_dedent(parser, true);
383 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
384 str_append_str(target, parser->line_ending);
388 // not a real HTML tag; so nothing to pop
393 str_append(target, strong_end, sizeof(strong_end) - 1);
398 str_append(target, em_end, sizeof(em_end) - 1);
403 str_append(target, tt_end, sizeof(tt_end) - 1);
407 wiki_dedent(parser, true);
408 str_append(target, ol_end, sizeof(ol_end) - 1);
409 str_append_str(target, parser->line_ending);
413 wiki_dedent(parser, true);
414 str_append(target, ul_end, sizeof(ul_end) - 1);
415 str_append_str(target, parser->line_ending);
419 // next token to pop will be a LI
420 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
421 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
422 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
423 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
424 wiki_dedent(parser, true); // we really only want to emit the spaces
425 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
429 str_append(target, li_end, sizeof(li_end) - 1);
430 str_append_str(target, parser->line_ending);
431 wiki_dedent(parser, false);
435 str_append(target, h6_end, sizeof(h6_end) - 1);
436 str_append_str(target, parser->line_ending);
437 wiki_dedent(parser, false);
441 str_append(target, h5_end, sizeof(h5_end) - 1);
442 str_append_str(target, parser->line_ending);
443 wiki_dedent(parser, false);
447 str_append(target, h4_end, sizeof(h4_end) - 1);
448 str_append_str(target, parser->line_ending);
449 wiki_dedent(parser, false);
453 str_append(target, h3_end, sizeof(h3_end) - 1);
454 str_append_str(target, parser->line_ending);
455 wiki_dedent(parser, false);
459 str_append(target, h2_end, sizeof(h2_end) - 1);
460 str_append_str(target, parser->line_ending);
461 wiki_dedent(parser, false);
465 str_append(target, h1_end, sizeof(h1_end) - 1);
466 str_append_str(target, parser->line_ending);
467 wiki_dedent(parser, false);
471 // not an HTML tag; so nothing to emit
475 // not an HTML tag; so nothing to emit
479 // not an HTML tag; so nothing to emit
483 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
487 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
491 str_append(target, p_end, sizeof(p_end) - 1);
492 str_append_str(target, parser->line_ending);
493 wiki_dedent(parser, false);
501 // should probably raise an exception here
504 ary_pop(parser->scope);
507 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
508 // If including is true then the item itself is also popped.
509 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
510 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
512 int continue_looping = 1;
515 int top = ary_entry(parser->scope, -1);
522 continue_looping = 0;
524 wiki_pop_from_stack(parser, target);
525 } while (continue_looping);
528 void wiki_pop_all_from_stack(parser_t *parser)
530 for (int i = 0, max = parser->scope->count; i < max; i++)
531 wiki_pop_from_stack(parser, NULL);
534 void wiki_start_para_if_necessary(parser_t *parser)
539 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
540 if (parser->scope->count == 0 ||
541 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
542 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
545 str_append(parser->output, p_start, sizeof(p_start) - 1);
546 ary_push(parser->scope, P);
547 ary_push(parser->line, P);
549 else if (parser->pending_crlf)
552 // already in a paragraph block; convert pending CRLF into a space
553 str_append(parser->output, space, sizeof(space) - 1);
555 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
556 str_append_str(parser->output, parser->line_ending);
558 parser->pending_crlf = false;
561 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
563 if (parser->pending_crlf)
565 str_append_str(parser->output, parser->line_ending);
566 parser->pending_crlf = false;
570 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
571 // For example, given input like:
576 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
577 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
582 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
583 // but not on the line scope:
588 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
589 // on the line scope.
590 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
591 // entering the for loop.
592 void wiki_pop_excess_elements(parser_t *parser)
596 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
598 // special case for last item on scope
601 // don't auto-pop P if it is only item on scope
602 if (ary_entry(parser->scope, -1) == P)
604 // add P to the line scope to prevent us entering the loop at all next time around
605 ary_push(parser->line, P);
609 wiki_pop_from_stack(parser, NULL);
613 // Convert a single UTF-8 codepoint to UTF-32
615 // Expects an input buffer, src, containing a UTF-8 encoded character (which
616 // may be multi-byte). The end of the input buffer, end, is also passed in to
617 // allow the detection of invalidly truncated codepoints. The number of bytes
618 // in the UTF-8 character (between 1 and 4) is returned by reference in
621 // Raises a RangeError if the supplied character is invalid UTF-8.
622 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
625 if ((unsigned char)src[0] <= 0x7f)
631 else if ((src[0] & 0xe0) == 0xc0)
633 // byte starts with 110..... : this should be a two-byte sequence
636 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
637 else if (((unsigned char)src[0] == 0xc0) ||
638 ((unsigned char)src[0] == 0xc1))
639 // overlong encoding: lead byte of 110..... but code point <= 127
640 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
641 else if ((src[1] & 0xc0) != 0x80 )
642 // should have second byte starting with 10......
643 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
646 ((uint32_t)(src[0] & 0x1f)) << 6 |
650 else if ((src[0] & 0xf0) == 0xe0)
652 // byte starts with 1110.... : this should be a three-byte sequence
654 // missing second or third byte
655 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
656 else if (((src[1] & 0xc0) != 0x80 ) ||
657 ((src[2] & 0xc0) != 0x80 ))
658 // should have second and third bytes starting with 10......
659 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
662 ((uint32_t)(src[0] & 0x0f)) << 12 |
663 ((uint32_t)(src[1] & 0x3f)) << 6 |
667 else if ((src[0] & 0xf8) == 0xf0)
669 // bytes starts with 11110... : this should be a four-byte sequence
671 // missing second, third, or fourth byte
672 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
673 else if ((unsigned char)src[0] >= 0xf5 &&
674 (unsigned char)src[0] <= 0xf7)
675 // disallowed by RFC 3629 (codepoints above 0x10ffff)
676 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
677 else if (((src[1] & 0xc0) != 0x80 ) ||
678 ((src[2] & 0xc0) != 0x80 ) ||
679 ((src[3] & 0xc0) != 0x80 ))
680 // should have second and third bytes starting with 10......
681 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
684 ((uint32_t)(src[0] & 0x07)) << 18 |
685 ((uint32_t)(src[1] & 0x3f)) << 12 |
686 ((uint32_t)(src[1] & 0x3f)) << 6 |
691 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
695 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
697 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
698 char scratch = (character & 0xf000) >> 12;
699 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
700 scratch = (character & 0x0f00) >> 8;
701 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
702 scratch = (character & 0x00f0) >> 4;
703 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
704 scratch = character & 0x000f;
705 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
706 str_append(output, hex_string, sizeof(hex_string));
709 // trim parser->link_text in place
710 void wiki_trim_link_text(parser_t *parser)
712 char *src = parser->link_text->ptr;
713 char *start = src; // remember this so we can check if we're at the start
715 char *non_space = src; // remember last non-space character output
716 char *end = src + parser->link_text->len;
728 if (left != start || non_space + 1 != end)
730 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
731 parser->link_text->len = (non_space + 1) - left;
732 memmove(parser->link_text->ptr, left, parser->link_text->len);
736 // - non-printable (non-ASCII) characters converted to numeric entities
737 // - QUOT and AMP characters converted to named entities
738 // - if trim is true, leading and trailing whitespace trimmed
739 // - if trim is false, there is no special treatment of spaces
740 void wiki_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
742 char *src = parser->link_target->ptr;
743 char *start = src; // remember this so we can check if we're at the start
744 char *non_space = output->ptr + output->len; // remember last non-space character output
745 char *end = src + parser->link_target->len;
748 // need at most 8 bytes to display each input character (�)
749 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
751 char *old_ptr = output->ptr;
752 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
753 if (old_ptr != output->ptr) // may have moved
754 non_space += output->ptr - old_ptr;
759 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
760 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
762 else if (*src == '&')
764 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
765 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
767 else if (*src == '<' || *src == '>')
768 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
769 else if (*src == ' ' && src == start && trim)
770 start++; // we eat leading space
771 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
773 *(output->ptr + output->len) = *src;
776 else // all others: must convert to entities
779 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
781 non_space = output->ptr + output->len;
785 non_space = output->ptr + output->len;
789 // trim trailing space if necessary
790 if (trim && output->ptr + output->len != non_space)
791 output->len -= (output->ptr + output->len) - non_space;
794 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
797 parser.link_target = str_new_from_string(string);
798 GC_WRAP_STR(parser.link_target, link_target_gc);
799 str_t *output = str_new();
800 GC_WRAP_STR(output, output_gc);
801 wiki_append_sanitized_link_target(&parser, output, true);
802 return string_from_str(output);
805 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
807 // Leading and trailing whitespace trimmed. Spaces are converted to
808 // underscores if the parser space_to_underscore member is true.
809 static void wiki_encode_link_target(parser_t *parser)
811 char *src = parser->link_target->ptr;
812 char *start = src; // remember this so we can check if we're at the start
813 long len = parser->link_target->len;
816 char *end = src + len;
817 long dest_len = len * 2;
818 char *dest = ALLOC_N(char, dest_len);
819 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
820 char *non_space = dest; // remember last non-space character output
821 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
822 for (; src < end; src++)
824 // worst case: a single character may grow to 3 characters once encoded
825 if ((dest + 3) > (dest_ptr + dest_len))
827 // outgrowing buffer, must reallocate
828 char *old_dest = dest;
829 char *old_dest_ptr = dest_ptr;
831 dest = realloc(dest_ptr, dest_len);
834 // would have used reallocf, but this has to run on Linux too, not just Darwin
836 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
839 dest = dest_ptr + (old_dest - old_dest_ptr);
840 non_space = dest_ptr + (non_space - old_dest_ptr);
843 // pass through unreserved characters
844 if ((*src >= 'a' && *src <= 'z') ||
845 (*src >= 'A' && *src <= 'Z') ||
846 (*src >= '0' && *src <= '9') ||
855 else if (*src == ' ' && src == start)
856 start++; // we eat leading space
857 else if (*src == ' ' && parser->space_to_underscore)
859 else // everything else gets URL-encoded
862 *dest++ = hex[(unsigned char)(*src) / 16]; // left
863 *dest++ = hex[(unsigned char)(*src) % 16]; // right
869 // trim trailing space if necessary
870 if (non_space > dest_ptr && dest != non_space)
871 dest_len = non_space - dest_ptr;
873 dest_len = dest - dest_ptr;
874 str_clear(parser->link_target);
875 str_append(parser->link_target, dest_ptr, dest_len);
879 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
882 parser.space_to_underscore = false;
883 parser.link_target = str_new_from_string(in);
884 GC_WRAP_STR(parser.link_target, link_target_gc);
885 wiki_encode_link_target(&parser);
886 return string_from_str(parser.link_target);
889 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
890 // returns 0 (false) otherwise
891 bool wiki_blank(str_t *str)
895 for (char *ptr = str->ptr,
896 *end = str->ptr + str->len;
905 void wiki_rollback_failed_internal_link(parser_t *parser)
908 return; // nothing to do!
909 int scope_includes_separator = IN(SEPARATOR);
910 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
911 str_append(parser->output, link_start, sizeof(link_start) - 1);
912 if (parser->link_target->len > 0)
914 wiki_append_sanitized_link_target(parser, parser->output, false);
915 if (scope_includes_separator)
917 str_append(parser->output, separator, sizeof(separator) - 1);
918 if (parser->link_text->len > 0)
919 str_append_str(parser->output, parser->link_text);
922 parser->capture = NULL;
923 str_clear(parser->link_target);
924 str_clear(parser->link_text);
927 void wiki_rollback_failed_external_link(parser_t *parser)
929 if (!IN(EXT_LINK_START))
930 return; // nothing to do!
932 // store a couple of values before popping
933 int scope_includes_space = IN(SPACE);
934 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
935 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
937 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
938 if (parser->link_target->len > 0)
940 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
941 if (scope_includes_space)
943 str_append(parser->output, space, sizeof(space) - 1);
944 if (parser->link_text->len > 0)
945 str_append_str(parser->output, parser->link_text);
948 parser->capture = NULL;
949 str_clear(parser->link_target);
950 str_clear(parser->link_text);
953 void wiki_rollback_failed_link(parser_t *parser)
955 wiki_rollback_failed_internal_link(parser);
956 wiki_rollback_failed_external_link(parser);
959 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
963 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
967 VALUE autolink = Qtrue;
968 VALUE line_ending = rb_str_new2("\n");
969 VALUE external_link_class = rb_str_new2("external");
970 VALUE mailto_class = rb_str_new2("mailto");
971 VALUE internal_link_prefix = rb_str_new2("/wiki/");
972 VALUE img_prefix = rb_str_new2("/images/");
973 VALUE space_to_underscore = Qtrue;
974 VALUE minimum_fulltext_token_length = INT2NUM(3);
975 VALUE base_heading_level = INT2NUM(0);
977 // process options hash (override defaults)
978 if (!NIL_P(options) && TYPE(options) == T_HASH)
980 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
981 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
982 autolink = OVERRIDE_IF_SET(autolink);
983 line_ending = OVERRIDE_IF_SET(line_ending);
984 external_link_class = OVERRIDE_IF_SET(external_link_class);
985 mailto_class = OVERRIDE_IF_SET(mailto_class);
986 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
987 img_prefix = OVERRIDE_IF_SET(img_prefix);
988 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
989 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
990 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
993 // no need to call super here; rb_call_super()
994 rb_iv_set(self, "@autolink", autolink);
995 rb_iv_set(self, "@line_ending", line_ending);
996 rb_iv_set(self, "@external_link_class", external_link_class);
997 rb_iv_set(self, "@mailto_class", mailto_class);
998 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
999 rb_iv_set(self, "@img_prefix", img_prefix);
1000 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1001 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1002 rb_iv_set(self, "@base_heading_level", base_heading_level);
1006 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1008 for (int i = 0; i < 100000; i++)
1009 Wikitext_parser_parse(1, &string, self);
1013 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1015 // process arguments
1016 VALUE string, options;
1017 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1021 string = StringValue(string);
1023 // process options hash
1024 int base_indent = 0;
1025 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1026 if (!NIL_P(options) && TYPE(options) == T_HASH)
1028 // :indent => 0 (or more)
1029 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1031 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1032 if (indent == Qfalse)
1033 base_indent = -1; // indentation disabled
1036 base_indent = NUM2INT(indent);
1037 if (base_indent < 0)
1042 // :base_heading_level => 0/1/2/3/4/5/6
1043 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1044 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1047 // normalize, regardless of whether this came from instance variable or override
1048 if (base_heading_level < 0)
1049 base_heading_level = 0;
1050 if (base_heading_level > 6)
1051 base_heading_level = 6;
1054 char *p = RSTRING_PTR(string);
1055 long len = RSTRING_LEN(string);
1058 // access these once per parse
1059 VALUE line_ending = rb_iv_get(self, "@line_ending");
1060 line_ending = StringValue(line_ending);
1061 VALUE link_class = rb_iv_get(self, "@external_link_class");
1062 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1063 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1064 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1065 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1067 // set up parser struct to make passing parameters a little easier
1068 parser_t *parser = parser_new();
1069 GC_WRAP_PARSER(parser, parser_gc);
1070 parser->external_link_class = link_class;
1071 parser->mailto_class = mailto_class;
1072 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1073 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1074 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1075 parser->line_ending = str_new_from_string(line_ending);
1076 parser->base_indent = base_indent;
1077 parser->base_heading_level = base_heading_level;
1079 // this simple looping design leads to a single enormous function,
1080 // but it's faster than doing actual recursive descent and also secure in the face of
1081 // malicious input that seeks to overflow the stack
1082 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1083 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1084 // than a straightforward looping translator like this one anyway
1086 _token.type = NO_TOKEN;
1087 token_t *token = NULL;
1090 // note that whenever we grab a token we push it into the line buffer
1091 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1092 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1094 // check to see if we have a token hanging around from a previous iteration of this loop
1097 if (_token.type == NO_TOKEN)
1099 // first time here (haven't started scanning yet)
1101 next_token(token, NULL, p, pe);
1102 ary_push(parser->line_buffer, token->type);
1108 int type = token->type;
1110 // can't declare new variables inside a switch statement, so predeclare them here
1111 long remove_strong = -1;
1112 long remove_em = -1;
1114 // general purpose counters, flags and pointers
1118 str_t *output = NULL;
1120 str_t *token_str = &_token_str;
1122 // The following giant switch statement contains cases for all the possible token types.
1123 // In the most basic sense we are emitting the HTML that corresponds to each token,
1124 // but some tokens require context information in order to decide what to output.
1125 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1126 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1128 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1129 // - the line buffer (records tokens seen so far on the current line)
1130 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1132 // Although this is fairly complicated, there is one key simplifying factor:
1133 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1134 // scope stack (up to the current token) is valid; our translator can take this as a given.
1135 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1136 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1140 if (IN(NO_WIKI_START) || IN(PRE_START))
1142 str_append(parser->output, space, sizeof(space) - 1);
1145 else if (IN(BLOCKQUOTE_START))
1147 // this kind of nesting not allowed (to avoid user confusion)
1148 wiki_pop_excess_elements(parser);
1149 wiki_start_para_if_necessary(parser);
1150 output = parser->capture ? parser->capture : parser->output;
1151 str_append(output, space, sizeof(space) - 1);
1155 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1156 ary_push(parser->line, PRE);
1157 i = ary_count(parser->line, BLOCKQUOTE);
1158 j = ary_count(parser->scope, BLOCKQUOTE);
1161 // must pop (reduce nesting level)
1162 for (i = j - i; i > 0; i--)
1163 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1168 parser->pending_crlf = false;
1169 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1170 wiki_indent(parser);
1171 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1172 ary_push(parser->scope, PRE);
1177 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1179 wiki_emit_pending_crlf_if_necessary(parser);
1180 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1182 else if (IN(BLOCKQUOTE_START))
1184 wiki_rollback_failed_link(parser); // if any
1185 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1186 wiki_indent(parser);
1187 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1188 ary_push(parser->scope, PRE_START);
1189 ary_push(parser->line, PRE_START);
1191 else if (IN(BLOCKQUOTE))
1193 if (token->column_start == 1) // only allowed in first column
1195 wiki_rollback_failed_link(parser); // if any
1196 wiki_pop_all_from_stack(parser);
1197 wiki_indent(parser);
1198 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1199 ary_push(parser->scope, PRE_START);
1200 ary_push(parser->line, PRE_START);
1202 else // PRE_START illegal here
1204 output = parser->capture ? parser->capture : parser->output;
1205 wiki_pop_excess_elements(parser);
1206 wiki_start_para_if_necessary(parser);
1207 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1212 wiki_rollback_failed_link(parser); // if any
1213 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1214 wiki_indent(parser);
1215 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1216 ary_push(parser->scope, PRE_START);
1217 ary_push(parser->line, PRE_START);
1222 if (IN(NO_WIKI_START) || IN(PRE))
1224 wiki_emit_pending_crlf_if_necessary(parser);
1225 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1230 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1233 output = parser->capture ? parser->capture : parser->output;
1234 wiki_pop_excess_elements(parser);
1235 wiki_start_para_if_necessary(parser);
1236 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1242 if (IN(NO_WIKI_START) || IN(PRE_START))
1243 // no need to check for <pre>; can never appear inside it
1244 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1245 else if (IN(BLOCKQUOTE_START))
1247 // this kind of nesting not allowed (to avoid user confusion)
1248 wiki_pop_excess_elements(parser);
1249 wiki_start_para_if_necessary(parser);
1250 output = parser->capture ? parser->capture : parser->output;
1251 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1256 ary_push(parser->line, BLOCKQUOTE);
1258 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1259 i = ary_count(parser->line, BLOCKQUOTE);
1260 j = ary_count(parser->scope, BLOCKQUOTE);
1262 // 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
1263 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1265 ary_push(parser->line, BLOCKQUOTE);
1269 // now decide whether to push, pop or do nothing
1272 // must push (increase nesting level)
1273 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1274 for (i = i - j; i > 0; i--)
1276 wiki_indent(parser);
1277 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1278 str_append_str(parser->output, parser->line_ending);
1279 ary_push(parser->scope, BLOCKQUOTE);
1284 // must pop (reduce nesting level)
1285 for (i = j - i; i > 0; i--)
1286 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1289 // jump to top of the loop to process token we scanned during lookahead
1294 case BLOCKQUOTE_START:
1295 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1297 wiki_emit_pending_crlf_if_necessary(parser);
1298 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1300 else if (IN(BLOCKQUOTE_START))
1302 // nesting is fine here
1303 wiki_rollback_failed_link(parser); // if any
1304 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1305 wiki_indent(parser);
1306 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1307 str_append_str(parser->output, parser->line_ending);
1308 ary_push(parser->scope, BLOCKQUOTE_START);
1309 ary_push(parser->line, BLOCKQUOTE_START);
1311 else if (IN(BLOCKQUOTE))
1313 if (token->column_start == 1) // only allowed in first column
1315 wiki_rollback_failed_link(parser); // if any
1316 wiki_pop_all_from_stack(parser);
1317 wiki_indent(parser);
1318 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1319 str_append_str(parser->output, parser->line_ending);
1320 ary_push(parser->scope, BLOCKQUOTE_START);
1321 ary_push(parser->line, BLOCKQUOTE_START);
1323 else // BLOCKQUOTE_START illegal here
1325 output = parser->capture ? parser->capture : parser->output;
1326 wiki_pop_excess_elements(parser);
1327 wiki_start_para_if_necessary(parser);
1328 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1333 // would be nice to eliminate the repetition here but it's probably the clearest way
1334 wiki_rollback_failed_link(parser); // if any
1335 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1336 wiki_indent(parser);
1337 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1338 str_append_str(parser->output, parser->line_ending);
1339 ary_push(parser->scope, BLOCKQUOTE_START);
1340 ary_push(parser->line, BLOCKQUOTE_START);
1344 case BLOCKQUOTE_END:
1345 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1347 wiki_emit_pending_crlf_if_necessary(parser);
1348 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1352 if (IN(BLOCKQUOTE_START))
1353 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1356 output = parser->capture ? parser->capture : parser->output;
1357 wiki_pop_excess_elements(parser);
1358 wiki_start_para_if_necessary(parser);
1359 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1365 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1367 wiki_emit_pending_crlf_if_necessary(parser);
1368 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1372 wiki_pop_excess_elements(parser);
1373 wiki_start_para_if_necessary(parser);
1374 ary_push(parser->scope, NO_WIKI_START);
1375 ary_push(parser->line, NO_WIKI_START);
1380 if (IN(NO_WIKI_START))
1381 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1382 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1385 wiki_pop_excess_elements(parser);
1386 wiki_start_para_if_necessary(parser);
1387 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1392 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1394 wiki_emit_pending_crlf_if_necessary(parser);
1395 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1399 output = parser->capture ? parser->capture : parser->output;
1400 wiki_pop_excess_elements(parser);
1402 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1403 // otherwise, must open them
1406 j = parser->scope->count;
1407 for (j = j - 1; j >= 0; j--)
1409 int val = ary_entry(parser->scope, j);
1410 if (val == STRONG || val == STRONG_START)
1412 str_append(output, strong_end, sizeof(strong_end) - 1);
1415 else if (val == EM || val == EM_START)
1417 str_append(output, em_end, sizeof(em_end) - 1);
1422 if (remove_strong > remove_em) // must remove strong first
1424 ary_pop(parser->scope);
1426 ary_pop(parser->scope);
1427 else // there was no em to remove!, so consider this an opening em tag
1429 str_append(output, em_start, sizeof(em_start) - 1);
1430 ary_push(parser->scope, EM);
1431 ary_push(parser->line, EM);
1434 else if (remove_em > remove_strong) // must remove em first
1436 ary_pop(parser->scope);
1437 if (remove_strong > -1)
1438 ary_pop(parser->scope);
1439 else // there was no strong to remove!, so consider this an opening strong tag
1441 str_append(output, strong_start, sizeof(strong_start) - 1);
1442 ary_push(parser->scope, STRONG);
1443 ary_push(parser->line, STRONG);
1446 else // no strong or em to remove, so this must be a new opening of both
1448 wiki_start_para_if_necessary(parser);
1449 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1450 ary_push(parser->scope, STRONG);
1451 ary_push(parser->line, STRONG);
1452 ary_push(parser->scope, EM);
1453 ary_push(parser->line, EM);
1458 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1460 wiki_emit_pending_crlf_if_necessary(parser);
1461 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1465 output = parser->capture ? parser->capture : parser->output;
1466 if (IN(STRONG_START))
1467 // already in span started with <strong>, no choice but to emit this literally
1468 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1469 else if (IN(STRONG))
1470 // STRONG already seen, this is a closing tag
1471 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1474 // this is a new opening
1475 wiki_pop_excess_elements(parser);
1476 wiki_start_para_if_necessary(parser);
1477 str_append(output, strong_start, sizeof(strong_start) - 1);
1478 ary_push(parser->scope, STRONG);
1479 ary_push(parser->line, STRONG);
1485 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1487 wiki_emit_pending_crlf_if_necessary(parser);
1488 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1492 output = parser->capture ? parser->capture : parser->output;
1493 if (IN(STRONG_START) || IN(STRONG))
1494 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1497 wiki_pop_excess_elements(parser);
1498 wiki_start_para_if_necessary(parser);
1499 str_append(output, strong_start, sizeof(strong_start) - 1);
1500 ary_push(parser->scope, STRONG_START);
1501 ary_push(parser->line, STRONG_START);
1507 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1509 wiki_emit_pending_crlf_if_necessary(parser);
1510 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1514 output = parser->capture ? parser->capture : parser->output;
1515 if (IN(STRONG_START))
1516 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1519 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1520 wiki_pop_excess_elements(parser);
1521 wiki_start_para_if_necessary(parser);
1522 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1528 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1530 wiki_emit_pending_crlf_if_necessary(parser);
1531 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1535 output = parser->capture ? parser->capture : parser->output;
1537 // already in span started with <em>, no choice but to emit this literally
1538 str_append(output, literal_em, sizeof(literal_em) - 1);
1540 // EM already seen, this is a closing tag
1541 wiki_pop_from_stack_up_to(parser, output, EM, true);
1544 // this is a new opening
1545 wiki_pop_excess_elements(parser);
1546 wiki_start_para_if_necessary(parser);
1547 str_append(output, em_start, sizeof(em_start) - 1);
1548 ary_push(parser->scope, EM);
1549 ary_push(parser->line, EM);
1555 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1557 wiki_emit_pending_crlf_if_necessary(parser);
1558 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1562 output = parser->capture ? parser->capture : parser->output;
1563 if (IN(EM_START) || IN(EM))
1564 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1567 wiki_pop_excess_elements(parser);
1568 wiki_start_para_if_necessary(parser);
1569 str_append(output, em_start, sizeof(em_start) - 1);
1570 ary_push(parser->scope, EM_START);
1571 ary_push(parser->line, EM_START);
1577 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1579 wiki_emit_pending_crlf_if_necessary(parser);
1580 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1584 output = parser->capture ? parser->capture : parser->output;
1586 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1589 // no EM_START in scope, so must interpret the TT_END without any special meaning
1590 wiki_pop_excess_elements(parser);
1591 wiki_start_para_if_necessary(parser);
1592 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1598 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1600 wiki_emit_pending_crlf_if_necessary(parser);
1601 str_append(parser->output, backtick, sizeof(backtick) - 1);
1605 output = parser->capture ? parser->capture : parser->output;
1607 // already in span started with <tt>, no choice but to emit this literally
1608 str_append(output, backtick, sizeof(backtick) - 1);
1610 // TT (`) already seen, this is a closing tag
1611 wiki_pop_from_stack_up_to(parser, output, TT, true);
1614 // this is a new opening
1615 wiki_pop_excess_elements(parser);
1616 wiki_start_para_if_necessary(parser);
1617 str_append(output, tt_start, sizeof(tt_start) - 1);
1618 ary_push(parser->scope, TT);
1619 ary_push(parser->line, TT);
1625 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1627 wiki_emit_pending_crlf_if_necessary(parser);
1628 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1632 output = parser->capture ? parser->capture : parser->output;
1633 if (IN(TT_START) || IN(TT))
1634 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1637 wiki_pop_excess_elements(parser);
1638 wiki_start_para_if_necessary(parser);
1639 str_append(output, tt_start, sizeof(tt_start) - 1);
1640 ary_push(parser->scope, TT_START);
1641 ary_push(parser->line, TT_START);
1647 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1649 wiki_emit_pending_crlf_if_necessary(parser);
1650 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1654 output = parser->capture ? parser->capture : parser->output;
1656 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1659 // no TT_START in scope, so must interpret the TT_END without any special meaning
1660 wiki_pop_excess_elements(parser);
1661 wiki_start_para_if_necessary(parser);
1662 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1669 if (IN(NO_WIKI_START) || IN(PRE_START))
1671 // no need to check for PRE; can never appear inside it
1672 str_append(parser->output, token->start, TOKEN_LEN(token));
1676 // count number of tokens in line and scope stacks
1677 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1678 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1679 j = parser->scope->count - bq_count;
1682 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1686 if (type == OL || type == UL)
1689 if (i - k >= 2) // already seen at least one OL or UL
1691 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1696 ary_push(parser->line, type);
1697 ary_push(parser->line, LI);
1699 // want to compare line with scope but can only do so if scope has enough items on it
1702 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1703 ary_entry(parser->scope, i + bq_count - 1) == LI)
1705 // line and scope match at this point: do nothing yet
1709 // item just pushed onto line does not match corresponding slot of scope!
1710 for (; j >= i - 2; j--)
1711 // must pop back before emitting
1712 wiki_pop_from_stack(parser, NULL);
1714 // will emit UL or OL, then LI
1718 else // line stack size now exceeds scope stack size: must increase nesting level
1719 break; // will emit UL or OL, then LI
1723 // not a OL or UL token!
1725 // must close existing LI and re-open new one
1726 wiki_pop_from_stack(parser, NULL);
1729 // item just pushed onto line does not match corresponding slot of scope!
1731 // must pop back before emitting
1732 wiki_pop_from_stack(parser, NULL);
1740 if (type == OL || type == UL)
1742 // if LI is at the top of a stack this is the start of a nested list
1743 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1745 // so we should precede it with a CRLF, and indicate that it's a nested list
1746 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1747 ary_push(parser->scope, NESTED_LIST);
1751 // this is a new list
1752 if (IN(BLOCKQUOTE_START))
1753 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1755 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1759 wiki_indent(parser);
1761 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1762 else if (type == UL)
1763 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1764 ary_push(parser->scope, type);
1765 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1767 else if (type == SPACE)
1768 // silently throw away the optional SPACE token after final list marker
1771 wiki_indent(parser);
1772 str_append(parser->output, li_start, sizeof(li_start) - 1);
1773 ary_push(parser->scope, LI);
1775 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1776 if (type == OL || type == UL)
1779 while (k++, NEXT_TOKEN(), (type = token->type))
1781 if (type == OL || type == UL)
1782 str_append(parser->output, token->start, TOKEN_LEN(token));
1783 else if (type == SPACE && k == 1)
1785 // silently throw away the optional SPACE token after final list marker
1794 // jump to top of the loop to process token we scanned during lookahead
1803 if (IN(NO_WIKI_START) || IN(PRE_START))
1805 // no need to check for PRE; can never appear inside it
1806 str_append(parser->output, token->start, TOKEN_LEN(token));
1810 // pop up to but not including the last BLOCKQUOTE on the scope stack
1811 if (IN(BLOCKQUOTE_START))
1812 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1814 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1816 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1817 ary_push(parser->line, type);
1818 i = ary_count(parser->line, BLOCKQUOTE);
1819 j = ary_count(parser->scope, BLOCKQUOTE);
1821 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1824 // must pop (reduce nesting level)
1825 for (i = j - i; i > 0; i--)
1826 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1829 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1830 while (NEXT_TOKEN(), (token->type == SPACE))
1833 ary_push(parser->scope, type);
1834 wiki_indent(parser);
1836 // take base_heading_level into account
1837 type += base_heading_level;
1838 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1841 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1842 if (type == H6_START)
1843 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1844 else if (type == H5_START)
1845 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1846 else if (type == H4_START)
1847 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1848 else if (type == H3_START)
1849 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1850 else if (type == H2_START)
1851 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1852 else if (type == H1_START)
1853 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1855 // jump to top of the loop to process token we scanned during lookahead
1864 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1866 wiki_emit_pending_crlf_if_necessary(parser);
1867 str_append(parser->output, token->start, TOKEN_LEN(token));
1871 wiki_rollback_failed_external_link(parser); // if any
1872 if ((type == H6_END && !IN(H6_START)) ||
1873 (type == H5_END && !IN(H5_START)) ||
1874 (type == H4_END && !IN(H4_START)) ||
1875 (type == H3_END && !IN(H3_START)) ||
1876 (type == H2_END && !IN(H2_START)) ||
1877 (type == H1_END && !IN(H1_START)))
1879 // literal output only if not in appropriate scope (we stay silent in that case)
1880 wiki_start_para_if_necessary(parser);
1881 str_append(parser->output, token->start, TOKEN_LEN(token));
1887 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1889 wiki_emit_pending_crlf_if_necessary(parser);
1890 str_append(parser->output, token->start, TOKEN_LEN(token));
1894 wiki_pop_excess_elements(parser);
1895 wiki_start_para_if_necessary(parser);
1896 token_str->ptr = token->start;
1897 token_str->len = TOKEN_LEN(token);
1898 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
1903 if (IN(NO_WIKI_START))
1904 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1905 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1906 str_append(parser->output, token->start, TOKEN_LEN(token));
1907 else if (IN(LINK_START))
1909 // if the URI were allowed it would have been handled already in LINK_START
1910 wiki_rollback_failed_internal_link(parser);
1911 token_str->ptr = token->start;
1912 token_str->len = TOKEN_LEN(token);
1913 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1915 else if (IN(EXT_LINK_START))
1917 if (parser->link_target->len == 0)
1919 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1920 token_str->ptr = token->start;
1921 token_str->len = TOKEN_LEN(token);
1923 if (token->type == SPACE)
1925 ary_push(parser->scope, SPACE);
1926 str_append_str(parser->link_target, token_str);
1927 str_clear(parser->link_text);
1928 parser->capture = parser->link_text;
1929 token = NULL; // silently consume space
1933 // didn't see the space! this must be an error
1934 wiki_pop_from_stack(parser, NULL);
1935 wiki_pop_excess_elements(parser);
1936 wiki_start_para_if_necessary(parser);
1937 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1938 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1942 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1946 wiki_pop_excess_elements(parser);
1947 wiki_start_para_if_necessary(parser);
1948 token_str->ptr = token->start;
1949 token_str->len = TOKEN_LEN(token);
1950 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1955 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
1956 str_append(parser->output, token->start, TOKEN_LEN(token));
1957 else if (IN(EXT_LINK_START))
1959 if (parser->link_target->len == 0)
1961 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1962 token_str->ptr = token->start;
1963 token_str->len = TOKEN_LEN(token);
1965 if (token->type == SPACE)
1967 ary_push(parser->scope, PATH);
1968 ary_push(parser->scope, SPACE);
1969 str_append_str(parser->link_target, token_str);
1970 str_clear(parser->link_text);
1971 parser->capture = parser->link_text;
1972 token = NULL; // silently consume space
1976 // didn't see the space! this must be an error
1977 wiki_pop_from_stack(parser, NULL);
1978 wiki_pop_excess_elements(parser);
1979 wiki_start_para_if_necessary(parser);
1980 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1981 str_append_str(parser->output, token_str);
1985 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1989 output = parser->capture ? parser->capture : parser->output;
1990 wiki_pop_excess_elements(parser);
1991 wiki_start_para_if_necessary(parser);
1992 str_append(output, token->start, TOKEN_LEN(token));
1996 // internal links (links to other wiki articles) look like this:
1997 // [[another article]] (would point at, for example, "/wiki/another_article")
1998 // [[the other article|the link text we'll use for it]]
1999 // [[the other article | the link text we'll use for it]]
2000 // MediaWiki has strict requirements about what it will accept as a link target:
2001 // all wikitext markup is disallowed:
2002 // example [[foo ''bar'' baz]]
2003 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2004 // example [[foo <em>bar</em> baz]]
2005 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2006 // example [[foo <nowiki>''</nowiki> baz]]
2007 // renders [[foo '' baz]] (ie. not a link)
2008 // example [[foo <bar> baz]]
2009 // renders [[foo <bar> baz]] (ie. not a link)
2010 // HTML entities and non-ASCII, however, make it through:
2011 // example [[foo €]]
2012 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2013 // example [[foo €]]
2014 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2015 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2016 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2017 // everything else will be rejected
2019 output = parser->capture ? parser->capture : parser->output;
2020 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2022 wiki_emit_pending_crlf_if_necessary(parser);
2023 str_append(output, link_start, sizeof(link_start) - 1);
2025 else if (IN(EXT_LINK_START))
2026 // already in external link scope! (and in fact, must be capturing link_text right now)
2027 str_append(output, link_start, sizeof(link_start) - 1);
2028 else if (IN(LINK_START))
2030 // already in internal link scope! this is a syntax error
2031 wiki_rollback_failed_internal_link(parser);
2032 str_append(parser->output, link_start, sizeof(link_start) - 1);
2034 else if (IN(SEPARATOR))
2036 // scanning internal link text
2038 else // not in internal link scope yet
2040 // will either emit a link, or the rollback of a failed link, so start the para now
2041 wiki_pop_excess_elements(parser);
2042 wiki_start_para_if_necessary(parser);
2043 ary_push(parser->scope, LINK_START);
2045 // look ahead and try to gobble up link target
2046 while (NEXT_TOKEN(), (type = token->type))
2048 if (type == SPACE ||
2049 type == SPECIAL_URI_CHARS ||
2051 type == PRINTABLE ||
2055 type == QUOT_ENTITY ||
2057 type == AMP_ENTITY ||
2058 type == IMG_START ||
2060 type == LEFT_CURLY ||
2061 type == RIGHT_CURLY)
2063 // accumulate these tokens into link_target
2064 if (parser->link_target->len == 0)
2066 str_clear(parser->link_target);
2067 parser->capture = parser->link_target;
2069 if (type == QUOT_ENTITY)
2070 // don't insert the entity, insert the literal quote
2071 str_append(parser->link_target, quote, sizeof(quote) - 1);
2072 else if (type == AMP_ENTITY)
2073 // don't insert the entity, insert the literal ampersand
2074 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2076 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2078 else if (type == LINK_END)
2080 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2081 wiki_rollback_failed_internal_link(parser);
2082 break; // jump back to top of loop (will handle this in LINK_END case below)
2084 else if (type == SEPARATOR)
2086 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2087 wiki_rollback_failed_internal_link(parser);
2090 ary_push(parser->scope, SEPARATOR);
2091 str_clear(parser->link_text);
2092 parser->capture = parser->link_text;
2097 else // unexpected token (syntax error)
2099 wiki_rollback_failed_internal_link(parser);
2100 break; // jump back to top of loop to handle unexpected token
2104 // jump to top of the loop to process token we scanned during lookahead (if any)
2110 output = parser->capture ? parser->capture : parser->output;
2111 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2113 wiki_emit_pending_crlf_if_necessary(parser);
2114 str_append(output, link_end, sizeof(link_end) - 1);
2116 else if (IN(EXT_LINK_START))
2117 // already in external link scope! (and in fact, must be capturing link_text right now)
2118 str_append(output, link_end, sizeof(link_end) - 1);
2119 else if (IN(LINK_START)) // in internal link scope!
2121 if (wiki_blank(parser->link_target))
2123 // special case for inputs like "[[ ]]"
2124 wiki_rollback_failed_internal_link(parser);
2125 str_append(parser->output, link_end, sizeof(link_end) - 1);
2128 if (parser->link_text->len == 0 ||
2129 wiki_blank(parser->link_text))
2131 // use link target as link text
2132 str_clear(parser->link_text);
2133 wiki_append_sanitized_link_target(parser, parser->link_text, true);
2136 wiki_trim_link_text(parser);
2137 wiki_encode_link_target(parser);
2138 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2139 parser->capture = NULL;
2140 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, false);
2141 str_clear(parser->link_target);
2142 str_clear(parser->link_text);
2144 else // wasn't in internal link scope
2146 wiki_pop_excess_elements(parser);
2147 wiki_start_para_if_necessary(parser);
2148 str_append(output, link_end, sizeof(link_end) - 1);
2152 // external links look like this:
2153 // [http://google.com/ the link text]
2154 // [/other/page/on/site see this page]
2155 // strings in square brackets which don't match this syntax get passed through literally; eg:
2156 // he was very angery [sic] about the turn of events
2157 case EXT_LINK_START:
2158 output = parser->capture ? parser->capture : parser->output;
2159 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2161 wiki_emit_pending_crlf_if_necessary(parser);
2162 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2164 else if (IN(EXT_LINK_START))
2165 // already in external link scope! (and in fact, must be capturing link_text right now)
2166 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2167 else if (IN(LINK_START))
2169 // already in internal link scope!
2170 if (parser->link_target->len == 0 || !IN(SPACE))
2171 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2172 else // link target has already been scanned
2173 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2175 else // not in external link scope yet
2177 // will either emit a link, or the rollback of a failed link, so start the para now
2178 wiki_pop_excess_elements(parser);
2179 wiki_start_para_if_necessary(parser);
2181 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2183 if (token->type == URI || token->type == PATH)
2184 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2186 // only get here if there was a syntax error (missing URI)
2187 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2188 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2193 output = parser->capture ? parser->capture : parser->output;
2194 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2196 wiki_emit_pending_crlf_if_necessary(parser);
2197 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2199 else if (IN(EXT_LINK_START))
2201 if (parser->link_text->len == 0)
2202 // syntax error: external link with no link text
2203 wiki_rollback_failed_external_link(parser);
2207 j = IN(PATH) ? Qnil : parser->external_link_class;
2208 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2209 parser->capture = NULL;
2210 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2212 str_clear(parser->link_target);
2213 str_clear(parser->link_text);
2217 wiki_pop_excess_elements(parser);
2218 wiki_start_para_if_necessary(parser);
2219 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2224 output = parser->capture ? parser->capture : parser->output;
2225 wiki_pop_excess_elements(parser);
2226 wiki_start_para_if_necessary(parser);
2227 str_append(output, separator, sizeof(separator) - 1);
2231 output = parser->capture ? parser->capture : parser->output;
2232 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2234 wiki_emit_pending_crlf_if_necessary(parser);
2235 str_append(output, token->start, TOKEN_LEN(token));
2239 // peek ahead to see next token
2240 char *token_ptr = token->start;
2241 int token_len = TOKEN_LEN(token);
2244 if ((type == H6_END && IN(H6_START)) ||
2245 (type == H5_END && IN(H5_START)) ||
2246 (type == H4_END && IN(H4_START)) ||
2247 (type == H3_END && IN(H3_START)) ||
2248 (type == H2_END && IN(H2_START)) ||
2249 (type == H1_END && IN(H1_START)))
2251 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2256 wiki_pop_excess_elements(parser);
2257 wiki_start_para_if_necessary(parser);
2258 str_append(output, token_ptr, token_len);
2261 // jump to top of the loop to process token we scanned during lookahead
2269 case DECIMAL_ENTITY:
2270 // pass these through unaltered as they are case sensitive
2271 output = parser->capture ? parser->capture : parser->output;
2272 wiki_pop_excess_elements(parser);
2273 wiki_start_para_if_necessary(parser);
2274 str_append(output, token->start, TOKEN_LEN(token));
2278 // normalize hex entities (downcase them)
2279 output = parser->capture ? parser->capture : parser->output;
2280 wiki_pop_excess_elements(parser);
2281 wiki_start_para_if_necessary(parser);
2282 str_append(output, token->start, TOKEN_LEN(token));
2283 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2287 output = parser->capture ? parser->capture : parser->output;
2288 wiki_pop_excess_elements(parser);
2289 wiki_start_para_if_necessary(parser);
2290 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2294 output = parser->capture ? parser->capture : parser->output;
2295 wiki_pop_excess_elements(parser);
2296 wiki_start_para_if_necessary(parser);
2297 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2301 output = parser->capture ? parser->capture : parser->output;
2302 wiki_pop_excess_elements(parser);
2303 wiki_start_para_if_necessary(parser);
2304 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2308 output = parser->capture ? parser->capture : parser->output;
2309 wiki_pop_excess_elements(parser);
2310 wiki_start_para_if_necessary(parser);
2311 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2315 if (IN(NO_WIKI_START) || IN(PRE) || IN(PRE_START))
2317 wiki_emit_pending_crlf_if_necessary(parser);
2318 str_append(parser->output, token->start, TOKEN_LEN(token));
2320 else if (parser->capture)
2321 str_append(parser->capture, token->start, TOKEN_LEN(token));
2324 // not currently capturing: will be emitting something on success or failure, so get ready
2325 wiki_pop_excess_elements(parser);
2326 wiki_start_para_if_necessary(parser);
2328 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2329 // will cheat here and abuse the link_target capture buffer to accumulate text
2330 while (NEXT_TOKEN(), (type = token->type))
2332 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2333 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2334 else if (type == IMG_END && parser->link_target->len > 0)
2337 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2341 else // unexpected token or zero-length target (syntax error)
2344 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2345 if (parser->link_target->len > 0)
2346 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2351 // jump to top of the loop to process token we scanned during lookahead
2352 str_clear(parser->link_target);
2358 i = parser->pending_crlf;
2359 parser->pending_crlf = false;
2360 wiki_rollback_failed_link(parser); // if any
2361 if (IN(NO_WIKI_START) || IN(PRE_START))
2363 ary_clear(parser->line_buffer);
2364 str_append_str(parser->output, parser->line_ending);
2369 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2370 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2371 // don't emit in this case
2372 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2375 if (ary_entry(parser->line_buffer, -2) == PRE)
2377 // only thing on line is the PRE: emit pending line ending (if we had one)
2379 str_append_str(parser->output, parser->line_ending);
2382 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2383 ary_clear(parser->line);
2384 ary_clear(parser->line_buffer);
2386 // peek ahead to see if this is definitely the end of the PRE block
2389 if (type != BLOCKQUOTE && type != PRE)
2390 // this is definitely the end of the block, so don't emit
2391 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2393 // potentially will emit
2394 parser->pending_crlf = true;
2396 continue; // jump back to top of loop to handle token grabbed via lookahead
2401 parser->pending_crlf = true;
2403 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2404 // as a side effect, this handles any open span-level elements and unclosed blocks
2405 // (with special handling for P blocks and LI elements)
2406 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2407 for (j = parser->scope->count; j > i; j--)
2409 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2411 parser->pending_crlf = false;
2415 // special handling on last iteration through the loop if the top item on the scope is a P block
2416 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2418 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2419 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2420 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2421 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2422 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2424 parser->pending_crlf = false;
2426 // not a paragraph break!
2429 wiki_pop_from_stack(parser, NULL);
2433 // delete the entire contents of the line scope stack and buffer
2434 ary_clear(parser->line);
2435 ary_clear(parser->line_buffer);
2438 case SPECIAL_URI_CHARS:
2444 output = parser->capture ? parser->capture : parser->output;
2445 wiki_pop_excess_elements(parser);
2446 wiki_start_para_if_necessary(parser);
2447 str_append(output, token->start, TOKEN_LEN(token));
2451 output = parser->capture ? parser->capture : parser->output;
2452 wiki_pop_excess_elements(parser);
2453 wiki_start_para_if_necessary(parser);
2454 wiki_append_entity_from_utf32_char(output, token->code_point);
2458 // special case for input like " foo\n " (see pre_spec.rb)
2460 ary_entry(parser->line_buffer, -2) == PRE &&
2461 parser->pending_crlf)
2462 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2464 // close any open scopes on hitting EOF
2465 wiki_rollback_failed_link(parser); // if any
2466 wiki_pop_all_from_stack(parser);
2467 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2473 // reset current token; forcing lexer to return another token at the top of the loop
2477 // nasty hack to avoid re-allocating our return value
2478 str_append(parser->output, null_str, 1); // null-terminate
2479 len = parser->output->len - 1; // don't count null termination
2481 #if defined(RUBY_1_9_x)
2482 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2483 free(RSTRING_PTR(out));
2484 RSTRING(out)->as.heap.aux.capa = len;
2485 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2486 RSTRING(out)->as.heap.len = len;
2487 #elif defined(RUBY_1_8_x)
2488 VALUE out = rb_str_new2("");
2489 free(RSTRING_PTR(out));
2490 RSTRING(out)->len = len;
2491 RSTRING(out)->aux.capa = len;
2492 RSTRING(out)->ptr = parser->output->ptr;
2494 #error unsupported RUBY_VERSION
2496 parser->output->ptr = NULL; // don't double-free