1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
20 # Parse a markdown string and split it in blocks.
22 # Blocks are then outputed by an `MarkdownEmitter`.
26 # var proc = new MarkdownProcessor
27 # var html = proc.process("**Hello World!**")
28 # assert html == "<p><strong>Hello World!</strong></p>\n"
30 # SEE: `String::md_to_html` for a shortcut.
31 class MarkdownProcessor
33 # `MarkdownEmitter` used for ouput.
34 var emitter
: MarkdownEmitter is noinit
, protected writable
36 # Work in extended mode (default).
38 # Behavior changes when using extended mode:
40 # * Lists and code blocks end a paragraph
42 # In normal markdown the following:
46 # * and this is not a list
52 # <p>This is a paragraph
53 # * and this is not a list</p>
56 # When using extended mode this changes to:
59 # <p>This is a paragraph</p>
61 # <li>and this is not a list</li>
65 # * Fences code blocks
67 # If you don't want to indent your all your code with 4 spaces,
68 # you can wrap your code in ``` ``` ``` or `~~~`.
74 # print "Hello World!"
80 # If you want to use syntax highlighting tools, most of them need to know what kind
81 # of language they are highlighting.
82 # You can add an optional language identifier after the fence declaration to output
83 # it in the HTML render.
88 # print "# Hello World!".md_to_html
94 # <pre class="nit"><code>import markdown
96 # print "Hello World!".md_to_html
100 # * Underscores (Emphasis)
102 # Underscores in the middle of a word like:
108 # normally produces this:
111 # <p>Con<em>cat</em>this</p>
114 # With extended mode they don't result in emphasis.
117 # <p>Con_cat_this</p>
122 # Like in [GFM](https://help.github.com/articles/github-flavored-markdown),
123 # strikethrought span is marked with `~~`.
132 # <del>Mistaken text.</del>
136 # Disable attaching MDLocation to Tokens
138 # Locations are useful for some tools but they may
139 # cause an important time and space overhead.
142 var no_location
= false is writable
144 init do self.emitter
= new MarkdownEmitter(self)
146 # Process the mardown `input` string and return the processed output.
147 fun process
(input
: String): Writable do
154 var parent
= read_lines
(input
)
155 parent
.remove_surrounding_empty_lines
156 recurse
(parent
, false)
157 # output processed text
158 return emitter
.emit
(parent
.kind
)
161 # Split `input` string into `MDLines` and create a parent `MDBlock` with it.
162 private fun read_lines
(input
: String): MDBlock do
163 var block
= new MDBlock(new MDLocation(1, 1, 1, 1))
164 var value
= new FlatBuffer
170 while i
< input
.length
do
174 while not eol
and i
< input
.length
do
179 else if c
== '\r' then
180 else if c
== '\t' then
181 var np
= pos
+ (4 - (pos
& 3))
194 var loc
= new MDLocation(line_pos
, 1, line_pos
, col_pos
)
195 var line
= new MDLine(loc
, value
.write_to_string
)
196 var is_link_ref
= check_link_ref
(line
)
198 if not is_link_ref
then block
.add_line line
204 # Check if line is a block link definition.
205 # Return `true` if line contains a valid link ref and save it into `link_refs`.
206 private fun check_link_ref
(line
: MDLine): Bool do
208 var is_link_ref
= false
209 var id
= new FlatBuffer
210 var link
= new FlatBuffer
211 var comment
= new FlatBuffer
213 if not line
.is_empty
and line
.leading
< 4 and line
.value
[line
.leading
] == '[' then
214 pos
= line
.leading
+ 1
215 pos
= md
.read_until
(id
, pos
, ']')
216 if not id
.is_empty
and pos
>= 0 and pos
+ 2 < line
.value
.length
then
217 if line
.value
[pos
+ 1] == ':' then
219 pos
= md
.skip_spaces
(pos
)
220 if pos
>= 0 and line
.value
[pos
] == '<' then
222 pos
= md
.read_until
(link
, pos
, '>')
224 else if pos
>= 0 then
225 pos
= md
.read_until
(link
, pos
, ' ', '\n')
227 if not link
.is_empty
then
228 pos
= md
.skip_spaces
(pos
)
229 if pos
> 0 and pos
< line
.value
.length
then
230 var c
= line
.value
[pos
]
231 if c
== '\"' or c
== '\'' or c == '(' then
234 pos = md.read_until(comment, pos, ')')
236 pos = md.read_until(comment, pos, c)
238 if pos > 0 then is_link_ref = true
247 if is_link_ref and not id.is_empty and not link.is_empty then
248 var lr = new LinkRef.with_title(link.write_to_string, comment.write_to_string)
249 add_link_ref(id.write_to_string, lr)
250 if comment.is_empty then last_link_ref = lr
253 comment = new FlatBuffer
254 if not line.is_empty and last_link_ref != null then
256 var c = line.value[pos]
257 if c == '\
"' or c == '\'' or c == '(' then
260 pos = md.read_until(comment, pos, ')')
262 pos = md.read_until(comment, pos, c)
265 var last_link_ref = self.last_link_ref
266 if not comment.is_empty and last_link_ref != null then
267 last_link_ref.title = comment.write_to_string
270 if comment.is_empty then return false
276 # This list will be needed during output to expand links.
277 var link_refs: Map[String, LinkRef] = new HashMap[String, LinkRef]
279 # Last encountered link ref (for multiline definitions)
281 # Markdown allows link refs to be defined over two lines:
284 # [id]: http://example.com/longish/path/to/resource/here
285 # "Optional Title Here"
288 private var last_link_ref: nullable LinkRef = null
290 # Add a link ref to the list
291 fun add_link_ref(key: String, ref: LinkRef) do link_refs[key.to_lower] = ref
293 # Recursively split a `block`.
295 # The block is splitted according to the type of lines it contains.
296 # Some blocks can be splited again recursively like lists.
297 # The `in_list` mode is used to recurse on list and build
298 # nested paragraphs or code blocks.
299 fun recurse(root: MDBlock, in_list: Bool) do
300 var old_mode = self.in_list
301 var old_root = self.current_block
302 self.in_list = in_list
304 var line = root.first_line
305 while line != null and line.is_empty do
307 if line == null then return
312 while current_line != null do
313 line_kind(current_line.as(not null)).process(self)
315 self.in_list = old_mode
316 self.current_block = old_root
319 # Currently processed line.
320 # Used when visiting blocks with `recurse`.
321 var current_line: nullable MDLine = null is writable
323 # Currently processed block.
324 # Used when visiting blocks with `recurse`.
325 var current_block: nullable MDBlock = null is writable
327 # Is the current recursion in list mode?
328 # Used when visiting blocks with `recurse`
329 private var in_list = false
333 fun line_kind(md: MDLine): Line do
335 var leading = md.leading
336 var trailing = md.trailing
337 if md.is_empty then return new LineEmpty
338 if md.leading > 3 then return new LineCode
339 if value[leading] == '#' then return new LineHeadline
340 if value[leading] == '>' then return new LineBlockquote
343 if value.length - leading - trailing > 2 then
344 if value[leading] == '`' and md.count_chars_start('`') >= 3 then
347 if value[leading] == '~' and md.count_chars_start('~') >= 3 then
353 if value.length - leading - trailing > 2 and
354 (value[leading] == '*' or value[leading] == '-' or value[leading] == '_') then
355 if md.count_chars(value[leading]) >= 3 then
360 if value.length - leading >= 2 and value[leading + 1] == ' ' then
361 var c = value[leading]
362 if c == '*' or c == '-' or c == '+' then return new LineUList
365 if value.length - leading >= 3 and value[leading].is_digit then
367 while i < value.length and value[i].is_digit do i += 1
368 if i + 1 < value.length and value[i] == '.' and value[i + 1] == ' ' then
373 if value[leading] == '<' and md.check_html then return new LineXML
376 if next != null and not next.is_empty then
377 if next.count_chars('=') > 0 then
378 return new LineHeadline1
380 if next.count_chars('-') > 0 then
381 return new LineHeadline2
387 # Get the token kind at `pos`.
388 fun token_at(text: Text, pos: Int): Token do
400 if pos + 1 < text.length then
405 if pos + 2 < text.length then
415 loc = new MDLocation(
416 current_loc.line_start,
417 current_loc.column_start + pos,
418 current_loc.line_start,
419 current_loc.column_start + pos)
424 if c0 != ' ' or c2 != ' ' then
425 return new TokenStrongStar(loc, pos, c)
427 return new TokenEmStar(loc, pos, c)
430 if c0 != ' ' or c1 != ' ' then
431 return new TokenEmStar(loc, pos, c)
433 return new TokenNone(loc, pos, c)
435 else if c == '_' then
437 if c0 != ' ' or c2 != ' ' then
438 return new TokenStrongUnderscore(loc, pos, c)
440 return new TokenEmUnderscore(loc, pos, c)
444 if (c0.is_letter or c0.is_digit) and c0 != '_' and
445 (c1.is_letter or c1.is_digit) then
446 return new TokenNone(loc, pos, c)
448 return new TokenEmUnderscore(loc, pos, c)
451 if c0 != ' ' or c1 != ' ' then
452 return new TokenEmUnderscore(loc, pos, c)
454 return new TokenNone(loc, pos, c)
456 else if c == '!' then
457 if c1 == '[' then return new TokenImage(loc, pos, c)
458 return new TokenNone(loc, pos, c)
459 else if c == '[' then
460 return new TokenLink(loc, pos, c)
461 else if c == ']' then
462 return new TokenNone(loc, pos, c)
463 else if c == '`' then
465 return new TokenCodeDouble(loc, pos, c)
467 return new TokenCodeSingle(loc, pos, c)
469 else if c == '\\' then
470 if c1 == '\\' or c1 == '[' or c1 == ']' or c1 == '(' or c1 == ')' or c1 == '{' or c1 == '}' or c1 == '#' or c1 == '"' or c1 == '\
'' or c1
== '.' or c1
== '<' or c1
== '>' or c1
== '*' or c1
== '+' or c1
== '-' or c1
== '_' or c1
== '!' or c1
== '`' or c1
== '~' or c1
== '^' then
471 return new TokenEscape(loc
, pos
, c
)
473 return new TokenNone(loc
, pos
, c
)
475 else if c
== '<' then
476 return new TokenHTML(loc
, pos
, c
)
477 else if c
== '&' then
478 return new TokenEntity(loc
, pos
, c
)
481 if c
== '~' and c1
== '~' then
482 return new TokenStrike(loc
, pos
, c
)
485 return new TokenNone(loc
, pos
, c
)
489 # Find the position of a `token` in `self`.
490 fun find_token
(text
: Text, start
: Int, token
: Token): Int do
492 while pos
< text
.length
do
493 if token_at
(text
, pos
).is_same_type
(token
) then
501 # Location used for next parsed token.
503 # This location can be changed by the emitter to adjust with `\n` found
505 private fun current_loc
: MDLocation do return emitter
.current_loc
508 # Emit output corresponding to blocks content.
510 # Blocks are created by a previous pass in `MarkdownProcessor`.
511 # The emitter use a `Decorator` to select the output format.
512 class MarkdownEmitter
514 # Kind of processor used for parsing.
515 type PROCESSOR: MarkdownProcessor
517 # Processor containing link refs.
518 var processor
: PROCESSOR
520 # Kind of decorator used for decoration.
521 type DECORATOR: Decorator
523 # Decorator used for output.
524 # Default is `HTMLDecorator`
525 var decorator
: DECORATOR is writable, lazy
do
526 return new HTMLDecorator
529 # Create a new `MarkdownEmitter` using a custom `decorator`.
530 init with_decorator
(processor
: PROCESSOR, decorator
: DECORATOR) do
532 self.decorator
= decorator
535 # Output `block` using `decorator` in the current buffer.
536 fun emit
(block
: Block): Text do
537 var buffer
= push_buffer
543 # Output the content of `block`.
544 fun emit_in
(block
: Block) do block
.emit_in
(self)
546 # Transform and emit mardown text
547 fun emit_text
(text
: Text) do emit_text_until
(text
, 0, null)
549 # Transform and emit mardown text starting at `start` and
550 # until a token with the same type as `token` is found.
551 # Go until the end of `text` if `token` is null.
552 fun emit_text_until
(text
: Text, start
: Int, token
: nullable Token): Int do
553 var old_text
= current_text
554 var old_pos
= current_pos
557 while current_pos
< text
.length
do
558 if text
[current_pos
] == '\n' then
559 current_loc
.line_start
+= 1
560 current_loc
.column_start
= -current_pos
562 var mt
= processor
.token_at
(text
, current_pos
)
563 if (token
!= null and not token
isa TokenNone) and
564 (mt
.is_same_type
(token
) or
565 (token
isa TokenEmStar and mt
isa TokenStrongStar) or
566 (token
isa TokenEmUnderscore and mt
isa TokenStrongUnderscore)) then
572 current_text
= old_text
573 current_pos
= old_pos
577 # Currently processed position in `current_text`.
578 # Used when visiting inline production with `emit_text_until`.
579 private var current_pos
: Int = -1
581 # Currently processed text.
582 # Used when visiting inline production with `emit_text_until`.
583 private var current_text
: nullable Text = null
586 private var buffer_stack
= new List[FlatBuffer]
588 # Push a new buffer on the stack.
589 private fun push_buffer
: FlatBuffer do
590 var buffer
= new FlatBuffer
591 buffer_stack
.add buffer
595 # Pop the last buffer.
596 private fun pop_buffer
do buffer_stack
.pop
598 # Current output buffer.
599 private fun current_buffer
: FlatBuffer do
600 assert not buffer_stack
.is_empty
601 return buffer_stack
.last
605 private var loc_stack
= new List[MDLocation]
607 # Push a new MDLocation on the stack.
608 private fun push_loc
(location
: MDLocation) do loc_stack
.add location
610 # Pop the last buffer.
611 private fun pop_loc
: MDLocation do return loc_stack
.pop
613 # Current output buffer.
614 private fun current_loc
: MDLocation do
615 assert not loc_stack
.is_empty
616 return loc_stack
.last
619 # Append `e` to current buffer.
620 fun add
(e
: Writable) do
622 current_buffer
.append e
624 current_buffer
.append e
.write_to_string
628 # Append `c` to current buffer.
633 # Append a "\n" line break.
634 fun addn
do addc
'\n'
638 # Links that are specified somewhere in the mardown document to be reused as shortcuts.
641 # [1]: http://example.com/ "Optional title"
648 # Optional link title
649 var title
: nullable String = null
651 # Is the link an abreviation?
652 var is_abbrev
= false
654 # Create a link with a title.
655 init with_title
(link
: String, title
: nullable String) do
661 # A `Decorator` is used to emit mardown into a specific format.
662 # Default decorator used is `HTMLDecorator`.
665 # Kind of emitter used for decoration.
666 type EMITTER: MarkdownEmitter
668 # Render a single plain char.
670 # Redefine this method to add special escaping for plain text.
671 fun add_char
(v
: EMITTER, c
: Char) do v
.addc c
673 # Render a ruler block.
674 fun add_ruler
(v
: EMITTER, block
: BlockRuler) is abstract
676 # Render a headline block with corresponding level.
677 fun add_headline
(v
: EMITTER, block
: BlockHeadline) is abstract
679 # Render a paragraph block.
680 fun add_paragraph
(v
: EMITTER, block
: BlockParagraph) is abstract
682 # Render a code or fence block.
683 fun add_code
(v
: EMITTER, block
: BlockCode) is abstract
685 # Render a blockquote.
686 fun add_blockquote
(v
: EMITTER, block
: BlockQuote) is abstract
688 # Render an unordered list.
689 fun add_unorderedlist
(v
: EMITTER, block
: BlockUnorderedList) is abstract
691 # Render an ordered list.
692 fun add_orderedlist
(v
: EMITTER, block
: BlockOrderedList) is abstract
694 # Render a list item.
695 fun add_listitem
(v
: EMITTER, block
: BlockListItem) is abstract
697 # Render an emphasis text.
698 fun add_em
(v
: EMITTER, text
: Text) is abstract
700 # Render a strong text.
701 fun add_strong
(v
: EMITTER, text
: Text) is abstract
703 # Render a strike text.
705 # Extended mode only (see `MarkdownProcessor::ext_mode`)
706 fun add_strike
(v
: EMITTER, text
: Text) is abstract
709 fun add_link
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
712 fun add_image
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
714 # Render an abbreviation.
715 fun add_abbr
(v
: EMITTER, name
: Text, comment
: Text) is abstract
717 # Render a code span reading from a buffer.
718 fun add_span_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
720 # Render a text and escape it.
721 fun append_value
(v
: EMITTER, value
: Text) is abstract
723 # Render code text from buffer and escape it.
724 fun append_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
726 # Render a character escape.
727 fun escape_char
(v
: EMITTER, char
: Char) is abstract
729 # Render a line break
730 fun add_line_break
(v
: EMITTER) is abstract
732 # Generate a new html valid id from a `String`.
733 fun strip_id
(txt
: String): String is abstract
735 # Found headlines during the processing labeled by their ids.
736 fun headlines
: ArrayMap[String, HeadLine] is abstract
739 # Class representing a markdown headline.
741 # Unique identifier of this headline.
744 # Text of the headline.
747 # Level of this headline.
749 # According toe the markdown specification, level must be in `[1..6]`.
753 # `Decorator` that outputs HTML.
757 redef var headlines
= new ArrayMap[String, HeadLine]
759 redef fun add_ruler
(v
, block
) do v
.add
"<hr/>\n"
761 redef fun add_headline
(v
, block
) do
763 var line
= block
.block
.first_line
764 if line
== null then return
766 var id
= strip_id
(txt
)
767 var lvl
= block
.depth
768 headlines
[id
] = new HeadLine(id
, txt
, lvl
)
770 v
.add
"<h{lvl} id=\"{id}\
">"
775 redef fun add_paragraph
(v
, block
) do
781 redef fun add_code
(v
, block
) do
782 var meta
= block
.meta
784 v
.add
"<pre class=\""
785 append_value(v, meta)
791 v
.add
"</code></pre>\n"
794 redef fun add_blockquote
(v
, block
) do
795 v
.add
"<blockquote>\n"
797 v
.add
"</blockquote>\n"
800 redef fun add_unorderedlist
(v
, block
) do
806 redef fun add_orderedlist
(v
, block
) do
812 redef fun add_listitem
(v
, block
) do
818 redef fun add_em
(v
, text
) do
824 redef fun add_strong
(v
, text
) do
830 redef fun add_strike
(v
, text
) do
836 redef fun add_image
(v
, link
, name
, comment
) do
838 append_value(v, link)
840 append_value(v, name)
842 if comment
!= null and not comment
.is_empty
then
844 append_value(v, comment)
850 redef fun add_link
(v
, link
, name
, comment
) do
852 append_value(v, link)
854 if comment
!= null and not comment
.is_empty
then
856 append_value(v, comment)
864 redef fun add_abbr
(v
, name
, comment
) do
865 v
.add
"<abbr title=\""
866 append_value(v, comment)
872 redef fun add_span_code
(v
, text
, from
, to
) do
874 append_code
(v
, text
, from
, to
)
878 redef fun add_line_break
(v
) do
882 redef fun append_value
(v
, text
) do for c
in text
do escape_char
(v
, c
)
884 redef fun escape_char
(v
, c
) do
887 else if c
== '<' then
889 else if c
== '>' then
891 else if c
== '"' then
893 else if c
== '\'' then
900 redef fun append_code(v, buffer, from, to) do
901 for i in [from..to[ do
905 else if c == '<' then
907 else if c == '>' then
915 redef fun strip_id(txt) do
917 var b = new FlatBuffer
922 if not c.is_letter and
924 not allowed_id_chars.has(c) then continue
930 # check for multiple id definitions
931 if headlines.has_key(key) then
934 while headlines.has_key(key) do
942 private var allowed_id_chars: Array[Char] = ['-', '_
', ':', '.']
945 # Location in a Markdown input.
948 # Starting line number (starting from 1).
951 # Starting column number (starting from 1).
952 var column_start: Int
954 # Stopping line number (starting from 1).
957 # Stopping column number (starting from 1).
960 redef fun to_s do return "{line_start},{column_start}--{line_end},{column_end}"
962 # Return a copy of `self`.
963 fun copy: MDLocation do
964 return new MDLocation(line_start, column_start, line_end, column_end)
968 # A block of markdown lines.
969 # A `MDBlock` can contains lines and/or sub-blocks.
972 # Position of `self` in the input.
973 var location: MDLocation
977 var kind: Block = new BlockNone(self) is writable
980 var first_line: nullable MDLine = null is writable
983 var last_line: nullable MDLine = null is writable
985 # First sub-block if any.
986 var first_block: nullable MDBlock = null is writable
988 # Last sub-block if any.
989 var last_block: nullable MDBlock = null is writable
991 # Previous block if any.
992 var prev: nullable MDBlock = null is writable
995 var next: nullable MDBlock = null is writable
997 # Does this block contain subblocks?
998 fun has_blocks: Bool do return first_block != null
1001 fun count_blocks: Int do
1003 var block = first_block
1004 while block != null do
1011 # Does this block contain lines?
1012 fun has_lines: Bool do return first_line != null
1014 # Count block lines.
1015 fun count_lines: Int do
1017 var line = first_line
1018 while line != null do
1025 # Split `self` creating a new sub-block having `line` has `last_line`.
1026 fun split(line: MDLine): MDBlock do
1027 # location for new block
1028 var new_loc = new MDLocation(
1029 first_line.as(not null).location.line_start,
1030 first_line.as(not null).location.column_start,
1031 line.location.line_end,
1032 line.location.column_end)
1034 var block = new MDBlock(new_loc)
1035 block.first_line = first_line
1036 block.last_line = line
1037 first_line = line.next
1039 if first_line == null then
1042 first_line.as(not null).prev = null
1043 # update current block loc
1044 location.line_start = first_line.as(not null).location.line_start
1045 location.column_start = first_line.as(not null).location.column_start
1047 if first_block == null then
1051 last_block.as(not null).next = block
1057 # Add a `line` to this block.
1058 fun add_line(line: MDLine) do
1059 if last_line == null then
1063 last_line.as(not null).next_empty = line.is_empty
1064 line.prev_empty = last_line.as(not null).is_empty
1065 line.prev = last_line
1066 last_line.as(not null).next = line
1071 # Remove `line` from this block.
1072 fun remove_line(line: MDLine) do
1073 if line.prev == null then
1074 first_line = line.next
1076 line.prev.as(not null).next = line.next
1078 if line.next == null then
1079 last_line = line.prev
1081 line.next.as(not null).prev = line.prev
1087 # Remove leading empty lines.
1088 fun remove_leading_empty_lines: Bool do
1089 var was_empty = false
1090 var line = first_line
1091 while line != null and line.is_empty do
1099 # Remove trailing empty lines.
1100 fun remove_trailing_empty_lines: Bool do
1101 var was_empty = false
1102 var line = last_line
1103 while line != null and line.is_empty do
1111 # Remove leading and trailing empty lines.
1112 fun remove_surrounding_empty_lines: Bool do
1113 var was_empty = false
1114 if remove_leading_empty_lines then was_empty = true
1115 if remove_trailing_empty_lines then was_empty = true
1119 # Remove list markers and up to 4 leading spaces.
1120 # Used to clean nested lists.
1121 fun remove_list_indent(v: MarkdownProcessor) do
1122 var line = first_line
1123 while line != null do
1124 if not line.is_empty then
1125 var kind = v.line_kind(line)
1126 if kind isa LineList then
1127 line.value = kind.extract_value(line)
1129 line.value = line.value.substring_from(line.leading.min(4))
1131 line.leading = line.process_leading
1137 # Collect block line text.
1139 var text = new FlatBuffer
1140 var line = first_line
1141 while line != null do
1142 if not line.is_empty then
1143 text.append line.text
1148 return text.write_to_string
1152 # Representation of a markdown block in the AST.
1153 # Each `Block` is linked to a `MDBlock` that contains mardown code.
1154 abstract class Block
1156 # The markdown block `self` is related to.
1159 # Output `self` using `v.decorator`.
1160 fun emit(v: MarkdownEmitter) do v.emit_in(self)
1162 # Emit the containts of `self`, lines or blocks.
1163 fun emit_in(v: MarkdownEmitter) do
1164 block.remove_surrounding_empty_lines
1165 if block.has_lines then
1172 # Emit lines contained in `block`.
1173 fun emit_lines(v: MarkdownEmitter) do
1174 var tpl = v.push_buffer
1175 var line = block.first_line
1176 while line != null do
1177 if not line.is_empty then
1178 v.add line.value.substring(line.leading, line.value.length - line.trailing)
1179 if line.trailing >= 2 then v.decorator.add_line_break(v)
1181 if line.next != null then
1190 # Emit sub-blocks contained in `block`.
1191 fun emit_blocks(v: MarkdownEmitter) do
1192 var block = self.block.first_block
1193 while block != null do
1194 v.push_loc(block.location)
1201 # The raw content of the block as a multi-line string.
1202 fun raw_content: String do
1203 var infence = self isa BlockFence
1204 var text = new FlatBuffer
1205 var line = self.block.first_line
1206 while line != null do
1207 if not line.is_empty then
1208 var str = line.value
1209 if not infence and str.has_prefix(" ") then
1210 text.append str.substring(4, str.length - line.trailing)
1218 return text.write_to_string
1222 # A block without any markdown specificities.
1224 # Actually use the same implementation than `BlockCode`,
1225 # this class is only used for typing purposes.
1230 # A markdown blockquote.
1234 redef fun emit(v) do v.decorator.add_blockquote(v, self)
1236 # Remove blockquote markers.
1237 private fun remove_block_quote_prefix(block: MDBlock) do
1238 var line = block.first_line
1239 while line != null do
1240 if not line.is_empty then
1241 if line.value[line.leading] == '>' then
1242 var rem = line.leading + 1
1243 if line.leading + 1 < line.value.length and
1244 line.value[line.leading + 1] == ' ' then
1247 line.value = line.value.substring_from(rem)
1248 line.leading = line.process_leading
1256 # A markdown code block.
1260 # Any string found after fence token.
1261 var meta: nullable Text
1263 # Number of char to skip at the beginning of the line.
1265 # Block code lines start at 4 spaces.
1266 protected var line_start = 4
1268 redef fun emit(v) do v.decorator.add_code(v, self)
1270 redef fun emit_lines(v) do
1271 var line = block.first_line
1272 while line != null do
1273 if not line.is_empty then
1274 v.decorator.append_code(v, line.value, line_start, line.value.length)
1282 # A markdown code-fence block.
1284 # Actually use the same implementation than `BlockCode`,
1285 # this class is only used for typing purposes.
1289 # Fence code lines start at 0 spaces.
1290 redef var line_start = 0
1293 # A markdown headline.
1297 redef fun emit(v) do
1298 var loc = block.location.copy
1299 loc.column_start += start
1301 v.decorator.add_headline(v, self)
1305 private var start = 0
1307 # Depth of the headline used to determine the headline level.
1310 # Remove healine marks from lines contained in `self`.
1311 private fun transform_headline(block: MDBlock) do
1312 if depth > 0 then return
1314 var line = block.first_line
1315 if line == null then return
1316 if line.is_empty then return
1317 var start = line.leading
1318 while start < line.value.length and line.value[start] == '#' do
1322 while start
< line
.value
.length
and line
.value
[start
] == ' ' do
1325 if start
>= line
.value
.length
then
1326 line
.is_empty
= true
1328 var nend
= line
.value
.length
- line
.trailing
- 1
1329 while line
.value
[nend
] == '#' do nend
-= 1
1330 while line
.value
[nend
] == ' ' do nend
-= 1
1331 line
.value
= line
.value
.substring
(start
, nend
- start
+ 1)
1336 depth
= level
.min
(6)
1340 # A markdown list item block.
1344 redef fun emit
(v
) do v
.decorator
.add_listitem
(v
, self)
1347 # A markdown list block.
1348 # Can be either an ordered or unordered list, this class is mainly used to factorize code.
1349 abstract class BlockList
1352 # Split list block into list items sub-blocks.
1353 private fun init_block
(v
: MarkdownProcessor) do
1354 var line
= block
.first_line
1355 if line
== null then return
1357 while line
!= null do
1358 var t
= v
.line_kind
(line
)
1359 if t
isa LineList or
1360 (not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1361 not (t
isa LineList))) then
1362 var sblock
= block
.split
(line
.prev
.as(not null))
1363 sblock
.kind
= new BlockListItem(sblock
)
1367 var sblock
= block
.split
(block
.last_line
.as(not null))
1368 sblock
.kind
= new BlockListItem(sblock
)
1371 # Expand list items as paragraphs if needed.
1372 private fun expand_paragraphs
(block
: MDBlock) do
1373 var outer
= block
.first_block
1374 var inner
: nullable MDBlock
1375 var has_paragraph
= false
1376 while outer
!= null and not has_paragraph
do
1377 if outer
.kind
isa BlockListItem then
1378 inner
= outer
.first_block
1379 while inner
!= null and not has_paragraph
do
1380 if inner
.kind
isa BlockParagraph then
1381 has_paragraph
= true
1388 if has_paragraph
then
1389 outer
= block
.first_block
1390 while outer
!= null do
1391 if outer
.kind
isa BlockListItem then
1392 inner
= outer
.first_block
1393 while inner
!= null do
1394 if inner
.kind
isa BlockNone then
1395 inner
.kind
= new BlockParagraph(inner
)
1406 # A markdown ordered list.
1407 class BlockOrderedList
1410 redef fun emit
(v
) do v
.decorator
.add_orderedlist
(v
, self)
1413 # A markdown unordred list.
1414 class BlockUnorderedList
1417 redef fun emit
(v
) do v
.decorator
.add_unorderedlist
(v
, self)
1420 # A markdown paragraph block.
1421 class BlockParagraph
1424 redef fun emit
(v
) do v
.decorator
.add_paragraph
(v
, self)
1431 redef fun emit
(v
) do v
.decorator
.add_ruler
(v
, self)
1434 # Xml blocks that can be found in markdown markup.
1438 redef fun emit_lines
(v
) do
1439 var line
= block
.first_line
1440 while line
!= null do
1441 if not line
.is_empty
then v
.add line
.value
1451 # Location of `self` in the original input.
1452 var location
: MDLocation
1454 # Text contained in this line.
1455 var value
: String is writable
1457 # Is this line empty?
1458 # Lines containing only spaces are considered empty.
1459 var is_empty
: Bool = true is writable
1461 # Previous line in `MDBlock` or null if first line.
1462 var prev
: nullable MDLine = null is writable
1464 # Next line in `MDBlock` or null if last line.
1465 var next
: nullable MDLine = null is writable
1467 # Is the previous line empty?
1468 var prev_empty
: Bool = false is writable
1470 # Is the next line empty?
1471 var next_empty
: Bool = false is writable
1473 # Initialize a new MDLine from its string value
1475 self.leading
= process_leading
1476 if leading
!= value
.length
then
1477 self.is_empty
= false
1478 self.trailing
= process_trailing
1482 # Set `value` as an empty String and update `leading`, `trailing` and is_`empty`.
1488 if prev
!= null then prev
.as(not null).next_empty
= true
1489 if next
!= null then next
.as(not null).prev_empty
= true
1492 # Number or leading spaces on this line.
1493 var leading
: Int = 0 is writable
1495 # Compute `leading` depending on `value`.
1496 fun process_leading
: Int do
1498 var value
= self.value
1499 while count
< value
.length
and value
[count
] == ' ' do count
+= 1
1500 if leading
== value
.length
then clear
1504 # Number of trailing spaces on this line.
1505 var trailing
: Int = 0 is writable
1507 # Compute `trailing` depending on `value`.
1508 fun process_trailing
: Int do
1510 var value
= self.value
1511 while value
[value
.length
- count
- 1] == ' ' do
1517 # Count the amount of `ch` in this line.
1518 # Return A value > 0 if this line only consists of `ch` end spaces.
1519 fun count_chars
(ch
: Char): Int do
1535 # Count the amount of `ch` at the start of this line ignoring spaces.
1536 fun count_chars_start
(ch
: Char): Int do
1551 # Last XML line if any.
1552 private var xml_end_line
: nullable MDLine = null
1554 # Does `value` contains valid XML markup?
1555 private fun check_html
: Bool do
1556 var tags
= new Array[String]
1557 var tmp
= new FlatBuffer
1559 if pos
+ 1 < value
.length
and value
[pos
+ 1] == '!' then
1560 if read_xml_comment
(self, pos
) > 0 then return true
1562 pos
= value
.read_xml
(tmp
, pos
, false)
1566 if not tag
.is_html_block
then
1574 var line
: nullable MDLine = self
1575 while line
!= null do
1576 while pos
< line
.value
.length
and line
.value
[pos
] != '<' do
1579 if pos
>= line
.value
.length
then
1580 if pos
- 2 >= 0 and line
.value
[pos
- 2] == '/' then
1582 if tags
.is_empty
then
1590 tmp
= new FlatBuffer
1591 var new_pos
= line
.value
.read_xml
(tmp
, pos
, false)
1594 if tag
.is_html_block
and not tag
== "hr" then
1595 if tmp
[1] == '/' then
1596 if tags
.last
!= tag
then
1604 if tags
.is_empty
then
1614 return tags
.is_empty
1619 # Read a XML comment.
1620 # Used by `check_html`.
1621 private fun read_xml_comment
(first_line
: MDLine, start
: Int): Int do
1622 var line
: nullable MDLine = first_line
1623 if start
+ 3 < line
.as(not null).value
.length
then
1624 if line
.as(not null).value
[2] == '-' and line
.as(not null).value
[3] == '-' then
1626 while line
!= null do
1627 while pos
< line
.value
.length
and line
.value
[pos
] != '-' do
1630 if pos
== line
.value
.length
then
1634 if pos
+ 2 < line
.value
.length
then
1635 if line
.value
[pos
+ 1] == '-' and line
.value
[pos
+ 2] == '>' then
1636 first_line
.xml_end_line
= line
1648 # Extract the text of `self` without leading and trailing.
1649 fun text
: String do return value
.substring
(leading
, value
.length
- trailing
)
1656 # See `MarkdownProcessor::recurse`.
1657 fun process
(v
: MarkdownProcessor) is abstract
1660 # An empty markdown line.
1664 redef fun process
(v
) do
1665 v
.current_line
= v
.current_line
.as(not null).next
1669 # A non-specific markdown construction.
1670 # Mainly used as part of another line construct such as paragraphs or lists.
1674 redef fun process
(v
) do
1675 var line
= v
.current_line
1677 var was_empty
= line
.as(not null).prev_empty
1678 while line
!= null and not line
.is_empty
do
1679 var t
= v
.line_kind
(line
)
1680 if (v
.in_list
or v
.ext_mode
) and t
isa LineList then
1683 if v
.ext_mode
and (t
isa LineCode or t
isa LineFence) then
1686 if t
isa LineHeadline or t
isa LineHeadline1 or t
isa LineHeadline2 or
1687 t
isa LineHR or t
isa LineBlockquote or t
isa LineXML then
1693 var current_block
= v
.current_block
.as(not null)
1694 if line
!= null and not line
.is_empty
then
1695 var block
= current_block
.split
(line
.prev
.as(not null))
1696 if v
.in_list
and not was_empty
then
1697 block
.kind
= new BlockNone(block
)
1699 block
.kind
= new BlockParagraph(block
)
1701 current_block
.remove_leading_empty_lines
1704 if line
!= null then
1705 block
= current_block
.split
(line
)
1707 block
= current_block
.split
(current_block
.last_line
.as(not null))
1709 if v
.in_list
and (line
== null or not line
.is_empty
) and not was_empty
then
1710 block
.kind
= new BlockNone(block
)
1712 block
.kind
= new BlockParagraph(block
)
1714 current_block
.remove_leading_empty_lines
1716 v
.current_line
= current_block
.first_line
1720 # A line of markdown code.
1724 redef fun process
(v
) do
1725 var line
= v
.current_line
1727 while line
!= null and (line
.is_empty
or v
.line_kind
(line
) isa LineCode) do
1730 # split at block end line
1731 var current_block
= v
.current_block
.as(not null)
1733 if line
!= null then
1734 block
= current_block
.split
(line
.prev
.as(not null))
1736 block
= current_block
.split
(current_block
.last_line
.as(not null))
1738 block
.kind
= new BlockCode(block
)
1739 block
.remove_surrounding_empty_lines
1740 v
.current_line
= current_block
.first_line
1744 # A line of raw XML.
1748 redef fun process
(v
) do
1749 var line
= v
.current_line
1750 if line
== null then return
1751 var current_block
= v
.current_block
.as(not null)
1752 var prev
= line
.prev
1753 if prev
!= null then current_block
.split
(prev
)
1754 var block
= current_block
.split
(line
.xml_end_line
.as(not null))
1755 block
.kind
= new BlockXML(block
)
1756 current_block
.remove_leading_empty_lines
1757 v
.current_line
= current_block
.first_line
1761 # A markdown blockquote line.
1762 class LineBlockquote
1765 redef fun process
(v
) do
1766 var line
= v
.current_line
1767 var current_block
= v
.current_block
.as(not null)
1769 while line
!= null do
1770 if not line
.is_empty
and (line
.prev_empty
and
1771 line
.leading
== 0 and
1772 not v
.line_kind
(line
) isa LineBlockquote) then break
1777 if line
!= null then
1778 block
= current_block
.split
(line
.prev
.as(not null))
1780 block
= current_block
.split
(current_block
.last_line
.as(not null))
1782 var kind
= new BlockQuote(block
)
1784 block
.remove_surrounding_empty_lines
1785 kind
.remove_block_quote_prefix
(block
)
1786 v
.current_line
= line
1787 v
.recurse
(block
, false)
1788 v
.current_line
= current_block
.first_line
1792 # A markdown ruler line.
1796 redef fun process
(v
) do
1797 var line
= v
.current_line
1798 if line
== null then return
1799 var current_block
= v
.current_block
.as(not null)
1800 if line
.prev
!= null then current_block
.split
(line
.prev
.as(not null))
1801 var block
= current_block
.split
(line
)
1802 block
.kind
= new BlockRuler(block
)
1803 current_block
.remove_leading_empty_lines
1804 v
.current_line
= current_block
.first_line
1808 # A markdown fence code line.
1812 redef fun process
(v
) do
1814 var line
= v
.current_line
.as(not null).next
1815 var current_block
= v
.current_block
.as(not null)
1816 while line
!= null do
1817 if v
.line_kind
(line
) isa LineFence then break
1820 if line
!= null then
1825 if line
!= null then
1826 block
= current_block
.split
(line
.prev
.as(not null))
1828 block
= current_block
.split
(current_block
.last_line
.as(not null))
1830 block
.remove_surrounding_empty_lines
1831 var meta
= block
.first_line
.as(not null).value
.meta_from_fence
1832 block
.kind
= new BlockFence(block
, meta
)
1833 block
.first_line
.as(not null).clear
1834 var last
= block
.last_line
1835 if last
!= null and v
.line_kind
(last
) isa LineFence then
1836 block
.last_line
.as(not null).clear
1838 block
.remove_surrounding_empty_lines
1839 v
.current_line
= line
1843 # A markdown headline.
1847 redef fun process
(v
) do
1848 var line
= v
.current_line
1849 if line
== null then return
1850 var current_block
= v
.current_block
.as(not null)
1851 var lprev
= line
.prev
1852 if lprev
!= null then current_block
.split
(lprev
)
1853 var block
= current_block
.split
(line
)
1854 var kind
= new BlockHeadline(block
)
1856 kind
.transform_headline
(block
)
1857 current_block
.remove_leading_empty_lines
1858 v
.current_line
= current_block
.first_line
1862 # A markdown headline of level 1.
1866 redef fun process
(v
) do
1867 var line
= v
.current_line
1868 if line
== null then return
1869 var current_block
= v
.current_block
.as(not null)
1870 var lprev
= line
.prev
1871 if lprev
!= null then current_block
.split
(lprev
)
1872 line
.next
.as(not null).clear
1873 var block
= current_block
.split
(line
)
1874 var kind
= new BlockHeadline(block
)
1876 kind
.transform_headline
(block
)
1878 current_block
.remove_leading_empty_lines
1879 v
.current_line
= current_block
.first_line
1883 # A markdown headline of level 2.
1887 redef fun process
(v
) do
1888 var line
= v
.current_line
1889 if line
== null then return
1890 var current_block
= v
.current_block
.as(not null)
1891 var lprev
= line
.prev
1892 if lprev
!= null then current_block
.split
(lprev
)
1893 line
.next
.as(not null).clear
1894 var block
= current_block
.split
(line
)
1895 var kind
= new BlockHeadline(block
)
1897 kind
.transform_headline
(block
)
1899 current_block
.remove_leading_empty_lines
1900 v
.current_line
= current_block
.first_line
1904 # A markdown list line.
1905 # Mainly used to factorize code between ordered and unordered lists.
1906 abstract class LineList
1909 redef fun process
(v
) do
1910 var line
= v
.current_line
1912 while line
!= null do
1913 var t
= v
.line_kind
(line
)
1914 if not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1915 not t
isa LineList) then break
1919 var current_block
= v
.current_block
.as(not null)
1921 if line
!= null then
1922 list
= current_block
.split
(line
.prev
.as(not null))
1924 list
= current_block
.split
(current_block
.last_line
.as(not null))
1926 var kind
= block_kind
(list
)
1928 list
.first_line
.as(not null).prev_empty
= false
1929 list
.last_line
.as(not null).next_empty
= false
1930 list
.remove_surrounding_empty_lines
1931 list
.first_line
.as(not null).prev_empty
= false
1932 list
.last_line
.as(not null).next_empty
= false
1934 var block
= list
.first_block
1935 while block
!= null do
1936 block
.remove_list_indent
(v
)
1937 v
.recurse
(block
, true)
1940 kind
.expand_paragraphs
(list
)
1941 v
.current_line
= line
1944 # Create a new block kind based on this line.
1945 protected fun block_kind
(block
: MDBlock): BlockList is abstract
1947 # Extract string value from `MDLine`.
1948 protected fun extract_value
(line
: MDLine): String is abstract
1951 # An ordered list line.
1955 redef fun block_kind
(block
) do return new BlockOrderedList(block
)
1957 redef fun extract_value
(line
) do
1958 return line
.value
.substring_from
(line
.value
.index_of
('.') + 2)
1962 # An unordered list line.
1966 redef fun block_kind
(block
) do return new BlockUnorderedList(block
)
1968 redef fun extract_value
(line
) do
1969 return line
.value
.substring_from
(line
.leading
+ 2)
1973 # A token represent a character in the markdown input.
1974 # Some tokens have a specific markup behaviour that is handled here.
1975 abstract class Token
1977 # Location of `self` in the original input.
1978 var location
: nullable MDLocation
1980 # Position of `self` in input independant from lines.
1983 # Character found at `pos` in the markdown input.
1986 # Output that token using `MarkdownEmitter::decorator`.
1987 fun emit
(v
: MarkdownEmitter) do v
.decorator
.add_char
(v
, char
)
1990 # A token without a specific meaning.
1995 # An emphasis token.
1996 abstract class TokenEm
1999 redef fun emit
(v
) do
2000 var tmp
= v
.push_buffer
2001 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 1, self)
2004 v
.decorator
.add_em
(v
, tmp
)
2012 # An emphasis star token.
2017 # An emphasis underscore token.
2018 class TokenEmUnderscore
2023 abstract class TokenStrong
2026 redef fun emit
(v
) do
2027 var tmp
= v
.push_buffer
2028 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2031 v
.decorator
.add_strong
(v
, tmp
)
2032 v
.current_pos
= b
+ 1
2039 # A strong star token.
2040 class TokenStrongStar
2044 # A strong underscore token.
2045 class TokenStrongUnderscore
2050 # This class is mainly used to factorize work between single and double quoted span codes.
2051 abstract class TokenCode
2054 redef fun emit
(v
) do
2055 var current_text
= v
.current_text
.as(not null)
2056 var a
= pos
+ next_pos
+ 1
2057 var b
= v
.processor
.find_token
(current_text
, a
, self)
2059 v
.current_pos
= b
+ next_pos
2060 while a
< b
and current_text
[a
] == ' ' do a
+= 1
2062 while current_text
[b
- 1] == ' ' do b
-= 1
2063 v
.decorator
.add_span_code
(v
, current_text
, a
, b
)
2070 private fun next_pos
: Int is abstract
2073 # A span code token.
2074 class TokenCodeSingle
2077 redef fun next_pos
do return 0
2080 # A doubled span code token.
2081 class TokenCodeDouble
2084 redef fun next_pos
do return 1
2087 # A link or image token.
2088 # This class is mainly used to factorize work between images and links.
2089 abstract class TokenLinkOrImage
2093 var link
: nullable Text = null
2096 var name
: nullable Text = null
2099 var comment
: nullable Text = null
2101 # Is the link construct an abbreviation?
2102 var is_abbrev
= false
2104 redef fun emit
(v
) do
2105 var tmp
= new FlatBuffer
2106 var b
= check_link
(v
, tmp
, pos
, self)
2115 # Emit the hyperlink as link or image.
2116 private fun emit_hyper
(v
: MarkdownEmitter) is abstract
2118 # Check if the link is a valid link.
2119 private fun check_link
(v
: MarkdownEmitter, out
: FlatBuffer, start
: Int, token
: Token): Int do
2120 var md
= v
.current_text
2121 if md
== null then return -1
2123 if token
isa TokenLink then
2128 var tmp
= new FlatBuffer
2129 pos
= md
.read_md_link_id
(tmp
, pos
)
2130 if pos
< start
then return -1
2134 pos
= md
.skip_spaces
(pos
)
2136 var tid
= name
.as(not null).write_to_string
.to_lower
2137 if v
.processor
.link_refs
.has_key
(tid
) then
2138 var lr
= v
.processor
.link_refs
[tid
]
2139 is_abbrev
= lr
.is_abbrev
2146 else if md
[pos
] == '(' then
2148 pos
= md
.skip_spaces
(pos
)
2149 if pos
< start
then return -1
2150 tmp
= new FlatBuffer
2151 var use_lt
= md
[pos
] == '<'
2153 pos
= md
.read_until
(tmp
, pos
+ 1, '>')
2155 pos
= md
.read_md_link
(tmp
, pos
)
2157 if pos
< start
then return -1
2158 if use_lt
then pos
+= 1
2159 link
= tmp
.write_to_string
2160 if md
[pos
] == ' ' then
2161 pos
= md
.skip_spaces
(pos
)
2162 if pos
> start
and md
[pos
] == '"' then
2164 tmp
= new FlatBuffer
2165 pos
= md
.read_until
(tmp
, pos
, '"')
2166 if pos
< start
then return -1
2167 comment
= tmp
.write_to_string
2169 pos
= md
.skip_spaces
(pos
)
2170 if pos
== -1 then return -1
2173 if pos
< start
then return -1
2174 if md
[pos
] != ')' then return -1
2175 else if md
[pos
] == '[' then
2177 tmp
= new FlatBuffer
2178 pos
= md
.read_raw_until
(tmp
, pos
, ']')
2179 if pos
< start
then return -1
2181 if tmp
.length
> 0 then
2186 var tid
= id
.as(not null).write_to_string
.to_lower
2187 if v
.processor
.link_refs
.has_key
(tid
) then
2188 var lr
= v
.processor
.link_refs
[tid
]
2193 var tid
= name
.as(not null).write_to_string
.replace
("\n", " ").to_lower
2194 if v
.processor
.link_refs
.has_key
(tid
) then
2195 var lr
= v
.processor
.link_refs
[tid
]
2203 if link
== null then return -1
2208 # A markdown link token.
2210 super TokenLinkOrImage
2212 redef fun emit_hyper
(v
) do
2213 if is_abbrev
and comment
!= null then
2214 v
.decorator
.add_abbr
(v
, name
.as(not null), comment
.as(not null))
2216 v
.decorator
.add_link
(v
, link
.as(not null), name
.as(not null), comment
)
2221 # A markdown image token.
2223 super TokenLinkOrImage
2225 redef fun emit_hyper
(v
) do
2226 v
.decorator
.add_image
(v
, link
.as(not null), name
.as(not null), comment
)
2234 redef fun emit
(v
) do
2235 var tmp
= new FlatBuffer
2236 var b
= check_html
(v
, tmp
, v
.current_text
.as(not null), v
.current_pos
)
2241 v
.decorator
.escape_char
(v
, char
)
2245 # Is the HTML valid?
2246 # Also take care of link and mailto shortcuts.
2247 private fun check_html
(v
: MarkdownEmitter, out
: FlatBuffer, md
: Text, start
: Int): Int do
2248 # check for auto links
2249 var tmp
= new FlatBuffer
2250 var pos
= md
.read_until
(tmp
, start
+ 1, ':', ' ', '>', '\n')
2251 if pos
!= -1 and md
[pos
] == ':' and tmp
.is_link_prefix
then
2252 pos
= md
.read_until
(tmp
, pos
, '>')
2254 var link
= tmp
.write_to_string
2255 v
.decorator
.add_link
(v
, link
, link
, null)
2259 # TODO check for mailto
2260 # check for inline html
2261 if start
+ 2 < md
.length
then
2262 return md
.read_xml
(out
, start
, true)
2268 # An HTML entity token.
2272 redef fun emit
(v
) do
2273 var tmp
= new FlatBuffer
2274 var b
= check_entity
(tmp
, v
.current_text
.as(not null), pos
)
2279 v
.decorator
.escape_char
(v
, char
)
2283 # Is the entity valid?
2284 private fun check_entity
(out
: FlatBuffer, md
: Text, start
: Int): Int do
2285 var pos
= md
.read_until
(out
, start
, ';')
2286 if pos
< 0 or out
.length
< 3 then
2289 if out
[1] == '#' then
2290 if out
[2] == 'x' or out
[2] == 'X' then
2291 if out
.length
< 4 then return -1
2292 for i
in [3..out
.length
[ do
2294 if (c
< '0' or c
> '9') and (c
< 'a' and c
> 'f') and (c
< 'A' and c
> 'F') then
2299 for i
in [2..out
.length
[ do
2301 if c
< '0' or c
> '9' then return -1
2306 for i
in [1..out
.length
[ do
2308 if not c
.is_digit
and not c
.is_letter
then return -1
2311 # TODO check entity is valid
2312 # if out.is_entity then
2322 # A markdown escape token.
2326 redef fun emit
(v
) do
2328 v
.addc v
.current_text
.as(not null)[v
.current_pos
]
2332 # A markdown strike token.
2334 # Extended mode only (see `MarkdownProcessor::ext_mode`)
2338 redef fun emit
(v
) do
2339 var tmp
= v
.push_buffer
2340 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2343 v
.decorator
.add_strike
(v
, tmp
)
2344 v
.current_pos
= b
+ 1
2353 # Get the position of the next non-space character.
2354 private fun skip_spaces
(start
: Int): Int do
2356 while pos
> -1 and pos
< length
and (self[pos
] == ' ' or self[pos
] == '\n') do
2359 if pos
< length
then return pos
2363 # Read `self` until `nend` and append it to the `out` buffer.
2364 # Escape markdown special chars.
2365 private fun read_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2367 while pos
< length
do
2369 if c
== '\\' and pos
+ 1 < length
then
2370 pos
= escape
(out
, self[pos
+ 1], pos
)
2372 for n
in nend
do if c
== n
then break label
2377 if pos
== length
then return -1
2381 # Read `self` as raw text until `nend` and append it to the `out` buffer.
2382 # No escape is made.
2383 private fun read_raw_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2385 while pos
< length
do
2387 var end_reached
= false
2394 if end_reached
then break
2398 if pos
== length
then return -1
2402 # Read `self` as XML until `to` and append it to the `out` buffer.
2403 # Escape HTML special chars.
2404 private fun read_xml_until
(out
: FlatBuffer, from
: Int, to
: Char...): Int do
2407 var str_char
: nullable Char = null
2408 while pos
< length
do
2414 if pos
< length
then
2420 if c
== str_char
then
2427 if c
== '"' or c
== '\'' then
2432 var end_reached = false
2433 for n in [0..to.length[ do
2439 if end_reached then break
2444 if pos == length then return -1
2448 # Read `self` as XML and append it to the `out` buffer.
2449 # Safe mode can be activated to limit reading to valid xml.
2450 private fun read_xml(out: FlatBuffer, start: Int, safe_mode: Bool): Int do
2453 var is_close_tag = false
2454 if start + 1 >= length then return -1
2455 if self[start + 1] == '/' then
2458 else if self[start + 1] == '!' then
2462 is_close_tag = false
2466 var tmp = new FlatBuffer
2467 pos = read_xml_until(tmp, pos, ' ', '/', '>')
2468 if pos == -1 then return -1
2469 var tag = tmp.write_to_string.trim.to_lower
2470 if not tag.is_valid_html_tag then
2473 else if tag.is_html_unsafe then
2476 if is_close_tag then out.add '/'
2480 if is_close_tag then out.add '/'
2485 if is_close_tag then out.add '/'
2486 pos = read_xml_until(out, pos, ' ', '/', '>')
2488 if pos == -1 then return -1
2489 pos = read_xml_until(out, pos, '/', '>')
2490 if pos == -1 then return -1
2491 if self[pos] == '/' then
2493 pos = self.read_xml_until(out, pos + 1, '>')
2494 if pos == -1 then return -1
2496 if self[pos] == '>' then
2507 # Read a markdown link address and append it to the `out` buffer.
2508 private fun read_md_link(out: FlatBuffer, start: Int): Int do
2511 while pos < length do
2513 if c == '\\
' and pos + 1 < length then
2514 pos = escape(out, self[pos + 1], pos)
2516 var end_reached = false
2519 else if c == ' ' then
2520 if counter == 1 then end_reached = true
2521 else if c == ')' then
2523 if counter == 0 then end_reached = true
2525 if end_reached then break
2530 if pos == length then return -1
2534 # Read a markdown link text and append it to the `out` buffer.
2535 private fun read_md_link_id(out: FlatBuffer, start: Int): Int do
2538 while pos < length do
2540 var end_reached = false
2544 else if c == ']' then
2546 if counter == 0 then
2554 if end_reached then break
2557 if pos == length then return -1
2561 # Extract the XML tag name from a XML tag.
2562 private fun xml_tag: String do
2563 var tpl = new FlatBuffer
2565 if pos < length and self[1] == '/' then pos += 1
2566 while pos < length - 1 and (self[pos].is_digit or self[pos].is_letter) do
2570 return tpl.write_to_string.to_lower
2573 private fun is_valid_html_tag: Bool do
2574 if is_empty then return false
2576 if not c.is_alpha then return false
2581 # Read and escape the markdown contained in `self`.
2582 private fun escape(out: FlatBuffer, c: Char, pos: Int): Int do
2583 if c == '\\
' or c == '[' or c == ']' or c == '(' or c == ')' or c == '{' or
2584 c == '}' or c == '#' or c == '"' or c == '\'' or c == '.' or c == '<' or
2585 c
== '>' or c
== '*' or c
== '+' or c
== '-' or c
== '_' or c
== '!' or
2586 c
== '`' or c
== '~' or c
== '^' then
2594 # Extract string found at end of fence opening.
2595 private fun meta_from_fence
: nullable Text do
2596 for i
in [0..chars
.length
[ do
2598 if c
!= ' ' and c
!= '`' and c
!= '~' then
2599 return substring_from
(i
).trim
2605 # Is `self` an unsafe HTML element?
2606 private fun is_html_unsafe
: Bool do return html_unsafe_tags
.has
(self.write_to_string
)
2608 # Is `self` a HRML block element?
2609 private fun is_html_block
: Bool do return html_block_tags
.has
(self.write_to_string
)
2611 # Is `self` a link prefix?
2612 private fun is_link_prefix
: Bool do return html_link_prefixes
.has
(self.write_to_string
)
2614 private fun html_unsafe_tags
: Array[String] do return once
["applet", "head", "body", "frame", "frameset", "iframe", "script", "object"]
2616 private fun html_block_tags
: Array[String] do return once
["address", "article", "aside", "audio", "blockquote", "canvas", "dd", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video"]
2618 private fun html_link_prefixes
: Array[String] do return once
["http", "https", "ftp", "ftps"]
2623 # Parse `self` as markdown and return the HTML representation
2625 # var md = "**Hello World!**"
2626 # var html = md.md_to_html
2627 # assert html == "<p><strong>Hello World!</strong></p>\n"
2628 fun md_to_html
: Writable do
2629 var processor
= new MarkdownProcessor
2630 return processor
.process
(self)