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)
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)
36 // poor man's object orientation in C:
37 // instead of passing around multiple parameters between functions in the parser
38 // we pack everything into a struct and pass around only a pointer to that
41 str_t *capture; // capturing to link_target, link_text, or NULL (direct to output, not capturing)
42 str_t *output; // for accumulating output to be returned
43 str_t *link_target; // short term "memory" for parsing links
44 str_t *link_text; // short term "memory" for parsing links
46 str_t *tabulation; // caching buffer for emitting indentation
47 ary_t *scope; // stack for tracking scope
48 ary_t *line; // stack for tracking scope as implied by current line
49 ary_t *line_buffer; // stack for tracking raw tokens (not scope) on current line
50 VALUE external_link_class; // CSS class applied to external links
51 VALUE mailto_class; // CSS class applied to email (mailto) links
52 VALUE img_prefix; // path prepended when emitting img tags
53 int base_indent; // controlled by the :indent option to Wikitext::Parser#parse
54 int current_indent; // fluctuates according to currently nested structures
55 int base_heading_level;
58 bool space_to_underscore;
61 const char null_str[] = { 0 };
62 const char escaped_no_wiki_start[] = "<nowiki>";
63 const char escaped_no_wiki_end[] = "</nowiki>";
64 const char literal_strong_em[] = "'''''";
65 const char literal_strong[] = "'''";
66 const char literal_em[] = "''";
67 const char escaped_em_start[] = "<em>";
68 const char escaped_em_end[] = "</em>";
69 const char escaped_strong_start[] = "<strong>";
70 const char escaped_strong_end[] = "</strong>";
71 const char escaped_tt_start[] = "<tt>";
72 const char escaped_tt_end[] = "</tt>";
73 const char pre_start[] = "<pre>";
74 const char pre_end[] = "</pre>";
75 const char escaped_pre_start[] = "<pre>";
76 const char escaped_pre_end[] = "</pre>";
77 const char blockquote_start[] = "<blockquote>";
78 const char blockquote_end[] = "</blockquote>";
79 const char escaped_blockquote_start[] = "<blockquote>";
80 const char escaped_blockquote_end[] = "</blockquote>";
81 const char strong_em_start[] = "<strong><em>";
82 const char strong_start[] = "<strong>";
83 const char strong_end[] = "</strong>";
84 const char em_start[] = "<em>";
85 const char em_end[] = "</em>";
86 const char tt_start[] = "<tt>";
87 const char tt_end[] = "</tt>";
88 const char ol_start[] = "<ol>";
89 const char ol_end[] = "</ol>";
90 const char ul_start[] = "<ul>";
91 const char ul_end[] = "</ul>";
92 const char li_start[] = "<li>";
93 const char li_end[] = "</li>";
94 const char h6_start[] = "<h6>";
95 const char h6_end[] = "</h6>";
96 const char h5_start[] = "<h5>";
97 const char h5_end[] = "</h5>";
98 const char h4_start[] = "<h4>";
99 const char h4_end[] = "</h4>";
100 const char h3_start[] = "<h3>";
101 const char h3_end[] = "</h3>";
102 const char h2_start[] = "<h2>";
103 const char h2_end[] = "</h2>";
104 const char h1_start[] = "<h1>";
105 const char h1_end[] = "</h1>";
106 const char p_start[] = "<p>";
107 const char p_end[] = "</p>";
108 const char space[] = " ";
109 const char a_start[] = "<a href=\"";
110 const char a_class[] = "\" class=\"";
111 const char a_start_close[] = "\">";
112 const char a_end[] = "</a>";
113 const char link_start[] = "[[";
114 const char link_end[] = "]]";
115 const char separator[] = "|";
116 const char ext_link_start[] = "[";
117 const char backtick[] = "`";
118 const char quote[] = "\"";
119 const char ampersand[] = "&";
120 const char quot_entity[] = """;
121 const char amp_entity[] = "&";
122 const char lt_entity[] = "<";
123 const char gt_entity[] = ">";
124 const char escaped_blockquote[] = "> ";
125 const char ext_link_end[] = "]";
126 const char literal_img_start[] = "{{";
127 const char img_start[] = "<img src=\"";
128 const char img_end[] = "\" />";
129 const char img_alt[] = "\" alt=\"";
131 // Mark the parser struct designated by ptr as a participant in Ruby's
132 // mark-and-sweep garbage collection scheme. A variable named name is placed on
133 // the C stack to prevent the structure from being prematurely collected.
134 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
136 parser_t *parser_new(void)
138 parser_t *parser = ALLOC_N(parser_t, 1);
139 parser->capture = NULL; // not a real instance, pointer to other member's instance
140 parser->output = str_new();
141 parser->link_target = str_new();
142 parser->link_text = str_new();
143 parser->line_ending = NULL; // caller should set up
144 parser->tabulation = str_new();
145 parser->scope = ary_new();
146 parser->line = ary_new();
147 parser->line_buffer = ary_new();
148 parser->external_link_class = Qnil; // caller should set up
149 parser->mailto_class = Qnil; // caller should set up
150 parser->img_prefix = Qnil; // caller should set up
151 parser->base_indent = 0;
152 parser->current_indent = 0;
153 parser->base_heading_level = 0;
154 parser->pending_crlf = false;
155 parser->autolink = true;
156 parser->space_to_underscore = true;
160 void parser_free(parser_t *parser)
162 // we don't free parser->capture; it's just a redundant pointer
163 if (parser->output) str_free(parser->output);
164 if (parser->link_target) str_free(parser->link_target);
165 if (parser->link_text) str_free(parser->link_text);
166 if (parser->line_ending) str_free(parser->line_ending);
167 if (parser->tabulation) str_free(parser->tabulation);
168 if (parser->scope) ary_free(parser->scope);
169 if (parser->line) ary_free(parser->line);
170 if (parser->line_buffer) ary_free(parser->line_buffer);
174 // for testing and debugging only
175 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
179 string = StringValue(string);
180 VALUE tokens = rb_ary_new();
181 char *p = RSTRING_PTR(string);
182 long len = RSTRING_LEN(string);
185 next_token(&token, NULL, p, pe);
186 rb_ary_push(tokens, wiki_token(&token));
187 while (token.type != END_OF_FILE)
189 next_token(&token, &token, NULL, pe);
190 rb_ary_push(tokens, wiki_token(&token));
195 // for benchmarking raw tokenization speed only
196 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
200 string = StringValue(string);
201 char *p = RSTRING_PTR(string);
202 long len = RSTRING_LEN(string);
205 next_token(&token, NULL, p, pe);
206 while (token.type != END_OF_FILE)
207 next_token(&token, &token, NULL, pe);
211 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
214 VALUE string, options;
215 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
219 string = StringValue(string);
220 VALUE tokens = rb_ary_new();
222 // check instance variables
223 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
225 // process options hash (can override instance variables)
226 if (!NIL_P(options) && TYPE(options) == T_HASH)
228 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
229 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
231 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
236 char *p = RSTRING_PTR(string);
237 long len = RSTRING_LEN(string);
240 token_t *_token = &token;
241 next_token(&token, NULL, p, pe);
242 while (token.type != END_OF_FILE)
249 if (TOKEN_LEN(_token) >= min_len)
250 rb_ary_push(tokens, TOKEN_TEXT(_token));
253 // ignore everything else
256 next_token(&token, &token, NULL, pe);
261 // we downcase "in place", overwriting the original contents of the buffer
262 void wiki_downcase_bang(char *ptr, long len)
264 for (long i = 0; i < len; i++)
266 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
271 // prepare hyperlink and append it to parser->output
272 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
273 // or merely the literal link target
274 // if link_text is Qnil, the link_target is re-used for the link text
275 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, bool check_autolink)
277 if (check_autolink && !parser->autolink)
278 str_append_str(parser->output, link_target);
281 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
282 if (!NIL_P(link_prefix))
283 str_append_string(parser->output, link_prefix);
284 str_append_str(parser->output, link_target);
286 // special handling for mailto URIs
287 const char *mailto = "mailto:";
288 if (NIL_P(link_prefix) &&
289 link_target->len >= (long)sizeof(mailto) &&
290 strncmp(mailto, link_target->ptr, sizeof(mailto)) == 0)
291 link_class = parser->mailto_class; // use mailto_class from parser
292 if (link_class != Qnil)
294 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
295 str_append_string(parser->output, link_class);
297 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
298 if (!link_text || link_text->len == 0) // re-use link_target
299 str_append_str(parser->output, link_target);
301 str_append_str(parser->output, link_text);
302 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
306 void wiki_append_img(parser_t *parser, char *token_ptr, int token_len)
308 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
309 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
310 str_append_string(parser->output, parser->img_prefix);
311 str_append(parser->output, token_ptr, token_len);
312 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
313 str_append(parser->output, token_ptr, token_len);
314 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
317 // will emit indentation only if we are about to emit any of:
318 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
319 // each time we enter one of those spans must ++ the indentation level
320 void wiki_indent(parser_t *parser)
322 if (parser->base_indent == -1) // indentation disabled
324 int space_count = parser->current_indent + parser->base_indent;
327 char *old_end, *new_end;
328 if (parser->tabulation->len < space_count)
329 str_grow(parser->tabulation, space_count); // reallocates if necessary
330 old_end = parser->tabulation->ptr + parser->tabulation->len;
331 new_end = parser->tabulation->ptr + space_count;
332 while (old_end < new_end)
334 if (space_count > parser->tabulation->len)
335 parser->tabulation->len = space_count;
336 str_append(parser->output, parser->tabulation->ptr, space_count);
338 parser->current_indent += 2;
341 void wiki_append_pre_start(parser_t *parser, token_t *token)
344 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
345 ary_push(parser->scope, PRE_START);
346 ary_push(parser->line, PRE_START);
349 void wiki_dedent(parser_t *parser, bool emit)
351 if (parser->base_indent == -1) // indentation disabled
353 parser->current_indent -= 2;
356 int space_count = parser->current_indent + parser->base_indent;
358 str_append(parser->output, parser->tabulation->ptr, space_count);
361 // Pops a single item off the parser's scope stack.
362 // A corresponding closing tag is written to the target string.
363 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
364 void wiki_pop_from_stack(parser_t *parser, str_t *target)
366 int top = ary_entry(parser->scope, -1);
370 target = parser->output;
372 // for headings, take base_heading_level into account
373 if (top >= H1_START && top <= H6_START)
375 top += parser->base_heading_level;
376 // no need to check for underflow (base_heading_level is never negative)
385 str_append(target, pre_end, sizeof(pre_end) - 1);
386 str_append_str(target, parser->line_ending);
387 wiki_dedent(parser, false);
391 case BLOCKQUOTE_START:
392 wiki_dedent(parser, true);
393 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
394 str_append_str(target, parser->line_ending);
398 // not a real HTML tag; so nothing to pop
403 str_append(target, strong_end, sizeof(strong_end) - 1);
408 str_append(target, em_end, sizeof(em_end) - 1);
413 str_append(target, tt_end, sizeof(tt_end) - 1);
417 wiki_dedent(parser, true);
418 str_append(target, ol_end, sizeof(ol_end) - 1);
419 str_append_str(target, parser->line_ending);
423 wiki_dedent(parser, true);
424 str_append(target, ul_end, sizeof(ul_end) - 1);
425 str_append_str(target, parser->line_ending);
429 // next token to pop will be a LI
430 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
431 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
432 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
433 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
434 wiki_dedent(parser, true); // we really only want to emit the spaces
435 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
439 str_append(target, li_end, sizeof(li_end) - 1);
440 str_append_str(target, parser->line_ending);
441 wiki_dedent(parser, false);
445 str_append(target, h6_end, sizeof(h6_end) - 1);
446 str_append_str(target, parser->line_ending);
447 wiki_dedent(parser, false);
451 str_append(target, h5_end, sizeof(h5_end) - 1);
452 str_append_str(target, parser->line_ending);
453 wiki_dedent(parser, false);
457 str_append(target, h4_end, sizeof(h4_end) - 1);
458 str_append_str(target, parser->line_ending);
459 wiki_dedent(parser, false);
463 str_append(target, h3_end, sizeof(h3_end) - 1);
464 str_append_str(target, parser->line_ending);
465 wiki_dedent(parser, false);
469 str_append(target, h2_end, sizeof(h2_end) - 1);
470 str_append_str(target, parser->line_ending);
471 wiki_dedent(parser, false);
475 str_append(target, h1_end, sizeof(h1_end) - 1);
476 str_append_str(target, parser->line_ending);
477 wiki_dedent(parser, false);
481 // not an HTML tag; so nothing to emit
485 // not an HTML tag; so nothing to emit
489 // not an HTML tag; so nothing to emit
493 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
497 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
501 str_append(target, p_end, sizeof(p_end) - 1);
502 str_append_str(target, parser->line_ending);
503 wiki_dedent(parser, false);
511 // should probably raise an exception here
514 ary_pop(parser->scope);
517 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
518 // If including is true then the item itself is also popped.
519 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
520 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
522 int continue_looping = 1;
525 int top = ary_entry(parser->scope, -1);
532 continue_looping = 0;
534 wiki_pop_from_stack(parser, target);
535 } while (continue_looping);
538 void wiki_pop_all_from_stack(parser_t *parser)
540 for (int i = 0, max = parser->scope->count; i < max; i++)
541 wiki_pop_from_stack(parser, NULL);
544 void wiki_start_para_if_necessary(parser_t *parser)
549 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
550 if (parser->scope->count == 0 ||
551 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
552 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
555 str_append(parser->output, p_start, sizeof(p_start) - 1);
556 ary_push(parser->scope, P);
557 ary_push(parser->line, P);
559 else if (parser->pending_crlf)
562 // already in a paragraph block; convert pending CRLF into a space
563 str_append(parser->output, space, sizeof(space) - 1);
565 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
566 str_append_str(parser->output, parser->line_ending);
568 parser->pending_crlf = false;
571 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
573 if (parser->pending_crlf)
575 str_append_str(parser->output, parser->line_ending);
576 parser->pending_crlf = false;
580 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
581 // For example, given input like:
586 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
587 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
592 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
593 // but not on the line scope:
598 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
599 // on the line scope.
600 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
601 // entering the for loop.
602 void wiki_pop_excess_elements(parser_t *parser)
606 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
608 // special case for last item on scope
611 // don't auto-pop P if it is only item on scope
612 if (ary_entry(parser->scope, -1) == P)
614 // add P to the line scope to prevent us entering the loop at all next time around
615 ary_push(parser->line, P);
619 wiki_pop_from_stack(parser, NULL);
623 // Convert a single UTF-8 codepoint to UTF-32
625 // Expects an input buffer, src, containing a UTF-8 encoded character (which
626 // may be multi-byte). The end of the input buffer, end, is also passed in to
627 // allow the detection of invalidly truncated codepoints. The number of bytes
628 // in the UTF-8 character (between 1 and 4) is returned by reference in
631 // Raises a RangeError if the supplied character is invalid UTF-8.
632 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
635 if ((unsigned char)src[0] <= 0x7f)
641 else if ((src[0] & 0xe0) == 0xc0)
643 // byte starts with 110..... : this should be a two-byte sequence
646 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
647 else if (((unsigned char)src[0] == 0xc0) ||
648 ((unsigned char)src[0] == 0xc1))
649 // overlong encoding: lead byte of 110..... but code point <= 127
650 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
651 else if ((src[1] & 0xc0) != 0x80 )
652 // should have second byte starting with 10......
653 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
656 ((uint32_t)(src[0] & 0x1f)) << 6 |
660 else if ((src[0] & 0xf0) == 0xe0)
662 // byte starts with 1110.... : this should be a three-byte sequence
664 // missing second or third byte
665 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
666 else if (((src[1] & 0xc0) != 0x80 ) ||
667 ((src[2] & 0xc0) != 0x80 ))
668 // should have second and third bytes starting with 10......
669 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
672 ((uint32_t)(src[0] & 0x0f)) << 12 |
673 ((uint32_t)(src[1] & 0x3f)) << 6 |
677 else if ((src[0] & 0xf8) == 0xf0)
679 // bytes starts with 11110... : this should be a four-byte sequence
681 // missing second, third, or fourth byte
682 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
683 else if ((unsigned char)src[0] >= 0xf5 &&
684 (unsigned char)src[0] <= 0xf7)
685 // disallowed by RFC 3629 (codepoints above 0x10ffff)
686 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
687 else if (((src[1] & 0xc0) != 0x80 ) ||
688 ((src[2] & 0xc0) != 0x80 ) ||
689 ((src[3] & 0xc0) != 0x80 ))
690 // should have second and third bytes starting with 10......
691 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
694 ((uint32_t)(src[0] & 0x07)) << 18 |
695 ((uint32_t)(src[1] & 0x3f)) << 12 |
696 ((uint32_t)(src[1] & 0x3f)) << 6 |
701 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
705 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
707 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
708 char scratch = (character & 0xf000) >> 12;
709 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
710 scratch = (character & 0x0f00) >> 8;
711 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
712 scratch = (character & 0x00f0) >> 4;
713 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
714 scratch = character & 0x000f;
715 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
716 str_append(output, hex_string, sizeof(hex_string));
719 // trim parser->link_text in place
720 void wiki_trim_link_text(parser_t *parser)
722 char *src = parser->link_text->ptr;
723 char *start = src; // remember this so we can check if we're at the start
725 char *non_space = src; // remember last non-space character output
726 char *end = src + parser->link_text->len;
738 if (left != start || non_space + 1 != end)
740 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
741 parser->link_text->len = (non_space + 1) - left;
742 memmove(parser->link_text->ptr, left, parser->link_text->len);
746 // - non-printable (non-ASCII) characters converted to numeric entities
747 // - QUOT and AMP characters converted to named entities
748 // - if trim is true, leading and trailing whitespace trimmed
749 // - if trim is false, there is no special treatment of spaces
750 void wiki_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
752 char *src = parser->link_target->ptr;
753 char *start = src; // remember this so we can check if we're at the start
754 char *non_space = output->ptr + output->len; // remember last non-space character output
755 char *end = src + parser->link_target->len;
758 // need at most 8 bytes to display each input character (�)
759 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
761 char *old_ptr = output->ptr;
762 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
763 if (old_ptr != output->ptr) // may have moved
764 non_space += output->ptr - old_ptr;
769 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
770 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
772 else if (*src == '&')
774 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
775 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
777 else if (*src == '<' || *src == '>')
778 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
779 else if (*src == ' ' && src == start && trim)
780 start++; // we eat leading space
781 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
783 *(output->ptr + output->len) = *src;
786 else // all others: must convert to entities
789 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
791 non_space = output->ptr + output->len;
795 non_space = output->ptr + output->len;
799 // trim trailing space if necessary
800 if (trim && output->ptr + output->len != non_space)
801 output->len -= (output->ptr + output->len) - non_space;
804 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
807 parser.link_target = str_new_from_string(string);
808 GC_WRAP_STR(parser.link_target, link_target_gc);
809 str_t *output = str_new();
810 GC_WRAP_STR(output, output_gc);
811 wiki_append_sanitized_link_target(&parser, output, true);
812 return string_from_str(output);
815 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
817 // Leading and trailing whitespace trimmed. Spaces are converted to
818 // underscores if the parser space_to_underscore member is true.
819 static void wiki_encode_link_target(parser_t *parser)
821 char *src = parser->link_target->ptr;
822 char *start = src; // remember this so we can check if we're at the start
823 long len = parser->link_target->len;
826 char *end = src + len;
827 long dest_len = len * 2;
828 char *dest = ALLOC_N(char, dest_len);
829 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
830 char *non_space = dest; // remember last non-space character output
831 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
832 for (; src < end; src++)
834 // worst case: a single character may grow to 3 characters once encoded
835 if ((dest + 3) > (dest_ptr + dest_len))
837 // outgrowing buffer, must reallocate
838 char *old_dest = dest;
839 char *old_dest_ptr = dest_ptr;
841 dest = realloc(dest_ptr, dest_len);
844 // would have used reallocf, but this has to run on Linux too, not just Darwin
846 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
849 dest = dest_ptr + (old_dest - old_dest_ptr);
850 non_space = dest_ptr + (non_space - old_dest_ptr);
853 // pass through unreserved characters
854 if ((*src >= 'a' && *src <= 'z') ||
855 (*src >= 'A' && *src <= 'Z') ||
856 (*src >= '0' && *src <= '9') ||
865 else if (*src == ' ' && src == start)
866 start++; // we eat leading space
867 else if (*src == ' ' && parser->space_to_underscore)
869 else // everything else gets URL-encoded
872 *dest++ = hex[(unsigned char)(*src) / 16]; // left
873 *dest++ = hex[(unsigned char)(*src) % 16]; // right
879 // trim trailing space if necessary
880 if (non_space > dest_ptr && dest != non_space)
881 dest_len = non_space - dest_ptr;
883 dest_len = dest - dest_ptr;
884 str_clear(parser->link_target);
885 str_append(parser->link_target, dest_ptr, dest_len);
889 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
892 parser.space_to_underscore = false;
893 parser.link_target = str_new_from_string(in);
894 GC_WRAP_STR(parser.link_target, link_target_gc);
895 wiki_encode_link_target(&parser);
896 return string_from_str(parser.link_target);
899 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
900 // returns 0 (false) otherwise
901 bool wiki_blank(str_t *str)
905 for (char *ptr = str->ptr,
906 *end = str->ptr + str->len;
915 void wiki_rollback_failed_internal_link(parser_t *parser)
918 return; // nothing to do!
919 int scope_includes_separator = IN(SEPARATOR);
920 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
921 str_append(parser->output, link_start, sizeof(link_start) - 1);
922 if (parser->link_target->len > 0)
924 wiki_append_sanitized_link_target(parser, parser->output, false);
925 if (scope_includes_separator)
927 str_append(parser->output, separator, sizeof(separator) - 1);
928 if (parser->link_text->len > 0)
929 str_append_str(parser->output, parser->link_text);
932 parser->capture = NULL;
933 str_clear(parser->link_target);
934 str_clear(parser->link_text);
937 void wiki_rollback_failed_external_link(parser_t *parser)
939 if (!IN(EXT_LINK_START))
940 return; // nothing to do!
942 // store a couple of values before popping
943 int scope_includes_space = IN(SPACE);
944 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
945 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
947 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
948 if (parser->link_target->len > 0)
950 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
951 if (scope_includes_space)
953 str_append(parser->output, space, sizeof(space) - 1);
954 if (parser->link_text->len > 0)
955 str_append_str(parser->output, parser->link_text);
958 parser->capture = NULL;
959 str_clear(parser->link_target);
960 str_clear(parser->link_text);
963 void wiki_rollback_failed_link(parser_t *parser)
965 wiki_rollback_failed_internal_link(parser);
966 wiki_rollback_failed_external_link(parser);
969 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
973 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
977 VALUE autolink = Qtrue;
978 VALUE line_ending = rb_str_new2("\n");
979 VALUE external_link_class = rb_str_new2("external");
980 VALUE mailto_class = rb_str_new2("mailto");
981 VALUE internal_link_prefix = rb_str_new2("/wiki/");
982 VALUE img_prefix = rb_str_new2("/images/");
983 VALUE space_to_underscore = Qtrue;
984 VALUE minimum_fulltext_token_length = INT2NUM(3);
985 VALUE base_heading_level = INT2NUM(0);
987 // process options hash (override defaults)
988 if (!NIL_P(options) && TYPE(options) == T_HASH)
990 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
991 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
992 autolink = OVERRIDE_IF_SET(autolink);
993 line_ending = OVERRIDE_IF_SET(line_ending);
994 external_link_class = OVERRIDE_IF_SET(external_link_class);
995 mailto_class = OVERRIDE_IF_SET(mailto_class);
996 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
997 img_prefix = OVERRIDE_IF_SET(img_prefix);
998 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
999 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1000 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1003 // no need to call super here; rb_call_super()
1004 rb_iv_set(self, "@autolink", autolink);
1005 rb_iv_set(self, "@line_ending", line_ending);
1006 rb_iv_set(self, "@external_link_class", external_link_class);
1007 rb_iv_set(self, "@mailto_class", mailto_class);
1008 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1009 rb_iv_set(self, "@img_prefix", img_prefix);
1010 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1011 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1012 rb_iv_set(self, "@base_heading_level", base_heading_level);
1016 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1018 for (int i = 0; i < 100000; i++)
1019 Wikitext_parser_parse(1, &string, self);
1023 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1025 // process arguments
1026 VALUE string, options;
1027 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1031 string = StringValue(string);
1033 // process options hash
1034 int base_indent = 0;
1035 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1036 if (!NIL_P(options) && TYPE(options) == T_HASH)
1038 // :indent => 0 (or more)
1039 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("indent"))) == Qtrue)
1041 VALUE indent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
1042 if (indent == Qfalse)
1043 base_indent = -1; // indentation disabled
1046 base_indent = NUM2INT(indent);
1047 if (base_indent < 0)
1052 // :base_heading_level => 0/1/2/3/4/5/6
1053 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("base_heading_level"))) == Qtrue)
1054 base_heading_level = NUM2INT(rb_hash_aref(options, ID2SYM(rb_intern("base_heading_level"))));
1057 // normalize, regardless of whether this came from instance variable or override
1058 if (base_heading_level < 0)
1059 base_heading_level = 0;
1060 if (base_heading_level > 6)
1061 base_heading_level = 6;
1064 char *p = RSTRING_PTR(string);
1065 long len = RSTRING_LEN(string);
1068 // access these once per parse
1069 VALUE line_ending = rb_iv_get(self, "@line_ending");
1070 line_ending = StringValue(line_ending);
1071 VALUE link_class = rb_iv_get(self, "@external_link_class");
1072 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1073 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1074 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1075 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1077 // set up parser struct to make passing parameters a little easier
1078 parser_t *parser = parser_new();
1079 GC_WRAP_PARSER(parser, parser_gc);
1080 parser->external_link_class = link_class;
1081 parser->mailto_class = mailto_class;
1082 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1083 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1084 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1085 parser->line_ending = str_new_from_string(line_ending);
1086 parser->base_indent = base_indent;
1087 parser->base_heading_level = base_heading_level;
1089 // this simple looping design leads to a single enormous function,
1090 // but it's faster than doing actual recursive descent and also secure in the face of
1091 // malicious input that seeks to overflow the stack
1092 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1093 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1094 // than a straightforward looping translator like this one anyway
1096 _token.type = NO_TOKEN;
1097 token_t *token = NULL;
1100 // note that whenever we grab a token we push it into the line buffer
1101 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1102 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1104 // check to see if we have a token hanging around from a previous iteration of this loop
1107 if (_token.type == NO_TOKEN)
1109 // first time here (haven't started scanning yet)
1111 next_token(token, NULL, p, pe);
1112 ary_push(parser->line_buffer, token->type);
1118 int type = token->type;
1120 // can't declare new variables inside a switch statement, so predeclare them here
1121 long remove_strong = -1;
1122 long remove_em = -1;
1124 // general purpose counters, flags and pointers
1128 str_t *output = NULL;
1130 str_t *token_str = &_token_str;
1132 // The following giant switch statement contains cases for all the possible token types.
1133 // In the most basic sense we are emitting the HTML that corresponds to each token,
1134 // but some tokens require context information in order to decide what to output.
1135 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1136 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1138 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1139 // - the line buffer (records tokens seen so far on the current line)
1140 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1142 // Although this is fairly complicated, there is one key simplifying factor:
1143 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1144 // scope stack (up to the current token) is valid; our translator can take this as a given.
1145 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1146 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1150 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1152 str_append(parser->output, space, sizeof(space) - 1);
1155 else if (IN(BLOCKQUOTE_START))
1157 // this kind of nesting not allowed (to avoid user confusion)
1158 wiki_pop_excess_elements(parser);
1159 wiki_start_para_if_necessary(parser);
1160 output = parser->capture ? parser->capture : parser->output;
1161 str_append(output, space, sizeof(space) - 1);
1165 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1166 ary_push(parser->line, PRE);
1167 i = ary_count(parser->line, BLOCKQUOTE);
1168 j = ary_count(parser->scope, BLOCKQUOTE);
1171 // must pop (reduce nesting level)
1172 for (i = j - i; i > 0; i--)
1173 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1178 parser->pending_crlf = false;
1179 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1180 wiki_indent(parser);
1181 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1182 ary_push(parser->scope, PRE);
1187 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1189 wiki_emit_pending_crlf_if_necessary(parser);
1190 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1192 else if (IN(BLOCKQUOTE_START))
1194 wiki_rollback_failed_link(parser); // if any
1195 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1196 wiki_append_pre_start(parser, token);
1198 else if (IN(BLOCKQUOTE))
1200 if (token->column_start == 1) // only allowed in first column
1202 wiki_rollback_failed_link(parser); // if any
1203 wiki_pop_all_from_stack(parser);
1204 wiki_append_pre_start(parser, token);
1206 else // PRE_START illegal here
1208 output = parser->capture ? parser->capture : parser->output;
1209 wiki_pop_excess_elements(parser);
1210 wiki_start_para_if_necessary(parser);
1211 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1216 wiki_rollback_failed_link(parser); // if any
1217 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1218 wiki_append_pre_start(parser, token);
1223 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1225 wiki_emit_pending_crlf_if_necessary(parser);
1226 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1231 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1234 output = parser->capture ? parser->capture : parser->output;
1235 wiki_pop_excess_elements(parser);
1236 wiki_start_para_if_necessary(parser);
1237 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1243 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1244 // no need to check for <pre>; can never appear inside it
1245 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1246 else if (IN(BLOCKQUOTE_START))
1248 // this kind of nesting not allowed (to avoid user confusion)
1249 wiki_pop_excess_elements(parser);
1250 wiki_start_para_if_necessary(parser);
1251 output = parser->capture ? parser->capture : parser->output;
1252 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1257 ary_push(parser->line, BLOCKQUOTE);
1259 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1260 i = ary_count(parser->line, BLOCKQUOTE);
1261 j = ary_count(parser->scope, BLOCKQUOTE);
1263 // 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
1264 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1266 ary_push(parser->line, BLOCKQUOTE);
1270 // now decide whether to push, pop or do nothing
1273 // must push (increase nesting level)
1274 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1275 for (i = i - j; i > 0; i--)
1277 wiki_indent(parser);
1278 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1279 str_append_str(parser->output, parser->line_ending);
1280 ary_push(parser->scope, BLOCKQUOTE);
1285 // must pop (reduce nesting level)
1286 for (i = j - i; i > 0; i--)
1287 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1290 // jump to top of the loop to process token we scanned during lookahead
1295 case BLOCKQUOTE_START:
1296 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1298 wiki_emit_pending_crlf_if_necessary(parser);
1299 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1301 else if (IN(BLOCKQUOTE_START))
1303 // nesting is fine here
1304 wiki_rollback_failed_link(parser); // if any
1305 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1306 wiki_indent(parser);
1307 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1308 str_append_str(parser->output, parser->line_ending);
1309 ary_push(parser->scope, BLOCKQUOTE_START);
1310 ary_push(parser->line, BLOCKQUOTE_START);
1312 else if (IN(BLOCKQUOTE))
1314 if (token->column_start == 1) // only allowed in first column
1316 wiki_rollback_failed_link(parser); // if any
1317 wiki_pop_all_from_stack(parser);
1318 wiki_indent(parser);
1319 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1320 str_append_str(parser->output, parser->line_ending);
1321 ary_push(parser->scope, BLOCKQUOTE_START);
1322 ary_push(parser->line, BLOCKQUOTE_START);
1324 else // BLOCKQUOTE_START illegal here
1326 output = parser->capture ? parser->capture : parser->output;
1327 wiki_pop_excess_elements(parser);
1328 wiki_start_para_if_necessary(parser);
1329 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1334 // would be nice to eliminate the repetition here but it's probably the clearest way
1335 wiki_rollback_failed_link(parser); // if any
1336 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1337 wiki_indent(parser);
1338 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1339 str_append_str(parser->output, parser->line_ending);
1340 ary_push(parser->scope, BLOCKQUOTE_START);
1341 ary_push(parser->line, BLOCKQUOTE_START);
1345 case BLOCKQUOTE_END:
1346 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1348 wiki_emit_pending_crlf_if_necessary(parser);
1349 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1353 if (IN(BLOCKQUOTE_START))
1354 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1357 output = parser->capture ? parser->capture : parser->output;
1358 wiki_pop_excess_elements(parser);
1359 wiki_start_para_if_necessary(parser);
1360 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1366 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1368 wiki_emit_pending_crlf_if_necessary(parser);
1369 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1373 wiki_pop_excess_elements(parser);
1374 wiki_start_para_if_necessary(parser);
1375 ary_push(parser->scope, NO_WIKI_START);
1376 ary_push(parser->line, NO_WIKI_START);
1381 if (IN(NO_WIKI_START))
1382 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1383 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1386 wiki_pop_excess_elements(parser);
1387 wiki_start_para_if_necessary(parser);
1388 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1393 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1395 wiki_emit_pending_crlf_if_necessary(parser);
1396 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1400 output = parser->capture ? parser->capture : parser->output;
1401 wiki_pop_excess_elements(parser);
1403 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1404 // otherwise, must open them
1407 j = parser->scope->count;
1408 for (j = j - 1; j >= 0; j--)
1410 int val = ary_entry(parser->scope, j);
1411 if (val == STRONG || val == STRONG_START)
1413 str_append(output, strong_end, sizeof(strong_end) - 1);
1416 else if (val == EM || val == EM_START)
1418 str_append(output, em_end, sizeof(em_end) - 1);
1423 if (remove_strong > remove_em) // must remove strong first
1425 ary_pop(parser->scope);
1427 ary_pop(parser->scope);
1428 else // there was no em to remove!, so consider this an opening em tag
1430 str_append(output, em_start, sizeof(em_start) - 1);
1431 ary_push(parser->scope, EM);
1432 ary_push(parser->line, EM);
1435 else if (remove_em > remove_strong) // must remove em first
1437 ary_pop(parser->scope);
1438 if (remove_strong > -1)
1439 ary_pop(parser->scope);
1440 else // there was no strong to remove!, so consider this an opening strong tag
1442 str_append(output, strong_start, sizeof(strong_start) - 1);
1443 ary_push(parser->scope, STRONG);
1444 ary_push(parser->line, STRONG);
1447 else // no strong or em to remove, so this must be a new opening of both
1449 wiki_start_para_if_necessary(parser);
1450 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1451 ary_push(parser->scope, STRONG);
1452 ary_push(parser->line, STRONG);
1453 ary_push(parser->scope, EM);
1454 ary_push(parser->line, EM);
1459 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1461 wiki_emit_pending_crlf_if_necessary(parser);
1462 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1466 output = parser->capture ? parser->capture : parser->output;
1467 if (IN(STRONG_START))
1468 // already in span started with <strong>, no choice but to emit this literally
1469 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1470 else if (IN(STRONG))
1471 // STRONG already seen, this is a closing tag
1472 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1475 // this is a new opening
1476 wiki_pop_excess_elements(parser);
1477 wiki_start_para_if_necessary(parser);
1478 str_append(output, strong_start, sizeof(strong_start) - 1);
1479 ary_push(parser->scope, STRONG);
1480 ary_push(parser->line, STRONG);
1486 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1488 wiki_emit_pending_crlf_if_necessary(parser);
1489 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1493 output = parser->capture ? parser->capture : parser->output;
1494 if (IN_EITHER_OF(STRONG_START, STRONG))
1495 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1498 wiki_pop_excess_elements(parser);
1499 wiki_start_para_if_necessary(parser);
1500 str_append(output, strong_start, sizeof(strong_start) - 1);
1501 ary_push(parser->scope, STRONG_START);
1502 ary_push(parser->line, STRONG_START);
1508 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1510 wiki_emit_pending_crlf_if_necessary(parser);
1511 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1515 output = parser->capture ? parser->capture : parser->output;
1516 if (IN(STRONG_START))
1517 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1520 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1521 wiki_pop_excess_elements(parser);
1522 wiki_start_para_if_necessary(parser);
1523 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1529 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1531 wiki_emit_pending_crlf_if_necessary(parser);
1532 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1536 output = parser->capture ? parser->capture : parser->output;
1538 // already in span started with <em>, no choice but to emit this literally
1539 str_append(output, literal_em, sizeof(literal_em) - 1);
1541 // EM already seen, this is a closing tag
1542 wiki_pop_from_stack_up_to(parser, output, EM, true);
1545 // this is a new opening
1546 wiki_pop_excess_elements(parser);
1547 wiki_start_para_if_necessary(parser);
1548 str_append(output, em_start, sizeof(em_start) - 1);
1549 ary_push(parser->scope, EM);
1550 ary_push(parser->line, EM);
1556 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1558 wiki_emit_pending_crlf_if_necessary(parser);
1559 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1563 output = parser->capture ? parser->capture : parser->output;
1564 if (IN_EITHER_OF(EM_START, EM))
1565 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1568 wiki_pop_excess_elements(parser);
1569 wiki_start_para_if_necessary(parser);
1570 str_append(output, em_start, sizeof(em_start) - 1);
1571 ary_push(parser->scope, EM_START);
1572 ary_push(parser->line, EM_START);
1578 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1580 wiki_emit_pending_crlf_if_necessary(parser);
1581 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1585 output = parser->capture ? parser->capture : parser->output;
1587 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1590 // no EM_START in scope, so must interpret the TT_END without any special meaning
1591 wiki_pop_excess_elements(parser);
1592 wiki_start_para_if_necessary(parser);
1593 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1599 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1601 wiki_emit_pending_crlf_if_necessary(parser);
1602 str_append(parser->output, backtick, sizeof(backtick) - 1);
1606 output = parser->capture ? parser->capture : parser->output;
1608 // already in span started with <tt>, no choice but to emit this literally
1609 str_append(output, backtick, sizeof(backtick) - 1);
1611 // TT (`) already seen, this is a closing tag
1612 wiki_pop_from_stack_up_to(parser, output, TT, true);
1615 // this is a new opening
1616 wiki_pop_excess_elements(parser);
1617 wiki_start_para_if_necessary(parser);
1618 str_append(output, tt_start, sizeof(tt_start) - 1);
1619 ary_push(parser->scope, TT);
1620 ary_push(parser->line, TT);
1626 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1628 wiki_emit_pending_crlf_if_necessary(parser);
1629 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1633 output = parser->capture ? parser->capture : parser->output;
1634 if (IN_EITHER_OF(TT_START, TT))
1635 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1638 wiki_pop_excess_elements(parser);
1639 wiki_start_para_if_necessary(parser);
1640 str_append(output, tt_start, sizeof(tt_start) - 1);
1641 ary_push(parser->scope, TT_START);
1642 ary_push(parser->line, TT_START);
1648 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1650 wiki_emit_pending_crlf_if_necessary(parser);
1651 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1655 output = parser->capture ? parser->capture : parser->output;
1657 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1660 // no TT_START in scope, so must interpret the TT_END without any special meaning
1661 wiki_pop_excess_elements(parser);
1662 wiki_start_para_if_necessary(parser);
1663 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1670 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1672 // no need to check for PRE; can never appear inside it
1673 str_append(parser->output, token->start, TOKEN_LEN(token));
1677 // count number of tokens in line and scope stacks
1678 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1679 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1680 j = parser->scope->count - bq_count;
1683 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1687 if (type == OL || type == UL)
1690 if (i - k >= 2) // already seen at least one OL or UL
1692 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1697 ary_push(parser->line, type);
1698 ary_push(parser->line, LI);
1700 // want to compare line with scope but can only do so if scope has enough items on it
1703 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1704 ary_entry(parser->scope, i + bq_count - 1) == LI)
1706 // line and scope match at this point: do nothing yet
1710 // item just pushed onto line does not match corresponding slot of scope!
1711 for (; j >= i - 2; j--)
1712 // must pop back before emitting
1713 wiki_pop_from_stack(parser, NULL);
1715 // will emit UL or OL, then LI
1719 else // line stack size now exceeds scope stack size: must increase nesting level
1720 break; // will emit UL or OL, then LI
1724 // not a OL or UL token!
1726 // must close existing LI and re-open new one
1727 wiki_pop_from_stack(parser, NULL);
1730 // item just pushed onto line does not match corresponding slot of scope!
1732 // must pop back before emitting
1733 wiki_pop_from_stack(parser, NULL);
1741 if (type == OL || type == UL)
1743 // if LI is at the top of a stack this is the start of a nested list
1744 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1746 // so we should precede it with a CRLF, and indicate that it's a nested list
1747 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1748 ary_push(parser->scope, NESTED_LIST);
1752 // this is a new list
1753 if (IN(BLOCKQUOTE_START))
1754 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1756 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1760 wiki_indent(parser);
1762 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1763 else if (type == UL)
1764 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1765 ary_push(parser->scope, type);
1766 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1768 else if (type == SPACE)
1769 // silently throw away the optional SPACE token after final list marker
1772 wiki_indent(parser);
1773 str_append(parser->output, li_start, sizeof(li_start) - 1);
1774 ary_push(parser->scope, LI);
1776 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1777 if (type == OL || type == UL)
1780 while (k++, NEXT_TOKEN(), (type = token->type))
1782 if (type == OL || type == UL)
1783 str_append(parser->output, token->start, TOKEN_LEN(token));
1784 else if (type == SPACE && k == 1)
1786 // silently throw away the optional SPACE token after final list marker
1795 // jump to top of the loop to process token we scanned during lookahead
1804 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1806 // no need to check for PRE; can never appear inside it
1807 str_append(parser->output, token->start, TOKEN_LEN(token));
1811 // pop up to but not including the last BLOCKQUOTE on the scope stack
1812 if (IN(BLOCKQUOTE_START))
1813 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1815 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1817 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1818 ary_push(parser->line, type);
1819 i = ary_count(parser->line, BLOCKQUOTE);
1820 j = ary_count(parser->scope, BLOCKQUOTE);
1822 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1825 // must pop (reduce nesting level)
1826 for (i = j - i; i > 0; i--)
1827 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1830 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1831 while (NEXT_TOKEN(), (token->type == SPACE))
1834 ary_push(parser->scope, type);
1835 wiki_indent(parser);
1837 // take base_heading_level into account
1838 type += base_heading_level;
1839 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1842 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1843 if (type == H6_START)
1844 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1845 else if (type == H5_START)
1846 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1847 else if (type == H4_START)
1848 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1849 else if (type == H3_START)
1850 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1851 else if (type == H2_START)
1852 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1853 else if (type == H1_START)
1854 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1856 // jump to top of the loop to process token we scanned during lookahead
1865 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1867 wiki_emit_pending_crlf_if_necessary(parser);
1868 str_append(parser->output, token->start, TOKEN_LEN(token));
1872 wiki_rollback_failed_external_link(parser); // if any
1873 if ((type == H6_END && !IN(H6_START)) ||
1874 (type == H5_END && !IN(H5_START)) ||
1875 (type == H4_END && !IN(H4_START)) ||
1876 (type == H3_END && !IN(H3_START)) ||
1877 (type == H2_END && !IN(H2_START)) ||
1878 (type == H1_END && !IN(H1_START)))
1880 // literal output only if not in appropriate scope (we stay silent in that case)
1881 wiki_start_para_if_necessary(parser);
1882 str_append(parser->output, token->start, TOKEN_LEN(token));
1888 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1890 wiki_emit_pending_crlf_if_necessary(parser);
1891 str_append(parser->output, token->start, TOKEN_LEN(token));
1895 wiki_pop_excess_elements(parser);
1896 wiki_start_para_if_necessary(parser);
1897 token_str->ptr = token->start;
1898 token_str->len = TOKEN_LEN(token);
1899 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
1904 if (IN(NO_WIKI_START))
1905 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1906 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1907 str_append(parser->output, token->start, TOKEN_LEN(token));
1908 else if (IN(LINK_START))
1910 // if the URI were allowed it would have been handled already in LINK_START
1911 wiki_rollback_failed_internal_link(parser);
1912 token_str->ptr = token->start;
1913 token_str->len = TOKEN_LEN(token);
1914 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1916 else if (IN(EXT_LINK_START))
1918 if (parser->link_target->len == 0)
1920 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1921 token_str->ptr = token->start;
1922 token_str->len = TOKEN_LEN(token);
1924 if (token->type == SPACE)
1926 ary_push(parser->scope, SPACE);
1927 str_append_str(parser->link_target, token_str);
1928 str_clear(parser->link_text);
1929 parser->capture = parser->link_text;
1930 token = NULL; // silently consume space
1934 // didn't see the space! this must be an error
1935 wiki_pop_from_stack(parser, NULL);
1936 wiki_pop_excess_elements(parser);
1937 wiki_start_para_if_necessary(parser);
1938 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1939 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1943 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1947 wiki_pop_excess_elements(parser);
1948 wiki_start_para_if_necessary(parser);
1949 token_str->ptr = token->start;
1950 token_str->len = TOKEN_LEN(token);
1951 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1956 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1957 str_append(parser->output, token->start, TOKEN_LEN(token));
1958 else if (IN(EXT_LINK_START))
1960 if (parser->link_target->len == 0)
1962 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1963 token_str->ptr = token->start;
1964 token_str->len = TOKEN_LEN(token);
1966 if (token->type == SPACE)
1968 ary_push(parser->scope, PATH);
1969 ary_push(parser->scope, SPACE);
1970 str_append_str(parser->link_target, token_str);
1971 str_clear(parser->link_text);
1972 parser->capture = parser->link_text;
1973 token = NULL; // silently consume space
1977 // didn't see the space! this must be an error
1978 wiki_pop_from_stack(parser, NULL);
1979 wiki_pop_excess_elements(parser);
1980 wiki_start_para_if_necessary(parser);
1981 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1982 str_append_str(parser->output, token_str);
1986 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1990 output = parser->capture ? parser->capture : parser->output;
1991 wiki_pop_excess_elements(parser);
1992 wiki_start_para_if_necessary(parser);
1993 str_append(output, token->start, TOKEN_LEN(token));
1997 // internal links (links to other wiki articles) look like this:
1998 // [[another article]] (would point at, for example, "/wiki/another_article")
1999 // [[the other article|the link text we'll use for it]]
2000 // [[the other article | the link text we'll use for it]]
2001 // MediaWiki has strict requirements about what it will accept as a link target:
2002 // all wikitext markup is disallowed:
2003 // example [[foo ''bar'' baz]]
2004 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2005 // example [[foo <em>bar</em> baz]]
2006 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2007 // example [[foo <nowiki>''</nowiki> baz]]
2008 // renders [[foo '' baz]] (ie. not a link)
2009 // example [[foo <bar> baz]]
2010 // renders [[foo <bar> baz]] (ie. not a link)
2011 // HTML entities and non-ASCII, however, make it through:
2012 // example [[foo €]]
2013 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2014 // example [[foo €]]
2015 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2016 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2017 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2018 // everything else will be rejected
2020 output = parser->capture ? parser->capture : parser->output;
2021 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2023 wiki_emit_pending_crlf_if_necessary(parser);
2024 str_append(output, link_start, sizeof(link_start) - 1);
2026 else if (IN(EXT_LINK_START))
2027 // already in external link scope! (and in fact, must be capturing link_text right now)
2028 str_append(output, link_start, sizeof(link_start) - 1);
2029 else if (IN(LINK_START))
2031 // already in internal link scope! this is a syntax error
2032 wiki_rollback_failed_internal_link(parser);
2033 str_append(parser->output, link_start, sizeof(link_start) - 1);
2035 else if (IN(SEPARATOR))
2037 // scanning internal link text
2039 else // not in internal link scope yet
2041 // will either emit a link, or the rollback of a failed link, so start the para now
2042 wiki_pop_excess_elements(parser);
2043 wiki_start_para_if_necessary(parser);
2044 ary_push(parser->scope, LINK_START);
2046 // look ahead and try to gobble up link target
2047 while (NEXT_TOKEN(), (type = token->type))
2049 if (type == SPACE ||
2050 type == SPECIAL_URI_CHARS ||
2052 type == PRINTABLE ||
2056 type == QUOT_ENTITY ||
2058 type == AMP_ENTITY ||
2059 type == IMG_START ||
2061 type == LEFT_CURLY ||
2062 type == RIGHT_CURLY)
2064 // accumulate these tokens into link_target
2065 if (parser->link_target->len == 0)
2067 str_clear(parser->link_target);
2068 parser->capture = parser->link_target;
2070 if (type == QUOT_ENTITY)
2071 // don't insert the entity, insert the literal quote
2072 str_append(parser->link_target, quote, sizeof(quote) - 1);
2073 else if (type == AMP_ENTITY)
2074 // don't insert the entity, insert the literal ampersand
2075 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2077 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2079 else if (type == LINK_END)
2081 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2082 wiki_rollback_failed_internal_link(parser);
2083 break; // jump back to top of loop (will handle this in LINK_END case below)
2085 else if (type == SEPARATOR)
2087 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2088 wiki_rollback_failed_internal_link(parser);
2091 ary_push(parser->scope, SEPARATOR);
2092 str_clear(parser->link_text);
2093 parser->capture = parser->link_text;
2098 else // unexpected token (syntax error)
2100 wiki_rollback_failed_internal_link(parser);
2101 break; // jump back to top of loop to handle unexpected token
2105 // jump to top of the loop to process token we scanned during lookahead (if any)
2111 output = parser->capture ? parser->capture : parser->output;
2112 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2114 wiki_emit_pending_crlf_if_necessary(parser);
2115 str_append(output, link_end, sizeof(link_end) - 1);
2117 else if (IN(EXT_LINK_START))
2118 // already in external link scope! (and in fact, must be capturing link_text right now)
2119 str_append(output, link_end, sizeof(link_end) - 1);
2120 else if (IN(LINK_START)) // in internal link scope!
2122 if (wiki_blank(parser->link_target))
2124 // special case for inputs like "[[ ]]"
2125 wiki_rollback_failed_internal_link(parser);
2126 str_append(parser->output, link_end, sizeof(link_end) - 1);
2129 if (parser->link_text->len == 0 ||
2130 wiki_blank(parser->link_text))
2132 // use link target as link text
2133 str_clear(parser->link_text);
2134 wiki_append_sanitized_link_target(parser, parser->link_text, true);
2137 wiki_trim_link_text(parser);
2138 wiki_encode_link_target(parser);
2139 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2140 parser->capture = NULL;
2141 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, Qnil, false);
2142 str_clear(parser->link_target);
2143 str_clear(parser->link_text);
2145 else // wasn't in internal link scope
2147 wiki_pop_excess_elements(parser);
2148 wiki_start_para_if_necessary(parser);
2149 str_append(output, link_end, sizeof(link_end) - 1);
2153 // external links look like this:
2154 // [http://google.com/ the link text]
2155 // [/other/page/on/site see this page]
2156 // strings in square brackets which don't match this syntax get passed through literally; eg:
2157 // he was very angery [sic] about the turn of events
2158 case EXT_LINK_START:
2159 output = parser->capture ? parser->capture : parser->output;
2160 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2162 wiki_emit_pending_crlf_if_necessary(parser);
2163 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2165 else if (IN(EXT_LINK_START))
2166 // already in external link scope! (and in fact, must be capturing link_text right now)
2167 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2168 else if (IN(LINK_START))
2170 // already in internal link scope!
2171 if (parser->link_target->len == 0 || !IN(SPACE))
2172 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2173 else // link target has already been scanned
2174 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2176 else // not in external link scope yet
2178 // will either emit a link, or the rollback of a failed link, so start the para now
2179 wiki_pop_excess_elements(parser);
2180 wiki_start_para_if_necessary(parser);
2182 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2184 if (token->type == URI || token->type == PATH)
2185 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2187 // only get here if there was a syntax error (missing URI)
2188 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2189 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2194 output = parser->capture ? parser->capture : parser->output;
2195 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2197 wiki_emit_pending_crlf_if_necessary(parser);
2198 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2200 else if (IN(EXT_LINK_START))
2202 if (parser->link_text->len == 0)
2203 // syntax error: external link with no link text
2204 wiki_rollback_failed_external_link(parser);
2208 j = IN(PATH) ? Qnil : parser->external_link_class;
2209 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2210 parser->capture = NULL;
2211 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2213 str_clear(parser->link_target);
2214 str_clear(parser->link_text);
2218 wiki_pop_excess_elements(parser);
2219 wiki_start_para_if_necessary(parser);
2220 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2225 output = parser->capture ? parser->capture : parser->output;
2226 wiki_pop_excess_elements(parser);
2227 wiki_start_para_if_necessary(parser);
2228 str_append(output, separator, sizeof(separator) - 1);
2232 output = parser->capture ? parser->capture : parser->output;
2233 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2235 wiki_emit_pending_crlf_if_necessary(parser);
2236 str_append(output, token->start, TOKEN_LEN(token));
2240 // peek ahead to see next token
2241 char *token_ptr = token->start;
2242 int token_len = TOKEN_LEN(token);
2245 if ((type == H6_END && IN(H6_START)) ||
2246 (type == H5_END && IN(H5_START)) ||
2247 (type == H4_END && IN(H4_START)) ||
2248 (type == H3_END && IN(H3_START)) ||
2249 (type == H2_END && IN(H2_START)) ||
2250 (type == H1_END && IN(H1_START)))
2252 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2257 wiki_pop_excess_elements(parser);
2258 wiki_start_para_if_necessary(parser);
2259 str_append(output, token_ptr, token_len);
2262 // jump to top of the loop to process token we scanned during lookahead
2270 case DECIMAL_ENTITY:
2271 // pass these through unaltered as they are case sensitive
2272 output = parser->capture ? parser->capture : parser->output;
2273 wiki_pop_excess_elements(parser);
2274 wiki_start_para_if_necessary(parser);
2275 str_append(output, token->start, TOKEN_LEN(token));
2279 // normalize hex entities (downcase them)
2280 output = parser->capture ? parser->capture : parser->output;
2281 wiki_pop_excess_elements(parser);
2282 wiki_start_para_if_necessary(parser);
2283 str_append(output, token->start, TOKEN_LEN(token));
2284 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2288 output = parser->capture ? parser->capture : parser->output;
2289 wiki_pop_excess_elements(parser);
2290 wiki_start_para_if_necessary(parser);
2291 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2295 output = parser->capture ? parser->capture : parser->output;
2296 wiki_pop_excess_elements(parser);
2297 wiki_start_para_if_necessary(parser);
2298 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2302 output = parser->capture ? parser->capture : parser->output;
2303 wiki_pop_excess_elements(parser);
2304 wiki_start_para_if_necessary(parser);
2305 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2309 output = parser->capture ? parser->capture : parser->output;
2310 wiki_pop_excess_elements(parser);
2311 wiki_start_para_if_necessary(parser);
2312 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2316 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2318 wiki_emit_pending_crlf_if_necessary(parser);
2319 str_append(parser->output, token->start, TOKEN_LEN(token));
2321 else if (parser->capture)
2322 str_append(parser->capture, token->start, TOKEN_LEN(token));
2325 // not currently capturing: will be emitting something on success or failure, so get ready
2326 wiki_pop_excess_elements(parser);
2327 wiki_start_para_if_necessary(parser);
2329 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2330 // will cheat here and abuse the link_target capture buffer to accumulate text
2331 while (NEXT_TOKEN(), (type = token->type))
2333 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2334 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2335 else if (type == IMG_END && parser->link_target->len > 0)
2338 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2342 else // unexpected token or zero-length target (syntax error)
2345 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2346 if (parser->link_target->len > 0)
2347 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2352 // jump to top of the loop to process token we scanned during lookahead
2353 str_clear(parser->link_target);
2359 i = parser->pending_crlf;
2360 parser->pending_crlf = false;
2361 wiki_rollback_failed_link(parser); // if any
2362 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2364 ary_clear(parser->line_buffer);
2365 str_append_str(parser->output, parser->line_ending);
2370 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2371 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2372 // don't emit in this case
2373 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2376 if (ary_entry(parser->line_buffer, -2) == PRE)
2378 // only thing on line is the PRE: emit pending line ending (if we had one)
2380 str_append_str(parser->output, parser->line_ending);
2383 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2384 ary_clear(parser->line);
2385 ary_clear(parser->line_buffer);
2387 // peek ahead to see if this is definitely the end of the PRE block
2390 if (type != BLOCKQUOTE && type != PRE)
2391 // this is definitely the end of the block, so don't emit
2392 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2394 // potentially will emit
2395 parser->pending_crlf = true;
2397 continue; // jump back to top of loop to handle token grabbed via lookahead
2402 parser->pending_crlf = true;
2404 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2405 // as a side effect, this handles any open span-level elements and unclosed blocks
2406 // (with special handling for P blocks and LI elements)
2407 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2408 for (j = parser->scope->count; j > i; j--)
2410 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2412 parser->pending_crlf = false;
2416 // special handling on last iteration through the loop if the top item on the scope is a P block
2417 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2419 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2420 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2421 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2422 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2423 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2425 parser->pending_crlf = false;
2427 // not a paragraph break!
2430 wiki_pop_from_stack(parser, NULL);
2434 // delete the entire contents of the line scope stack and buffer
2435 ary_clear(parser->line);
2436 ary_clear(parser->line_buffer);
2439 case SPECIAL_URI_CHARS:
2445 output = parser->capture ? parser->capture : parser->output;
2446 wiki_pop_excess_elements(parser);
2447 wiki_start_para_if_necessary(parser);
2448 str_append(output, token->start, TOKEN_LEN(token));
2452 output = parser->capture ? parser->capture : parser->output;
2453 wiki_pop_excess_elements(parser);
2454 wiki_start_para_if_necessary(parser);
2455 wiki_append_entity_from_utf32_char(output, token->code_point);
2459 // special case for input like " foo\n " (see pre_spec.rb)
2461 ary_entry(parser->line_buffer, -2) == PRE &&
2462 parser->pending_crlf)
2463 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2465 // close any open scopes on hitting EOF
2466 wiki_rollback_failed_link(parser); // if any
2467 wiki_pop_all_from_stack(parser);
2468 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2474 // reset current token; forcing lexer to return another token at the top of the loop
2478 // nasty hack to avoid re-allocating our return value
2479 str_append(parser->output, null_str, 1); // null-terminate
2480 len = parser->output->len - 1; // don't count null termination
2482 #if defined(RUBY_1_9_x)
2483 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2484 free(RSTRING_PTR(out));
2485 RSTRING(out)->as.heap.aux.capa = len;
2486 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2487 RSTRING(out)->as.heap.len = len;
2488 #elif defined(RUBY_1_8_x)
2489 VALUE out = rb_str_new2("");
2490 free(RSTRING_PTR(out));
2491 RSTRING(out)->len = len;
2492 RSTRING(out)->aux.capa = len;
2493 RSTRING(out)->ptr = parser->output->ptr;
2495 #error unsupported RUBY_VERSION
2497 parser->output->ptr = NULL; // don't double-free