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=\"";
130 const char pre_class_start[] = "<pre class=\"";
131 const char pre_class_end[] = "-syntax\">";
133 // Mark the parser struct designated by ptr as a participant in Ruby's
134 // mark-and-sweep garbage collection scheme. A variable named name is placed on
135 // the C stack to prevent the structure from being prematurely collected.
136 #define GC_WRAP_PARSER(ptr, name) volatile VALUE name __attribute__((unused)) = Data_Wrap_Struct(rb_cObject, 0, parser_free, ptr)
138 parser_t *parser_new(void)
140 parser_t *parser = ALLOC_N(parser_t, 1);
141 parser->capture = NULL; // not a real instance, pointer to other member's instance
142 parser->output = str_new();
143 parser->link_target = str_new();
144 parser->link_text = str_new();
145 parser->line_ending = NULL; // caller should set up
146 parser->tabulation = str_new();
147 parser->scope = ary_new();
148 parser->line = ary_new();
149 parser->line_buffer = ary_new();
150 parser->external_link_class = Qnil; // caller should set up
151 parser->mailto_class = Qnil; // caller should set up
152 parser->img_prefix = Qnil; // caller should set up
153 parser->base_indent = 0;
154 parser->current_indent = 0;
155 parser->base_heading_level = 0;
156 parser->pending_crlf = false;
157 parser->autolink = true;
158 parser->space_to_underscore = true;
162 void parser_free(parser_t *parser)
164 // we don't free parser->capture; it's just a redundant pointer
165 if (parser->output) str_free(parser->output);
166 if (parser->link_target) str_free(parser->link_target);
167 if (parser->link_text) str_free(parser->link_text);
168 if (parser->line_ending) str_free(parser->line_ending);
169 if (parser->tabulation) str_free(parser->tabulation);
170 if (parser->scope) ary_free(parser->scope);
171 if (parser->line) ary_free(parser->line);
172 if (parser->line_buffer) ary_free(parser->line_buffer);
176 // for testing and debugging only
177 VALUE Wikitext_parser_tokenize(VALUE self, VALUE string)
181 string = StringValue(string);
182 VALUE tokens = rb_ary_new();
183 char *p = RSTRING_PTR(string);
184 long len = RSTRING_LEN(string);
187 next_token(&token, NULL, p, pe);
188 rb_ary_push(tokens, wiki_token(&token));
189 while (token.type != END_OF_FILE)
191 next_token(&token, &token, NULL, pe);
192 rb_ary_push(tokens, wiki_token(&token));
197 // for benchmarking raw tokenization speed only
198 VALUE Wikitext_parser_benchmarking_tokenize(VALUE self, VALUE string)
202 string = StringValue(string);
203 char *p = RSTRING_PTR(string);
204 long len = RSTRING_LEN(string);
207 next_token(&token, NULL, p, pe);
208 while (token.type != END_OF_FILE)
209 next_token(&token, &token, NULL, pe);
213 VALUE Wikitext_parser_fulltext_tokenize(int argc, VALUE *argv, VALUE self)
216 VALUE string, options;
217 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
221 string = StringValue(string);
222 VALUE tokens = rb_ary_new();
224 // check instance variables
225 VALUE min = rb_iv_get(self, "@minimum_fulltext_token_length");
227 // process options hash (can override instance variables)
228 if (!NIL_P(options) && TYPE(options) == T_HASH)
230 if (rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern("minimum"))) == Qtrue)
231 min = rb_hash_aref(options, ID2SYM(rb_intern("minimum")));
233 int min_len = NIL_P(min) ? 3 : NUM2INT(min);
238 char *p = RSTRING_PTR(string);
239 long len = RSTRING_LEN(string);
242 token_t *_token = &token;
243 next_token(&token, NULL, p, pe);
244 while (token.type != END_OF_FILE)
251 if (TOKEN_LEN(_token) >= min_len)
252 rb_ary_push(tokens, TOKEN_TEXT(_token));
255 // ignore everything else
258 next_token(&token, &token, NULL, pe);
263 // we downcase "in place", overwriting the original contents of the buffer
264 void wiki_downcase_bang(char *ptr, long len)
266 for (long i = 0; i < len; i++)
268 if (ptr[i] >= 'A' && ptr[i] <= 'Z')
273 // prepare hyperlink and append it to parser->output
274 // if check_autolink is true, checks parser->autolink to decide whether to emit a real hyperlink
275 // or merely the literal link target
276 // if link_text is Qnil, the link_target is re-used for the link text
277 void wiki_append_hyperlink(parser_t *parser, VALUE link_prefix, str_t *link_target, str_t *link_text, VALUE link_class, bool check_autolink)
279 if (check_autolink && !parser->autolink)
280 str_append_str(parser->output, link_target);
283 str_append(parser->output, a_start, sizeof(a_start) - 1); // <a href="
284 if (!NIL_P(link_prefix))
285 str_append_string(parser->output, link_prefix);
286 str_append_str(parser->output, link_target);
288 // special handling for mailto URIs
289 const char *mailto = "mailto:";
290 long mailto_len = (long)sizeof(mailto) - 1; // don't count NUL byte
291 if ((link_target->len >= mailto_len &&
292 strncmp(mailto, link_target->ptr, mailto_len) == 0) ||
293 (!NIL_P(link_prefix) &&
294 RSTRING_LEN(link_prefix) >= mailto_len &&
295 strncmp(mailto, RSTRING_PTR(link_prefix), mailto_len) == 0))
296 link_class = parser->mailto_class; // use mailto_class from parser
297 if (link_class != Qnil)
299 str_append(parser->output, a_class, sizeof(a_class) - 1); // " class="
300 str_append_string(parser->output, link_class);
302 str_append(parser->output, a_start_close, sizeof(a_start_close) - 1); // ">
303 if (!link_text || link_text->len == 0) // re-use link_target
304 str_append_str(parser->output, link_target);
306 str_append_str(parser->output, link_text);
307 str_append(parser->output, a_end, sizeof(a_end) - 1); // </a>
311 void wiki_append_img(parser_t *parser, char *token_ptr, int token_len)
313 str_append(parser->output, img_start, sizeof(img_start) - 1); // <img src="
314 if (!NIL_P(parser->img_prefix) && *token_ptr != '/') // len always > 0
315 str_append_string(parser->output, parser->img_prefix);
316 str_append(parser->output, token_ptr, token_len);
317 str_append(parser->output, img_alt, sizeof(img_alt) - 1); // " alt="
318 str_append(parser->output, token_ptr, token_len);
319 str_append(parser->output, img_end, sizeof(img_end) - 1); // " />
322 // will emit indentation only if we are about to emit any of:
323 // <blockquote>, <p>, <ul>, <ol>, <li>, <h1> etc, <pre>
324 // each time we enter one of those spans must ++ the indentation level
325 void wiki_indent(parser_t *parser)
327 if (parser->base_indent == -1) // indentation disabled
329 int space_count = parser->current_indent + parser->base_indent;
332 char *old_end, *new_end;
333 if (parser->tabulation->len < space_count)
334 str_grow(parser->tabulation, space_count); // reallocates if necessary
335 old_end = parser->tabulation->ptr + parser->tabulation->len;
336 new_end = parser->tabulation->ptr + space_count;
337 while (old_end < new_end)
339 if (space_count > parser->tabulation->len)
340 parser->tabulation->len = space_count;
341 str_append(parser->output, parser->tabulation->ptr, space_count);
343 parser->current_indent += 2;
346 void wiki_append_pre_start(parser_t *parser, token_t *token)
349 if ((size_t)TOKEN_LEN(token) > sizeof(pre_start) - 1)
351 str_append(parser->output, pre_class_start, sizeof(pre_class_start) - 1); // <pre class="
352 str_append(parser->output, token->start + 11, TOKEN_LEN(token) - 13); // (the "lang" substring)
353 str_append(parser->output, pre_class_end, sizeof(pre_class_end) - 1); // -syntax">
356 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
357 ary_push(parser->scope, PRE_START);
358 ary_push(parser->line, PRE_START);
361 void wiki_dedent(parser_t *parser, bool emit)
363 if (parser->base_indent == -1) // indentation disabled
365 parser->current_indent -= 2;
368 int space_count = parser->current_indent + parser->base_indent;
370 str_append(parser->output, parser->tabulation->ptr, space_count);
373 // Pops a single item off the parser's scope stack.
374 // A corresponding closing tag is written to the target string.
375 // The target string may be the main output buffer, or a substring capturing buffer if a link is being scanned.
376 void wiki_pop_from_stack(parser_t *parser, str_t *target)
378 int top = ary_entry(parser->scope, -1);
382 target = parser->output;
384 // for headings, take base_heading_level into account
385 if (top >= H1_START && top <= H6_START)
387 top += parser->base_heading_level;
388 // no need to check for underflow (base_heading_level is never negative)
397 str_append(target, pre_end, sizeof(pre_end) - 1);
398 str_append_str(target, parser->line_ending);
399 wiki_dedent(parser, false);
403 case BLOCKQUOTE_START:
404 wiki_dedent(parser, true);
405 str_append(target, blockquote_end, sizeof(blockquote_end) - 1);
406 str_append_str(target, parser->line_ending);
410 // not a real HTML tag; so nothing to pop
415 str_append(target, strong_end, sizeof(strong_end) - 1);
420 str_append(target, em_end, sizeof(em_end) - 1);
425 str_append(target, tt_end, sizeof(tt_end) - 1);
429 wiki_dedent(parser, true);
430 str_append(target, ol_end, sizeof(ol_end) - 1);
431 str_append_str(target, parser->line_ending);
435 wiki_dedent(parser, true);
436 str_append(target, ul_end, sizeof(ul_end) - 1);
437 str_append_str(target, parser->line_ending);
441 // next token to pop will be a LI
442 // LI is an interesting token because sometimes we want it to behave like P (ie. do a non-emitting indent)
443 // and other times we want it to behave like BLOCKQUOTE (ie. when it has a nested list inside)
444 // hence this hack: we do an emitting dedent on behalf of the LI that we know must be coming
445 // and then when we pop the actual LI itself (below) we do the standard non-emitting indent
446 wiki_dedent(parser, true); // we really only want to emit the spaces
447 parser->current_indent += 2; // we don't want to decrement the actual indent level, so put it back
451 str_append(target, li_end, sizeof(li_end) - 1);
452 str_append_str(target, parser->line_ending);
453 wiki_dedent(parser, false);
457 str_append(target, h6_end, sizeof(h6_end) - 1);
458 str_append_str(target, parser->line_ending);
459 wiki_dedent(parser, false);
463 str_append(target, h5_end, sizeof(h5_end) - 1);
464 str_append_str(target, parser->line_ending);
465 wiki_dedent(parser, false);
469 str_append(target, h4_end, sizeof(h4_end) - 1);
470 str_append_str(target, parser->line_ending);
471 wiki_dedent(parser, false);
475 str_append(target, h3_end, sizeof(h3_end) - 1);
476 str_append_str(target, parser->line_ending);
477 wiki_dedent(parser, false);
481 str_append(target, h2_end, sizeof(h2_end) - 1);
482 str_append_str(target, parser->line_ending);
483 wiki_dedent(parser, false);
487 str_append(target, h1_end, sizeof(h1_end) - 1);
488 str_append_str(target, parser->line_ending);
489 wiki_dedent(parser, false);
493 // not an HTML tag; so nothing to emit
497 // not an HTML tag; so nothing to emit
501 // not an HTML tag; so nothing to emit
505 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
509 // not an HTML tag (only used to separate an external link target from the link text); so nothing to emit
513 str_append(target, p_end, sizeof(p_end) - 1);
514 str_append_str(target, parser->line_ending);
515 wiki_dedent(parser, false);
523 // should probably raise an exception here
526 ary_pop(parser->scope);
529 // Pops items off the top of parser's scope stack, accumulating closing tags for them into the target string, until item is reached.
530 // If including is true then the item itself is also popped.
531 // The target string may be the main output buffer, or a substring capturing buffer when scanning links.
532 void wiki_pop_from_stack_up_to(parser_t *parser, str_t *target, int item, bool including)
534 int continue_looping = 1;
537 int top = ary_entry(parser->scope, -1);
544 continue_looping = 0;
546 wiki_pop_from_stack(parser, target);
547 } while (continue_looping);
550 void wiki_pop_all_from_stack(parser_t *parser)
552 for (int i = 0, max = parser->scope->count; i < max; i++)
553 wiki_pop_from_stack(parser, NULL);
556 void wiki_start_para_if_necessary(parser_t *parser)
561 // if no block open yet, or top of stack is BLOCKQUOTE/BLOCKQUOTE_START (with nothing in it yet)
562 if (parser->scope->count == 0 ||
563 ary_entry(parser->scope, -1) == BLOCKQUOTE ||
564 ary_entry(parser->scope, -1) == BLOCKQUOTE_START)
567 str_append(parser->output, p_start, sizeof(p_start) - 1);
568 ary_push(parser->scope, P);
569 ary_push(parser->line, P);
571 else if (parser->pending_crlf)
574 // already in a paragraph block; convert pending CRLF into a space
575 str_append(parser->output, space, sizeof(space) - 1);
577 // PRE blocks can have pending CRLF too (helps us avoid emitting the trailing newline)
578 str_append_str(parser->output, parser->line_ending);
580 parser->pending_crlf = false;
583 void wiki_emit_pending_crlf_if_necessary(parser_t *parser)
585 if (parser->pending_crlf)
587 str_append_str(parser->output, parser->line_ending);
588 parser->pending_crlf = false;
592 // Helper function that pops any excess elements off scope (pushing is already handled in the respective rules).
593 // For example, given input like:
598 // Upon seeing "bar", we want to pop two BLOCKQUOTE elements from the scope.
599 // The reverse case (shown below) is handled from inside the BLOCKQUOTE rule itself:
604 // Things are made slightly more complicated by the fact that there is one block-level tag that can be on the scope
605 // but not on the line scope:
610 // Here on seeing "bar" we have one item on the scope (BLOCKQUOTE_START) which we don't want to pop, but we have nothing
611 // on the line scope.
612 // Luckily, BLOCKQUOTE_START tokens can only appear at the start of the scope array, so we can check for them first before
613 // entering the for loop.
614 void wiki_pop_excess_elements(parser_t *parser)
618 for (int i = parser->scope->count - ary_count(parser->scope, BLOCKQUOTE_START), j = parser->line->count; i > j; i--)
620 // special case for last item on scope
623 // don't auto-pop P if it is only item on scope
624 if (ary_entry(parser->scope, -1) == P)
626 // add P to the line scope to prevent us entering the loop at all next time around
627 ary_push(parser->line, P);
631 wiki_pop_from_stack(parser, NULL);
635 // Convert a single UTF-8 codepoint to UTF-32
637 // Expects an input buffer, src, containing a UTF-8 encoded character (which
638 // may be multi-byte). The end of the input buffer, end, is also passed in to
639 // allow the detection of invalidly truncated codepoints. The number of bytes
640 // in the UTF-8 character (between 1 and 4) is returned by reference in
643 // Raises a RangeError if the supplied character is invalid UTF-8.
644 uint32_t wiki_utf8_to_utf32(char *src, char *end, long *width_out)
647 if ((unsigned char)src[0] <= 0x7f)
653 else if ((src[0] & 0xe0) == 0xc0)
655 // byte starts with 110..... : this should be a two-byte sequence
658 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
659 else if (((unsigned char)src[0] == 0xc0) ||
660 ((unsigned char)src[0] == 0xc1))
661 // overlong encoding: lead byte of 110..... but code point <= 127
662 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
663 else if ((src[1] & 0xc0) != 0x80 )
664 // should have second byte starting with 10......
665 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
668 ((uint32_t)(src[0] & 0x1f)) << 6 |
672 else if ((src[0] & 0xf0) == 0xe0)
674 // byte starts with 1110.... : this should be a three-byte sequence
676 // missing second or third byte
677 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
678 else if (((src[1] & 0xc0) != 0x80 ) ||
679 ((src[2] & 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] & 0x0f)) << 12 |
685 ((uint32_t)(src[1] & 0x3f)) << 6 |
689 else if ((src[0] & 0xf8) == 0xf0)
691 // bytes starts with 11110... : this should be a four-byte sequence
693 // missing second, third, or fourth byte
694 rb_raise(eWikitextParserError, "invalid encoding: truncated byte sequence");
695 else if ((unsigned char)src[0] >= 0xf5 &&
696 (unsigned char)src[0] <= 0xf7)
697 // disallowed by RFC 3629 (codepoints above 0x10ffff)
698 rb_raise(eWikitextParserError, "invalid encoding: overlong encoding");
699 else if (((src[1] & 0xc0) != 0x80 ) ||
700 ((src[2] & 0xc0) != 0x80 ) ||
701 ((src[3] & 0xc0) != 0x80 ))
702 // should have second and third bytes starting with 10......
703 rb_raise(eWikitextParserError, "invalid encoding: malformed byte sequence");
706 ((uint32_t)(src[0] & 0x07)) << 18 |
707 ((uint32_t)(src[1] & 0x3f)) << 12 |
708 ((uint32_t)(src[1] & 0x3f)) << 6 |
713 rb_raise(eWikitextParserError, "invalid encoding: unexpected byte");
717 void wiki_append_entity_from_utf32_char(str_t *output, uint32_t character)
719 char hex_string[8] = { '&', '#', 'x', 0, 0, 0, 0, ';' };
720 char scratch = (character & 0xf000) >> 12;
721 hex_string[3] = (scratch <= 9 ? scratch + 48 : scratch + 87);
722 scratch = (character & 0x0f00) >> 8;
723 hex_string[4] = (scratch <= 9 ? scratch + 48 : scratch + 87);
724 scratch = (character & 0x00f0) >> 4;
725 hex_string[5] = (scratch <= 9 ? scratch + 48 : scratch + 87);
726 scratch = character & 0x000f;
727 hex_string[6] = (scratch <= 9 ? scratch + 48 : scratch + 87);
728 str_append(output, hex_string, sizeof(hex_string));
731 // trim parser->link_text in place
732 void wiki_trim_link_text(parser_t *parser)
734 char *src = parser->link_text->ptr;
735 char *start = src; // remember this so we can check if we're at the start
737 char *non_space = src; // remember last non-space character output
738 char *end = src + parser->link_text->len;
750 if (left != start || non_space + 1 != end)
752 // TODO: could potentially avoid this memmove by extending the str_t struct with an "offset" or "free" member
753 parser->link_text->len = (non_space + 1) - left;
754 memmove(parser->link_text->ptr, left, parser->link_text->len);
758 // - non-printable (non-ASCII) characters converted to numeric entities
759 // - QUOT and AMP characters converted to named entities
760 // - if trim is true, leading and trailing whitespace trimmed
761 // - if trim is false, there is no special treatment of spaces
762 void wiki_append_sanitized_link_target(parser_t *parser, str_t *output, bool trim)
764 char *src = parser->link_target->ptr;
765 char *start = src; // remember this so we can check if we're at the start
766 char *non_space = output->ptr + output->len; // remember last non-space character output
767 char *end = src + parser->link_target->len;
770 // need at most 8 bytes to display each input character (�)
771 if (output->ptr + output->len + 8 > output->ptr + output->capacity) // outgrowing buffer, must grow
773 char *old_ptr = output->ptr;
774 str_grow(output, output->len + (end - src) * 8); // allocate enough for worst case
775 if (old_ptr != output->ptr) // may have moved
776 non_space += output->ptr - old_ptr;
781 char quot_entity_literal[] = { '&', 'q', 'u', 'o', 't', ';' }; // no trailing NUL
782 str_append(output, quot_entity_literal, sizeof(quot_entity_literal));
784 else if (*src == '&')
786 char amp_entity_literal[] = { '&', 'a', 'm', 'p', ';' }; // no trailing NUL
787 str_append(output, amp_entity_literal, sizeof(amp_entity_literal));
789 else if (*src == '<' || *src == '>')
790 rb_raise(rb_eRangeError, "invalid link text (\"%c\" may not appear in link text)", *src);
791 else if (*src == ' ' && src == start && trim)
792 start++; // we eat leading space
793 else if (*src >= 0x20 && *src <= 0x7e) // printable ASCII
795 *(output->ptr + output->len) = *src;
798 else // all others: must convert to entities
801 wiki_append_entity_from_utf32_char(output, wiki_utf8_to_utf32(src, end, &width));
803 non_space = output->ptr + output->len;
807 non_space = output->ptr + output->len;
811 // trim trailing space if necessary
812 if (trim && output->ptr + output->len != non_space)
813 output->len -= (output->ptr + output->len) - non_space;
816 VALUE Wikitext_parser_sanitize_link_target(VALUE self, VALUE string)
819 parser.link_target = str_new_from_string(string);
820 GC_WRAP_STR(parser.link_target, link_target_gc);
821 str_t *output = str_new();
822 GC_WRAP_STR(output, output_gc);
823 wiki_append_sanitized_link_target(&parser, output, true);
824 return string_from_str(output);
827 // Encodes the parser link_target member (in-place) according to RFCs 2396 and 2718
829 // Leading and trailing whitespace trimmed. Spaces are converted to
830 // underscores if the parser space_to_underscore member is true.
831 static void wiki_encode_link_target(parser_t *parser)
833 char *src = parser->link_target->ptr;
834 char *start = src; // remember this so we can check if we're at the start
835 long len = parser->link_target->len;
838 char *end = src + len;
839 long dest_len = len * 2;
840 char *dest = ALLOC_N(char, dest_len);
841 char *dest_ptr = dest; // hang on to this so we can pass it to free() later
842 char *non_space = dest; // remember last non-space character output
843 static char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
844 for (; src < end; src++)
846 // worst case: a single character may grow to 3 characters once encoded
847 if ((dest + 3) > (dest_ptr + dest_len))
849 // outgrowing buffer, must reallocate
850 char *old_dest = dest;
851 char *old_dest_ptr = dest_ptr;
853 dest = realloc(dest_ptr, dest_len);
856 // would have used reallocf, but this has to run on Linux too, not just Darwin
858 rb_raise(rb_eNoMemError, "failed to re-allocate temporary storage (memory allocation error)");
861 dest = dest_ptr + (old_dest - old_dest_ptr);
862 non_space = dest_ptr + (non_space - old_dest_ptr);
865 // pass through unreserved characters
866 if ((*src >= 'a' && *src <= 'z') ||
867 (*src >= 'A' && *src <= 'Z') ||
868 (*src >= '0' && *src <= '9') ||
877 else if (*src == ' ' && src == start)
878 start++; // we eat leading space
879 else if (*src == ' ' && parser->space_to_underscore)
881 else // everything else gets URL-encoded
884 *dest++ = hex[(unsigned char)(*src) / 16]; // left
885 *dest++ = hex[(unsigned char)(*src) % 16]; // right
891 // trim trailing space if necessary
892 if (non_space > dest_ptr && dest != non_space)
893 dest_len = non_space - dest_ptr;
895 dest_len = dest - dest_ptr;
896 str_clear(parser->link_target);
897 str_append(parser->link_target, dest_ptr, dest_len);
901 VALUE Wikitext_parser_encode_link_target(VALUE self, VALUE in)
904 parser.space_to_underscore = false;
905 parser.link_target = str_new_from_string(in);
906 GC_WRAP_STR(parser.link_target, link_target_gc);
907 wiki_encode_link_target(&parser);
908 return string_from_str(parser.link_target);
911 // returns 1 (true) if supplied string is blank (nil, empty, or all whitespace)
912 // returns 0 (false) otherwise
913 bool wiki_blank(str_t *str)
917 for (char *ptr = str->ptr,
918 *end = str->ptr + str->len;
927 void wiki_rollback_failed_internal_link(parser_t *parser)
930 return; // nothing to do!
931 int scope_includes_separator = IN(SEPARATOR);
932 wiki_pop_from_stack_up_to(parser, NULL, LINK_START, true);
933 str_append(parser->output, link_start, sizeof(link_start) - 1);
934 if (parser->link_target->len > 0)
936 wiki_append_sanitized_link_target(parser, parser->output, false);
937 if (scope_includes_separator)
939 str_append(parser->output, separator, sizeof(separator) - 1);
940 if (parser->link_text->len > 0)
941 str_append_str(parser->output, parser->link_text);
944 parser->capture = NULL;
945 str_clear(parser->link_target);
946 str_clear(parser->link_text);
949 void wiki_rollback_failed_external_link(parser_t *parser)
951 if (!IN(EXT_LINK_START))
952 return; // nothing to do!
954 // store a couple of values before popping
955 int scope_includes_space = IN(SPACE);
956 VALUE link_class = IN(PATH) ? Qnil : parser->external_link_class;
957 wiki_pop_from_stack_up_to(parser, NULL, EXT_LINK_START, true);
959 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
960 if (parser->link_target->len > 0)
962 wiki_append_hyperlink(parser, Qnil, parser->link_target, NULL, link_class, true);
963 if (scope_includes_space)
965 str_append(parser->output, space, sizeof(space) - 1);
966 if (parser->link_text->len > 0)
967 str_append_str(parser->output, parser->link_text);
970 parser->capture = NULL;
971 str_clear(parser->link_target);
972 str_clear(parser->link_text);
975 void wiki_rollback_failed_link(parser_t *parser)
977 wiki_rollback_failed_internal_link(parser);
978 wiki_rollback_failed_external_link(parser);
981 VALUE Wikitext_parser_initialize(int argc, VALUE *argv, VALUE self)
985 if (rb_scan_args(argc, argv, "01", &options) == 0) // 0 mandatory arguments, 1 optional argument
989 VALUE autolink = Qtrue;
990 VALUE line_ending = rb_str_new2("\n");
991 VALUE external_link_class = rb_str_new2("external");
992 VALUE mailto_class = rb_str_new2("mailto");
993 VALUE internal_link_prefix = rb_str_new2("/wiki/");
994 VALUE img_prefix = rb_str_new2("/images/");
995 VALUE space_to_underscore = Qtrue;
996 VALUE minimum_fulltext_token_length = INT2NUM(3);
997 VALUE base_heading_level = INT2NUM(0);
999 // process options hash (override defaults)
1000 if (!NIL_P(options) && TYPE(options) == T_HASH)
1002 #define OVERRIDE_IF_SET(name) rb_funcall(options, rb_intern("has_key?"), 1, ID2SYM(rb_intern(#name))) == Qtrue ? \
1003 rb_hash_aref(options, ID2SYM(rb_intern(#name))) : name
1004 autolink = OVERRIDE_IF_SET(autolink);
1005 line_ending = OVERRIDE_IF_SET(line_ending);
1006 external_link_class = OVERRIDE_IF_SET(external_link_class);
1007 mailto_class = OVERRIDE_IF_SET(mailto_class);
1008 internal_link_prefix = OVERRIDE_IF_SET(internal_link_prefix);
1009 img_prefix = OVERRIDE_IF_SET(img_prefix);
1010 space_to_underscore = OVERRIDE_IF_SET(space_to_underscore);
1011 minimum_fulltext_token_length = OVERRIDE_IF_SET(minimum_fulltext_token_length);
1012 base_heading_level = OVERRIDE_IF_SET(base_heading_level);
1015 // no need to call super here; rb_call_super()
1016 rb_iv_set(self, "@autolink", autolink);
1017 rb_iv_set(self, "@line_ending", line_ending);
1018 rb_iv_set(self, "@external_link_class", external_link_class);
1019 rb_iv_set(self, "@mailto_class", mailto_class);
1020 rb_iv_set(self, "@internal_link_prefix", internal_link_prefix);
1021 rb_iv_set(self, "@img_prefix", img_prefix);
1022 rb_iv_set(self, "@space_to_underscore", space_to_underscore);
1023 rb_iv_set(self, "@minimum_fulltext_token_length", minimum_fulltext_token_length);
1024 rb_iv_set(self, "@base_heading_level", base_heading_level);
1028 VALUE Wikitext_parser_profiling_parse(VALUE self, VALUE string)
1030 for (int i = 0; i < 100000; i++)
1031 Wikitext_parser_parse(1, &string, self);
1035 VALUE Wikitext_parser_parse(int argc, VALUE *argv, VALUE self)
1037 // process arguments
1038 VALUE string, options;
1039 if (rb_scan_args(argc, argv, "11", &string, &options) == 1) // 1 mandatory argument, 1 optional argument
1043 string = StringValue(string);
1045 // process options hash
1046 int base_indent = 0;
1047 int base_heading_level = NUM2INT(rb_iv_get(self, "@base_heading_level"));
1048 VALUE link_proc = Qnil;
1049 if (!NIL_P(options) && TYPE(options) == T_HASH)
1051 // :indent => 0 (or more)
1052 ID has_key = rb_intern("has_key?");
1053 ID id = ID2SYM(rb_intern("indent"));
1054 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1056 VALUE indent = rb_hash_aref(options, id);
1057 if (indent == Qfalse)
1058 base_indent = -1; // indentation disabled
1061 base_indent = NUM2INT(indent);
1062 if (base_indent < 0)
1067 // :base_heading_level => 0/1/2/3/4/5/6
1068 id = ID2SYM(rb_intern("base_heading_level"));
1069 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1070 base_heading_level = NUM2INT(rb_hash_aref(options, id));
1072 // :link_proc => lambda { |link_target| ... }
1073 id = ID2SYM(rb_intern("link_proc"));
1074 if (rb_funcall(options, has_key, 1, id) == Qtrue)
1075 link_proc = rb_hash_aref(options, id);
1078 // normalize, regardless of whether this came from instance variable or override
1079 if (base_heading_level < 0)
1080 base_heading_level = 0;
1081 if (base_heading_level > 6)
1082 base_heading_level = 6;
1085 char *p = RSTRING_PTR(string);
1086 long len = RSTRING_LEN(string);
1089 // access these once per parse
1090 VALUE line_ending = rb_iv_get(self, "@line_ending");
1091 line_ending = StringValue(line_ending);
1092 VALUE link_class = rb_iv_get(self, "@external_link_class");
1093 link_class = NIL_P(link_class) ? Qnil : StringValue(link_class);
1094 VALUE mailto_class = rb_iv_get(self, "@mailto_class");
1095 mailto_class = NIL_P(mailto_class) ? Qnil : StringValue(mailto_class);
1096 VALUE prefix = rb_iv_get(self, "@internal_link_prefix");
1098 // set up parser struct to make passing parameters a little easier
1099 parser_t *parser = parser_new();
1100 GC_WRAP_PARSER(parser, parser_gc);
1101 parser->external_link_class = link_class;
1102 parser->mailto_class = mailto_class;
1103 parser->img_prefix = rb_iv_get(self, "@img_prefix");
1104 parser->autolink = rb_iv_get(self, "@autolink") == Qtrue ? true : false;
1105 parser->space_to_underscore = rb_iv_get(self, "@space_to_underscore") == Qtrue ? true : false;
1106 parser->line_ending = str_new_from_string(line_ending);
1107 parser->base_indent = base_indent;
1108 parser->base_heading_level = base_heading_level;
1110 // this simple looping design leads to a single enormous function,
1111 // but it's faster than doing actual recursive descent and also secure in the face of
1112 // malicious input that seeks to overflow the stack
1113 // (with "<blockquote><blockquote><blockquote>..." times by 10,000, for example)
1114 // given that we expect to deal with a lot of malformed input, a recursive descent design is less appropriate
1115 // than a straightforward looping translator like this one anyway
1117 _token.type = NO_TOKEN;
1118 token_t *token = NULL;
1121 // note that whenever we grab a token we push it into the line buffer
1122 // this provides us with context-sensitive "memory" of what's been seen so far on this line
1123 #define NEXT_TOKEN() token = &_token, next_token(token, token, NULL, pe), ary_push(parser->line_buffer, token->type)
1125 // check to see if we have a token hanging around from a previous iteration of this loop
1128 if (_token.type == NO_TOKEN)
1130 // first time here (haven't started scanning yet)
1132 next_token(token, NULL, p, pe);
1133 ary_push(parser->line_buffer, token->type);
1139 int type = token->type;
1141 // can't declare new variables inside a switch statement, so predeclare them here
1142 long remove_strong = -1;
1143 long remove_em = -1;
1145 // general purpose counters, flags and pointers
1149 str_t *output = NULL;
1151 str_t *token_str = &_token_str;
1153 // The following giant switch statement contains cases for all the possible token types.
1154 // In the most basic sense we are emitting the HTML that corresponds to each token,
1155 // but some tokens require context information in order to decide what to output.
1156 // For example, does the STRONG token (''') translate to <strong> or </strong>?
1157 // So when looking at any given token we have three state-maintaining variables which gives us a notion of "where we are":
1159 // - the "scope" stack (indicates what HTML DOM structures we are currently nested inside, similar to a CSS selector)
1160 // - the line buffer (records tokens seen so far on the current line)
1161 // - the line "scope" stack (indicates what the scope should be based only on what is visible on the line so far)
1163 // Although this is fairly complicated, there is one key simplifying factor:
1164 // The translator continuously performs auto-correction, and this means that we always have a guarantee that the
1165 // scope stack (up to the current token) is valid; our translator can take this as a given.
1166 // Auto-correction basically consists of inserting missing tokens (preventing subsquent HTML from being messed up),
1167 // or converting illegal (unexpected) tokens to their plain text equivalents (providing visual feedback to Wikitext author).
1171 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1173 str_append(parser->output, space, sizeof(space) - 1);
1176 else if (IN(BLOCKQUOTE_START))
1178 // this kind of nesting not allowed (to avoid user confusion)
1179 wiki_pop_excess_elements(parser);
1180 wiki_start_para_if_necessary(parser);
1181 output = parser->capture ? parser->capture : parser->output;
1182 str_append(output, space, sizeof(space) - 1);
1186 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1187 ary_push(parser->line, PRE);
1188 i = ary_count(parser->line, BLOCKQUOTE);
1189 j = ary_count(parser->scope, BLOCKQUOTE);
1192 // must pop (reduce nesting level)
1193 for (i = j - i; i > 0; i--)
1194 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1199 parser->pending_crlf = false;
1200 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1201 wiki_indent(parser);
1202 str_append(parser->output, pre_start, sizeof(pre_start) - 1);
1203 ary_push(parser->scope, PRE);
1208 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1210 wiki_emit_pending_crlf_if_necessary(parser);
1211 str_append(parser->output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1213 else if (IN(BLOCKQUOTE_START))
1215 wiki_rollback_failed_link(parser); // if any
1216 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1217 wiki_append_pre_start(parser, token);
1219 else if (IN(BLOCKQUOTE))
1221 if (token->column_start == 1) // only allowed in first column
1223 wiki_rollback_failed_link(parser); // if any
1224 wiki_pop_all_from_stack(parser);
1225 wiki_append_pre_start(parser, token);
1227 else // PRE_START illegal here
1229 output = parser->capture ? parser->capture : parser->output;
1230 wiki_pop_excess_elements(parser);
1231 wiki_start_para_if_necessary(parser);
1232 str_append(output, escaped_pre_start, sizeof(escaped_pre_start) - 1);
1237 wiki_rollback_failed_link(parser); // if any
1238 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1239 wiki_append_pre_start(parser, token);
1244 if (IN_EITHER_OF(NO_WIKI_START, PRE))
1246 wiki_emit_pending_crlf_if_necessary(parser);
1247 str_append(parser->output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1252 wiki_pop_from_stack_up_to(parser, parser->output, PRE_START, true);
1255 output = parser->capture ? parser->capture : parser->output;
1256 wiki_pop_excess_elements(parser);
1257 wiki_start_para_if_necessary(parser);
1258 str_append(output, escaped_pre_end, sizeof(escaped_pre_end) - 1);
1264 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1265 // no need to check for <pre>; can never appear inside it
1266 str_append(parser->output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1267 else if (IN(BLOCKQUOTE_START))
1269 // this kind of nesting not allowed (to avoid user confusion)
1270 wiki_pop_excess_elements(parser);
1271 wiki_start_para_if_necessary(parser);
1272 output = parser->capture ? parser->capture : parser->output;
1273 str_append(output, escaped_blockquote, TOKEN_LEN(token) + 3); // will either emit ">" or "> "
1278 ary_push(parser->line, BLOCKQUOTE);
1280 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1281 i = ary_count(parser->line, BLOCKQUOTE);
1282 j = ary_count(parser->scope, BLOCKQUOTE);
1284 // 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
1285 while (NEXT_TOKEN(), (token->type == BLOCKQUOTE))
1287 ary_push(parser->line, BLOCKQUOTE);
1291 // now decide whether to push, pop or do nothing
1294 // must push (increase nesting level)
1295 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1296 for (i = i - j; i > 0; i--)
1298 wiki_indent(parser);
1299 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1300 str_append_str(parser->output, parser->line_ending);
1301 ary_push(parser->scope, BLOCKQUOTE);
1306 // must pop (reduce nesting level)
1307 for (i = j - i; i > 0; i--)
1308 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1311 // jump to top of the loop to process token we scanned during lookahead
1316 case BLOCKQUOTE_START:
1317 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1319 wiki_emit_pending_crlf_if_necessary(parser);
1320 str_append(parser->output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1322 else if (IN(BLOCKQUOTE_START))
1324 // nesting is fine here
1325 wiki_rollback_failed_link(parser); // if any
1326 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1327 wiki_indent(parser);
1328 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1329 str_append_str(parser->output, parser->line_ending);
1330 ary_push(parser->scope, BLOCKQUOTE_START);
1331 ary_push(parser->line, BLOCKQUOTE_START);
1333 else if (IN(BLOCKQUOTE))
1335 if (token->column_start == 1) // only allowed in first column
1337 wiki_rollback_failed_link(parser); // if any
1338 wiki_pop_all_from_stack(parser);
1339 wiki_indent(parser);
1340 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1341 str_append_str(parser->output, parser->line_ending);
1342 ary_push(parser->scope, BLOCKQUOTE_START);
1343 ary_push(parser->line, BLOCKQUOTE_START);
1345 else // BLOCKQUOTE_START illegal here
1347 output = parser->capture ? parser->capture : parser->output;
1348 wiki_pop_excess_elements(parser);
1349 wiki_start_para_if_necessary(parser);
1350 str_append(output, escaped_blockquote_start, sizeof(escaped_blockquote_start) - 1);
1355 // would be nice to eliminate the repetition here but it's probably the clearest way
1356 wiki_rollback_failed_link(parser); // if any
1357 wiki_pop_from_stack_up_to(parser, NULL, P, true);
1358 wiki_indent(parser);
1359 str_append(parser->output, blockquote_start, sizeof(blockquote_start) - 1);
1360 str_append_str(parser->output, parser->line_ending);
1361 ary_push(parser->scope, BLOCKQUOTE_START);
1362 ary_push(parser->line, BLOCKQUOTE_START);
1366 case BLOCKQUOTE_END:
1367 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1369 wiki_emit_pending_crlf_if_necessary(parser);
1370 str_append(parser->output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1374 if (IN(BLOCKQUOTE_START))
1375 wiki_pop_from_stack_up_to(parser, parser->output, BLOCKQUOTE_START, true);
1378 output = parser->capture ? parser->capture : parser->output;
1379 wiki_pop_excess_elements(parser);
1380 wiki_start_para_if_necessary(parser);
1381 str_append(output, escaped_blockquote_end, sizeof(escaped_blockquote_end) - 1);
1387 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1389 wiki_emit_pending_crlf_if_necessary(parser);
1390 str_append(parser->output, escaped_no_wiki_start, sizeof(escaped_no_wiki_start) - 1);
1394 wiki_pop_excess_elements(parser);
1395 wiki_start_para_if_necessary(parser);
1396 ary_push(parser->scope, NO_WIKI_START);
1397 ary_push(parser->line, NO_WIKI_START);
1402 if (IN(NO_WIKI_START))
1403 // <nowiki> should always only ever be the last item in the stack, but use the helper routine just in case
1404 wiki_pop_from_stack_up_to(parser, NULL, NO_WIKI_START, true);
1407 wiki_pop_excess_elements(parser);
1408 wiki_start_para_if_necessary(parser);
1409 str_append(parser->output, escaped_no_wiki_end, sizeof(escaped_no_wiki_end) - 1);
1414 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1416 wiki_emit_pending_crlf_if_necessary(parser);
1417 str_append(parser->output, literal_strong_em, sizeof(literal_strong_em) - 1);
1421 output = parser->capture ? parser->capture : parser->output;
1422 wiki_pop_excess_elements(parser);
1424 // if you've seen STRONG/STRONG_START or EM/EM_START, must close them in the reverse order that you saw them!
1425 // otherwise, must open them
1428 j = parser->scope->count;
1429 for (j = j - 1; j >= 0; j--)
1431 int val = ary_entry(parser->scope, j);
1432 if (val == STRONG || val == STRONG_START)
1434 str_append(output, strong_end, sizeof(strong_end) - 1);
1437 else if (val == EM || val == EM_START)
1439 str_append(output, em_end, sizeof(em_end) - 1);
1444 if (remove_strong > remove_em) // must remove strong first
1446 ary_pop(parser->scope);
1448 ary_pop(parser->scope);
1449 else // there was no em to remove!, so consider this an opening em tag
1451 str_append(output, em_start, sizeof(em_start) - 1);
1452 ary_push(parser->scope, EM);
1453 ary_push(parser->line, EM);
1456 else if (remove_em > remove_strong) // must remove em first
1458 ary_pop(parser->scope);
1459 if (remove_strong > -1)
1460 ary_pop(parser->scope);
1461 else // there was no strong to remove!, so consider this an opening strong tag
1463 str_append(output, strong_start, sizeof(strong_start) - 1);
1464 ary_push(parser->scope, STRONG);
1465 ary_push(parser->line, STRONG);
1468 else // no strong or em to remove, so this must be a new opening of both
1470 wiki_start_para_if_necessary(parser);
1471 str_append(output, strong_em_start, sizeof(strong_em_start) - 1);
1472 ary_push(parser->scope, STRONG);
1473 ary_push(parser->line, STRONG);
1474 ary_push(parser->scope, EM);
1475 ary_push(parser->line, EM);
1480 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1482 wiki_emit_pending_crlf_if_necessary(parser);
1483 str_append(parser->output, literal_strong, sizeof(literal_strong) - 1);
1487 output = parser->capture ? parser->capture : parser->output;
1488 if (IN(STRONG_START))
1489 // already in span started with <strong>, no choice but to emit this literally
1490 str_append(output, literal_strong, sizeof(literal_strong) - 1);
1491 else if (IN(STRONG))
1492 // STRONG already seen, this is a closing tag
1493 wiki_pop_from_stack_up_to(parser, output, STRONG, true);
1496 // this is a new opening
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);
1501 ary_push(parser->line, STRONG);
1507 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1509 wiki_emit_pending_crlf_if_necessary(parser);
1510 str_append(parser->output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1514 output = parser->capture ? parser->capture : parser->output;
1515 if (IN_EITHER_OF(STRONG_START, STRONG))
1516 str_append(output, escaped_strong_start, sizeof(escaped_strong_start) - 1);
1519 wiki_pop_excess_elements(parser);
1520 wiki_start_para_if_necessary(parser);
1521 str_append(output, strong_start, sizeof(strong_start) - 1);
1522 ary_push(parser->scope, STRONG_START);
1523 ary_push(parser->line, STRONG_START);
1529 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1531 wiki_emit_pending_crlf_if_necessary(parser);
1532 str_append(parser->output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1536 output = parser->capture ? parser->capture : parser->output;
1537 if (IN(STRONG_START))
1538 wiki_pop_from_stack_up_to(parser, output, STRONG_START, true);
1541 // no STRONG_START in scope, so must interpret the STRONG_END without any special meaning
1542 wiki_pop_excess_elements(parser);
1543 wiki_start_para_if_necessary(parser);
1544 str_append(output, escaped_strong_end, sizeof(escaped_strong_end) - 1);
1550 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1552 wiki_emit_pending_crlf_if_necessary(parser);
1553 str_append(parser->output, literal_em, sizeof(literal_em) - 1);
1557 output = parser->capture ? parser->capture : parser->output;
1559 // already in span started with <em>, no choice but to emit this literally
1560 str_append(output, literal_em, sizeof(literal_em) - 1);
1562 // EM already seen, this is a closing tag
1563 wiki_pop_from_stack_up_to(parser, output, EM, true);
1566 // this is a new opening
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);
1571 ary_push(parser->line, EM);
1577 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1579 wiki_emit_pending_crlf_if_necessary(parser);
1580 str_append(parser->output, escaped_em_start, sizeof(escaped_em_start) - 1);
1584 output = parser->capture ? parser->capture : parser->output;
1585 if (IN_EITHER_OF(EM_START, EM))
1586 str_append(output, escaped_em_start, sizeof(escaped_em_start) - 1);
1589 wiki_pop_excess_elements(parser);
1590 wiki_start_para_if_necessary(parser);
1591 str_append(output, em_start, sizeof(em_start) - 1);
1592 ary_push(parser->scope, EM_START);
1593 ary_push(parser->line, EM_START);
1599 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1601 wiki_emit_pending_crlf_if_necessary(parser);
1602 str_append(parser->output, escaped_em_end, sizeof(escaped_em_end) - 1);
1606 output = parser->capture ? parser->capture : parser->output;
1608 wiki_pop_from_stack_up_to(parser, output, EM_START, true);
1611 // no EM_START in scope, so must interpret the TT_END without any special meaning
1612 wiki_pop_excess_elements(parser);
1613 wiki_start_para_if_necessary(parser);
1614 str_append(output, escaped_em_end, sizeof(escaped_em_end) - 1);
1620 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1622 wiki_emit_pending_crlf_if_necessary(parser);
1623 str_append(parser->output, backtick, sizeof(backtick) - 1);
1627 output = parser->capture ? parser->capture : parser->output;
1629 // already in span started with <tt>, no choice but to emit this literally
1630 str_append(output, backtick, sizeof(backtick) - 1);
1632 // TT (`) already seen, this is a closing tag
1633 wiki_pop_from_stack_up_to(parser, output, TT, true);
1636 // this is a new opening
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);
1641 ary_push(parser->line, TT);
1647 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1649 wiki_emit_pending_crlf_if_necessary(parser);
1650 str_append(parser->output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1654 output = parser->capture ? parser->capture : parser->output;
1655 if (IN_EITHER_OF(TT_START, TT))
1656 str_append(output, escaped_tt_start, sizeof(escaped_tt_start) - 1);
1659 wiki_pop_excess_elements(parser);
1660 wiki_start_para_if_necessary(parser);
1661 str_append(output, tt_start, sizeof(tt_start) - 1);
1662 ary_push(parser->scope, TT_START);
1663 ary_push(parser->line, TT_START);
1669 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1671 wiki_emit_pending_crlf_if_necessary(parser);
1672 str_append(parser->output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1676 output = parser->capture ? parser->capture : parser->output;
1678 wiki_pop_from_stack_up_to(parser, output, TT_START, true);
1681 // no TT_START in scope, so must interpret the TT_END without any special meaning
1682 wiki_pop_excess_elements(parser);
1683 wiki_start_para_if_necessary(parser);
1684 str_append(output, escaped_tt_end, sizeof(escaped_tt_end) - 1);
1691 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1693 // no need to check for PRE; can never appear inside it
1694 str_append(parser->output, token->start, TOKEN_LEN(token));
1698 // count number of tokens in line and scope stacks
1699 int bq_count = ary_count(parser->scope, BLOCKQUOTE_START);
1700 i = parser->line->count - ary_count(parser->line, BLOCKQUOTE_START);
1701 j = parser->scope->count - bq_count;
1704 // list tokens can be nested so look ahead for any more which might affect the decision to push or pop
1708 if (type == OL || type == UL)
1711 if (i - k >= 2) // already seen at least one OL or UL
1713 ary_push(parser->line, NESTED_LIST); // which means this is a nested list
1718 ary_push(parser->line, type);
1719 ary_push(parser->line, LI);
1721 // want to compare line with scope but can only do so if scope has enough items on it
1724 if (ary_entry(parser->scope, i + bq_count - 2) == type &&
1725 ary_entry(parser->scope, i + bq_count - 1) == LI)
1727 // line and scope match at this point: do nothing yet
1731 // item just pushed onto line does not match corresponding slot of scope!
1732 for (; j >= i - 2; j--)
1733 // must pop back before emitting
1734 wiki_pop_from_stack(parser, NULL);
1736 // will emit UL or OL, then LI
1740 else // line stack size now exceeds scope stack size: must increase nesting level
1741 break; // will emit UL or OL, then LI
1745 // not a OL or UL token!
1747 // must close existing LI and re-open new one
1748 wiki_pop_from_stack(parser, NULL);
1751 // item just pushed onto line does not match corresponding slot of scope!
1753 // must pop back before emitting
1754 wiki_pop_from_stack(parser, NULL);
1762 if (type == OL || type == UL)
1764 // if LI is at the top of a stack this is the start of a nested list
1765 if (j > 0 && ary_entry(parser->scope, -1) == LI)
1767 // so we should precede it with a CRLF, and indicate that it's a nested list
1768 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1769 ary_push(parser->scope, NESTED_LIST);
1773 // this is a new list
1774 if (IN(BLOCKQUOTE_START))
1775 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1777 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1781 wiki_indent(parser);
1783 str_append(parser->output, ol_start, sizeof(ol_start) - 1);
1784 else if (type == UL)
1785 str_append(parser->output, ul_start, sizeof(ul_start) - 1);
1786 ary_push(parser->scope, type);
1787 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
1789 else if (type == SPACE)
1790 // silently throw away the optional SPACE token after final list marker
1793 wiki_indent(parser);
1794 str_append(parser->output, li_start, sizeof(li_start) - 1);
1795 ary_push(parser->scope, LI);
1797 // any subsequent UL or OL tokens on this line are syntax errors and must be emitted literally
1798 if (type == OL || type == UL)
1801 while (k++, NEXT_TOKEN(), (type = token->type))
1803 if (type == OL || type == UL)
1804 str_append(parser->output, token->start, TOKEN_LEN(token));
1805 else if (type == SPACE && k == 1)
1807 // silently throw away the optional SPACE token after final list marker
1816 // jump to top of the loop to process token we scanned during lookahead
1825 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
1827 // no need to check for PRE; can never appear inside it
1828 str_append(parser->output, token->start, TOKEN_LEN(token));
1832 // pop up to but not including the last BLOCKQUOTE on the scope stack
1833 if (IN(BLOCKQUOTE_START))
1834 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE_START, false);
1836 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, false);
1838 // count number of BLOCKQUOTE tokens in line buffer and in scope stack
1839 ary_push(parser->line, type);
1840 i = ary_count(parser->line, BLOCKQUOTE);
1841 j = ary_count(parser->scope, BLOCKQUOTE);
1843 // decide whether we need to pop off excess BLOCKQUOTE tokens (will never need to push; that is handled above in the BLOCKQUOTE case itself)
1846 // must pop (reduce nesting level)
1847 for (i = j - i; i > 0; i--)
1848 wiki_pop_from_stack_up_to(parser, NULL, BLOCKQUOTE, true);
1851 // discard any whitespace here (so that "== foo ==" will be translated to "<h2>foo</h2>" rather than "<h2> foo </h2")
1852 while (NEXT_TOKEN(), (token->type == SPACE))
1855 ary_push(parser->scope, type);
1856 wiki_indent(parser);
1858 // take base_heading_level into account
1859 type += base_heading_level;
1860 if (type > H6_START) // no need to check for underflow (base_heading_level never negative)
1863 // rather than repeat all that code for each kind of heading, share it and use a conditional here
1864 if (type == H6_START)
1865 str_append(parser->output, h6_start, sizeof(h6_start) - 1);
1866 else if (type == H5_START)
1867 str_append(parser->output, h5_start, sizeof(h5_start) - 1);
1868 else if (type == H4_START)
1869 str_append(parser->output, h4_start, sizeof(h4_start) - 1);
1870 else if (type == H3_START)
1871 str_append(parser->output, h3_start, sizeof(h3_start) - 1);
1872 else if (type == H2_START)
1873 str_append(parser->output, h2_start, sizeof(h2_start) - 1);
1874 else if (type == H1_START)
1875 str_append(parser->output, h1_start, sizeof(h1_start) - 1);
1877 // jump to top of the loop to process token we scanned during lookahead
1886 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1888 wiki_emit_pending_crlf_if_necessary(parser);
1889 str_append(parser->output, token->start, TOKEN_LEN(token));
1893 wiki_rollback_failed_external_link(parser); // if any
1894 if ((type == H6_END && !IN(H6_START)) ||
1895 (type == H5_END && !IN(H5_START)) ||
1896 (type == H4_END && !IN(H4_START)) ||
1897 (type == H3_END && !IN(H3_START)) ||
1898 (type == H2_END && !IN(H2_START)) ||
1899 (type == H1_END && !IN(H1_START)))
1901 // literal output only if not in appropriate scope (we stay silent in that case)
1902 wiki_start_para_if_necessary(parser);
1903 str_append(parser->output, token->start, TOKEN_LEN(token));
1909 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1911 wiki_emit_pending_crlf_if_necessary(parser);
1912 str_append(parser->output, token->start, TOKEN_LEN(token));
1916 wiki_pop_excess_elements(parser);
1917 wiki_start_para_if_necessary(parser);
1918 token_str->ptr = token->start;
1919 token_str->len = TOKEN_LEN(token);
1920 wiki_append_hyperlink(parser, rb_str_new2("mailto:"), token_str, NULL, mailto_class, true);
1925 if (IN(NO_WIKI_START))
1926 // user can temporarily suppress autolinking by using <nowiki></nowiki>
1927 // note that unlike MediaWiki, we do allow autolinking inside PRE blocks
1928 str_append(parser->output, token->start, TOKEN_LEN(token));
1929 else if (IN(LINK_START))
1931 // if the URI were allowed it would have been handled already in LINK_START
1932 wiki_rollback_failed_internal_link(parser);
1933 token_str->ptr = token->start;
1934 token_str->len = TOKEN_LEN(token);
1935 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1937 else if (IN(EXT_LINK_START))
1939 if (parser->link_target->len == 0)
1941 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1942 token_str->ptr = token->start;
1943 token_str->len = TOKEN_LEN(token);
1945 if (token->type == SPACE)
1947 ary_push(parser->scope, SPACE);
1948 str_append_str(parser->link_target, token_str);
1949 str_clear(parser->link_text);
1950 parser->capture = parser->link_text;
1951 token = NULL; // silently consume space
1955 // didn't see the space! this must be an error
1956 wiki_pop_from_stack(parser, NULL);
1957 wiki_pop_excess_elements(parser);
1958 wiki_start_para_if_necessary(parser);
1959 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
1960 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1964 str_append(parser->link_text, token->start, TOKEN_LEN(token));
1968 wiki_pop_excess_elements(parser);
1969 wiki_start_para_if_necessary(parser);
1970 token_str->ptr = token->start;
1971 token_str->len = TOKEN_LEN(token);
1972 wiki_append_hyperlink(parser, Qnil, token_str, NULL, parser->external_link_class, true);
1977 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
1978 str_append(parser->output, token->start, TOKEN_LEN(token));
1979 else if (IN(EXT_LINK_START))
1981 if (parser->link_target->len == 0)
1983 // this must be our link target: look ahead to make sure we see the space we're expecting to see
1984 token_str->ptr = token->start;
1985 token_str->len = TOKEN_LEN(token);
1987 if (token->type == SPACE)
1989 ary_push(parser->scope, PATH);
1990 ary_push(parser->scope, SPACE);
1991 str_append_str(parser->link_target, token_str);
1992 str_clear(parser->link_text);
1993 parser->capture = parser->link_text;
1994 token = NULL; // silently consume space
1998 // didn't see the space! this must be an error
1999 wiki_pop_from_stack(parser, NULL);
2000 wiki_pop_excess_elements(parser);
2001 wiki_start_para_if_necessary(parser);
2002 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2003 str_append_str(parser->output, token_str);
2007 str_append(parser->link_text, token->start, TOKEN_LEN(token));
2011 output = parser->capture ? parser->capture : parser->output;
2012 wiki_pop_excess_elements(parser);
2013 wiki_start_para_if_necessary(parser);
2014 str_append(output, token->start, TOKEN_LEN(token));
2018 // internal links (links to other wiki articles) look like this:
2019 // [[another article]] (would point at, for example, "/wiki/another_article")
2020 // [[the other article|the link text we'll use for it]]
2021 // [[the other article | the link text we'll use for it]]
2022 // MediaWiki has strict requirements about what it will accept as a link target:
2023 // all wikitext markup is disallowed:
2024 // example [[foo ''bar'' baz]]
2025 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2026 // example [[foo <em>bar</em> baz]]
2027 // renders [[foo <em>bar</em> baz]] (ie. not a link)
2028 // example [[foo <nowiki>''</nowiki> baz]]
2029 // renders [[foo '' baz]] (ie. not a link)
2030 // example [[foo <bar> baz]]
2031 // renders [[foo <bar> baz]] (ie. not a link)
2032 // HTML entities and non-ASCII, however, make it through:
2033 // example [[foo €]]
2034 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2035 // example [[foo €]]
2036 // renders <a href="/wiki/Foo_%E2%82%AC">foo €</a>
2037 // we'll impose similar restrictions here for the link target; allowed tokens will be:
2038 // SPACE, SPECIAL_URI_CHARS, PRINTABLE, PATH, ALNUM, DEFAULT, QUOT and AMP
2039 // everything else will be rejected
2041 output = parser->capture ? parser->capture : parser->output;
2042 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2044 wiki_emit_pending_crlf_if_necessary(parser);
2045 str_append(output, link_start, sizeof(link_start) - 1);
2047 else if (IN(EXT_LINK_START))
2048 // already in external link scope! (and in fact, must be capturing link_text right now)
2049 str_append(output, link_start, sizeof(link_start) - 1);
2050 else if (IN(LINK_START))
2052 // already in internal link scope! this is a syntax error
2053 wiki_rollback_failed_internal_link(parser);
2054 str_append(parser->output, link_start, sizeof(link_start) - 1);
2056 else if (IN(SEPARATOR))
2058 // scanning internal link text
2060 else // not in internal link scope yet
2062 // will either emit a link, or the rollback of a failed link, so start the para now
2063 wiki_pop_excess_elements(parser);
2064 wiki_start_para_if_necessary(parser);
2065 ary_push(parser->scope, LINK_START);
2067 // look ahead and try to gobble up link target
2068 while (NEXT_TOKEN(), (type = token->type))
2070 if (type == SPACE ||
2071 type == SPECIAL_URI_CHARS ||
2073 type == PRINTABLE ||
2077 type == QUOT_ENTITY ||
2079 type == AMP_ENTITY ||
2080 type == IMG_START ||
2082 type == LEFT_CURLY ||
2083 type == RIGHT_CURLY)
2085 // accumulate these tokens into link_target
2086 if (parser->link_target->len == 0)
2088 str_clear(parser->link_target);
2089 parser->capture = parser->link_target;
2091 if (type == QUOT_ENTITY)
2092 // don't insert the entity, insert the literal quote
2093 str_append(parser->link_target, quote, sizeof(quote) - 1);
2094 else if (type == AMP_ENTITY)
2095 // don't insert the entity, insert the literal ampersand
2096 str_append(parser->link_target, ampersand, sizeof(ampersand) - 1);
2098 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2100 else if (type == LINK_END)
2102 if (parser->link_target->len == 0) // bail for inputs like "[[]]"
2103 wiki_rollback_failed_internal_link(parser);
2104 break; // jump back to top of loop (will handle this in LINK_END case below)
2106 else if (type == SEPARATOR)
2108 if (parser->link_target->len == 0) // bail for inputs like "[[|"
2109 wiki_rollback_failed_internal_link(parser);
2112 ary_push(parser->scope, SEPARATOR);
2113 str_clear(parser->link_text);
2114 parser->capture = parser->link_text;
2119 else // unexpected token (syntax error)
2121 wiki_rollback_failed_internal_link(parser);
2122 break; // jump back to top of loop to handle unexpected token
2126 // jump to top of the loop to process token we scanned during lookahead (if any)
2132 output = parser->capture ? parser->capture : parser->output;
2133 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2135 wiki_emit_pending_crlf_if_necessary(parser);
2136 str_append(output, link_end, sizeof(link_end) - 1);
2138 else if (IN(EXT_LINK_START))
2139 // already in external link scope! (and in fact, must be capturing link_text right now)
2140 str_append(output, link_end, sizeof(link_end) - 1);
2141 else if (IN(LINK_START)) // in internal link scope!
2143 if (wiki_blank(parser->link_target))
2145 // special case for inputs like "[[ ]]"
2146 wiki_rollback_failed_internal_link(parser);
2147 str_append(parser->output, link_end, sizeof(link_end) - 1);
2150 if (parser->link_text->len == 0 ||
2151 wiki_blank(parser->link_text))
2153 // use link target as link text
2154 str_clear(parser->link_text);
2155 wiki_append_sanitized_link_target(parser, parser->link_text, true);
2158 wiki_trim_link_text(parser);
2160 // perform "redlink" check before manipulating link_target
2161 if (NIL_P(link_proc))
2165 j = rb_funcall(link_proc, rb_intern("call"), 1, string_from_str(parser->link_target));
2168 VALUE l = j; // can't cast inside StringValue macro
2172 wiki_encode_link_target(parser);
2173 wiki_pop_from_stack_up_to(parser, output, LINK_START, true);
2174 parser->capture = NULL;
2175 wiki_append_hyperlink(parser, prefix, parser->link_target, parser->link_text, j, false);
2176 str_clear(parser->link_target);
2177 str_clear(parser->link_text);
2179 else // wasn't in internal link scope
2181 wiki_pop_excess_elements(parser);
2182 wiki_start_para_if_necessary(parser);
2183 str_append(output, link_end, sizeof(link_end) - 1);
2187 // external links look like this:
2188 // [http://google.com/ the link text]
2189 // [/other/page/on/site see this page]
2190 // strings in square brackets which don't match this syntax get passed through literally; eg:
2191 // he was very angery [sic] about the turn of events
2192 case EXT_LINK_START:
2193 output = parser->capture ? parser->capture : parser->output;
2194 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2196 wiki_emit_pending_crlf_if_necessary(parser);
2197 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2199 else if (IN(EXT_LINK_START))
2200 // already in external link scope! (and in fact, must be capturing link_text right now)
2201 str_append(output, ext_link_start, sizeof(ext_link_start) - 1);
2202 else if (IN(LINK_START))
2204 // already in internal link scope!
2205 if (parser->link_target->len == 0 || !IN(SPACE))
2206 str_append(parser->link_target, ext_link_start, sizeof(ext_link_start) - 1);
2207 else // link target has already been scanned
2208 str_append(parser->link_text, ext_link_start, sizeof(ext_link_start) - 1);
2210 else // not in external link scope yet
2212 // will either emit a link, or the rollback of a failed link, so start the para now
2213 wiki_pop_excess_elements(parser);
2214 wiki_start_para_if_necessary(parser);
2216 // look ahead: expect an absolute URI (with protocol) or "relative" (path) URI
2218 if (token->type == URI || token->type == PATH)
2219 ary_push(parser->scope, EXT_LINK_START); // so far so good, jump back to the top of the loop
2221 // only get here if there was a syntax error (missing URI)
2222 str_append(parser->output, ext_link_start, sizeof(ext_link_start) - 1);
2223 continue; // jump back to top of loop to handle token (either URI or whatever it is)
2228 output = parser->capture ? parser->capture : parser->output;
2229 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2231 wiki_emit_pending_crlf_if_necessary(parser);
2232 str_append(output, ext_link_end, sizeof(ext_link_end) - 1);
2234 else if (IN(EXT_LINK_START))
2236 if (parser->link_text->len == 0)
2237 // syntax error: external link with no link text
2238 wiki_rollback_failed_external_link(parser);
2242 j = IN(PATH) ? Qnil : parser->external_link_class;
2243 wiki_pop_from_stack_up_to(parser, output, EXT_LINK_START, true);
2244 parser->capture = NULL;
2245 wiki_append_hyperlink(parser, Qnil, parser->link_target, parser->link_text, j, false);
2247 str_clear(parser->link_target);
2248 str_clear(parser->link_text);
2252 wiki_pop_excess_elements(parser);
2253 wiki_start_para_if_necessary(parser);
2254 str_append(parser->output, ext_link_end, sizeof(ext_link_end) - 1);
2259 output = parser->capture ? parser->capture : parser->output;
2260 wiki_pop_excess_elements(parser);
2261 wiki_start_para_if_necessary(parser);
2262 str_append(output, separator, sizeof(separator) - 1);
2266 output = parser->capture ? parser->capture : parser->output;
2267 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2269 wiki_emit_pending_crlf_if_necessary(parser);
2270 str_append(output, token->start, TOKEN_LEN(token));
2274 // peek ahead to see next token
2275 char *token_ptr = token->start;
2276 int token_len = TOKEN_LEN(token);
2279 if ((type == H6_END && IN(H6_START)) ||
2280 (type == H5_END && IN(H5_START)) ||
2281 (type == H4_END && IN(H4_START)) ||
2282 (type == H3_END && IN(H3_START)) ||
2283 (type == H2_END && IN(H2_START)) ||
2284 (type == H1_END && IN(H1_START)))
2286 // will suppress emission of space (discard) if next token is a H6_END, H5_END etc and we are in the corresponding scope
2291 wiki_pop_excess_elements(parser);
2292 wiki_start_para_if_necessary(parser);
2293 str_append(output, token_ptr, token_len);
2296 // jump to top of the loop to process token we scanned during lookahead
2304 case DECIMAL_ENTITY:
2305 // pass these through unaltered as they are case sensitive
2306 output = parser->capture ? parser->capture : parser->output;
2307 wiki_pop_excess_elements(parser);
2308 wiki_start_para_if_necessary(parser);
2309 str_append(output, token->start, TOKEN_LEN(token));
2313 // normalize hex entities (downcase them)
2314 output = parser->capture ? parser->capture : parser->output;
2315 wiki_pop_excess_elements(parser);
2316 wiki_start_para_if_necessary(parser);
2317 str_append(output, token->start, TOKEN_LEN(token));
2318 wiki_downcase_bang(output->ptr + output->len - TOKEN_LEN(token), TOKEN_LEN(token));
2322 output = parser->capture ? parser->capture : parser->output;
2323 wiki_pop_excess_elements(parser);
2324 wiki_start_para_if_necessary(parser);
2325 str_append(output, quot_entity, sizeof(quot_entity) - 1);
2329 output = parser->capture ? parser->capture : parser->output;
2330 wiki_pop_excess_elements(parser);
2331 wiki_start_para_if_necessary(parser);
2332 str_append(output, amp_entity, sizeof(amp_entity) - 1);
2336 output = parser->capture ? parser->capture : parser->output;
2337 wiki_pop_excess_elements(parser);
2338 wiki_start_para_if_necessary(parser);
2339 str_append(output, lt_entity, sizeof(lt_entity) - 1);
2343 output = parser->capture ? parser->capture : parser->output;
2344 wiki_pop_excess_elements(parser);
2345 wiki_start_para_if_necessary(parser);
2346 str_append(output, gt_entity, sizeof(gt_entity) - 1);
2350 if (IN_ANY_OF(NO_WIKI_START, PRE, PRE_START))
2352 wiki_emit_pending_crlf_if_necessary(parser);
2353 str_append(parser->output, token->start, TOKEN_LEN(token));
2355 else if (parser->capture)
2356 str_append(parser->capture, token->start, TOKEN_LEN(token));
2359 // not currently capturing: will be emitting something on success or failure, so get ready
2360 wiki_pop_excess_elements(parser);
2361 wiki_start_para_if_necessary(parser);
2363 // scan ahead consuming PATH, PRINTABLE, ALNUM and SPECIAL_URI_CHARS tokens
2364 // will cheat here and abuse the link_target capture buffer to accumulate text
2365 while (NEXT_TOKEN(), (type = token->type))
2367 if (type == PATH || type == PRINTABLE || type == ALNUM || type == SPECIAL_URI_CHARS)
2368 str_append(parser->link_target, token->start, TOKEN_LEN(token));
2369 else if (type == IMG_END && parser->link_target->len > 0)
2372 wiki_append_img(parser, parser->link_target->ptr, parser->link_target->len);
2376 else // unexpected token or zero-length target (syntax error)
2379 str_append(parser->output, literal_img_start, sizeof(literal_img_start) - 1);
2380 if (parser->link_target->len > 0)
2381 str_append(parser->output, parser->link_target->ptr, parser->link_target->len);
2386 // jump to top of the loop to process token we scanned during lookahead
2387 str_clear(parser->link_target);
2393 i = parser->pending_crlf;
2394 parser->pending_crlf = false;
2395 wiki_rollback_failed_link(parser); // if any
2396 if (IN_EITHER_OF(NO_WIKI_START, PRE_START))
2398 ary_clear(parser->line_buffer);
2399 str_append_str(parser->output, parser->line_ending);
2404 // beware when BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, that must be end of PRE block
2405 if (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE)
2406 // don't emit in this case
2407 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2410 if (ary_entry(parser->line_buffer, -2) == PRE)
2412 // only thing on line is the PRE: emit pending line ending (if we had one)
2414 str_append_str(parser->output, parser->line_ending);
2417 // clear these _before_ calling NEXT_TOKEN (NEXT_TOKEN adds to the line_buffer)
2418 ary_clear(parser->line);
2419 ary_clear(parser->line_buffer);
2421 // peek ahead to see if this is definitely the end of the PRE block
2424 if (type != BLOCKQUOTE && type != PRE)
2425 // this is definitely the end of the block, so don't emit
2426 wiki_pop_from_stack_up_to(parser, parser->output, PRE, true);
2428 // potentially will emit
2429 parser->pending_crlf = true;
2431 continue; // jump back to top of loop to handle token grabbed via lookahead
2436 parser->pending_crlf = true;
2438 // count number of BLOCKQUOTE tokens in line buffer (can be zero) and pop back to that level
2439 // as a side effect, this handles any open span-level elements and unclosed blocks
2440 // (with special handling for P blocks and LI elements)
2441 i = ary_count(parser->line, BLOCKQUOTE) + ary_count(parser->scope, BLOCKQUOTE_START);
2442 for (j = parser->scope->count; j > i; j--)
2444 if (parser->scope->count > 0 && ary_entry(parser->scope, -1) == LI)
2446 parser->pending_crlf = false;
2450 // special handling on last iteration through the loop if the top item on the scope is a P block
2451 if ((j - i == 1) && ary_entry(parser->scope, -1) == P)
2453 // if nothing or BLOCKQUOTE on line buffer (not line stack!) prior to CRLF, this must be a paragraph break
2454 // (note that we have to make sure we're not inside a BLOCKQUOTE_START block
2455 // because in those blocks BLOCKQUOTE tokens have no special meaning)
2456 if (NO_ITEM(ary_entry(parser->line_buffer, -2)) ||
2457 (ary_entry(parser->line_buffer, -2) == BLOCKQUOTE && !IN(BLOCKQUOTE_START)))
2459 parser->pending_crlf = false;
2461 // not a paragraph break!
2464 wiki_pop_from_stack(parser, NULL);
2468 // delete the entire contents of the line scope stack and buffer
2469 ary_clear(parser->line);
2470 ary_clear(parser->line_buffer);
2473 case SPECIAL_URI_CHARS:
2479 output = parser->capture ? parser->capture : parser->output;
2480 wiki_pop_excess_elements(parser);
2481 wiki_start_para_if_necessary(parser);
2482 str_append(output, token->start, TOKEN_LEN(token));
2486 output = parser->capture ? parser->capture : parser->output;
2487 wiki_pop_excess_elements(parser);
2488 wiki_start_para_if_necessary(parser);
2489 wiki_append_entity_from_utf32_char(output, token->code_point);
2493 // special case for input like " foo\n " (see pre_spec.rb)
2495 ary_entry(parser->line_buffer, -2) == PRE &&
2496 parser->pending_crlf)
2497 str_append(parser->output, parser->line_ending->ptr, parser->line_ending->len);
2499 // close any open scopes on hitting EOF
2500 wiki_rollback_failed_link(parser); // if any
2501 wiki_pop_all_from_stack(parser);
2502 goto return_output; // break not enough here (want to break out of outer while loop, not inner switch statement)
2508 // reset current token; forcing lexer to return another token at the top of the loop
2512 // nasty hack to avoid re-allocating our return value
2513 str_append(parser->output, null_str, 1); // null-terminate
2514 len = parser->output->len - 1; // don't count null termination
2516 #if defined(RUBY_1_9_x)
2517 VALUE out = rb_str_buf_new(RSTRING_EMBED_LEN_MAX + 1);
2518 free(RSTRING_PTR(out));
2519 RSTRING(out)->as.heap.aux.capa = len;
2520 RSTRING(out)->as.heap.ptr = parser->output->ptr;
2521 RSTRING(out)->as.heap.len = len;
2522 #elif defined(RUBY_1_8_x)
2523 VALUE out = rb_str_new2("");
2524 free(RSTRING_PTR(out));
2525 RSTRING(out)->len = len;
2526 RSTRING(out)->aux.capa = len;
2527 RSTRING(out)->ptr = parser->output->ptr;
2529 #error unsupported RUBY_VERSION
2531 parser->output->ptr = NULL; // don't double-free