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 # Work in extended mode (default).
35 # Behavior changes when using extended mode:
37 # * Lists and code blocks end a paragraph
39 # In normal markdown the following:
43 # * and this is not a list
49 # <p>This is a paragraph
50 # * and this is not a list</p>
53 # When using extended mode this changes to:
56 # <p>This is a paragraph</p>
58 # <li>and this is not a list</li>
62 # * Fences code blocks
64 # If you don't want to indent your all your code with 4 spaces,
65 # you can wrap your code in ``` ``` ``` or `~~~`.
71 # print "Hello World!"
77 # If you want to use syntax highlighting tools, most of them need to know what kind
78 # of language they are highlighting.
79 # You can add an optional language identifier after the fence declaration to output
80 # it in the HTML render.
85 # print "# Hello World!".md_to_html
91 # <pre class="nit"><code>import markdown
93 # print "Hello World!".md_to_html
97 # * Underscores (Emphasis)
99 # Underscores in the middle of a word like:
105 # normally produces this:
108 # <p>Con<em>cat</em>this</p>
111 # With extended mode they don't result in emphasis.
114 # <p>Con_cat_this</p>
119 # Like in [GFM](https://help.github.com/articles/github-flavored-markdown),
120 # strikethrought span is marked with `~~`.
129 # <del>Mistaken text.</del>
133 # Disable attaching MDLocation to Tokens
135 # Locations are useful for some tools but they may
136 # cause an important time and space overhead.
139 var no_location
= false is writable
141 # Process the mardown `input` string and return the processed output.
142 fun process
(input
: String): Writable do
149 var parent
= read_lines
(input
)
150 parent
.remove_surrounding_empty_lines
151 recurse
(parent
, false)
152 # output processed text
153 return emit
(parent
.kind
)
156 # Split `input` string into `MDLines` and create a parent `MDBlock` with it.
157 private fun read_lines
(input
: String): MDBlock do
158 var block
= new MDBlock(new MDLocation(1, 1, 1, 1))
159 var value
= new FlatBuffer
165 while i
< input
.length
do
169 while not eol
and i
< input
.length
do
174 else if c
== '\r' then
175 else if c
== '\t' then
176 var np
= pos
+ (4 - (pos
& 3))
189 var loc
= new MDLocation(line_pos
, 1, line_pos
, col_pos
)
190 var line
= new MDLine(loc
, value
.write_to_string
)
191 var is_link_ref
= check_link_ref
(line
)
193 if not is_link_ref
then block
.add_line line
199 # Check if line is a block link definition.
200 # Return `true` if line contains a valid link ref and save it into `link_refs`.
201 private fun check_link_ref
(line
: MDLine): Bool do
203 var is_link_ref
= false
204 var id
= new FlatBuffer
205 var link
= new FlatBuffer
206 var comment
= new FlatBuffer
208 if not line
.is_empty
and line
.leading
< 4 and line
.value
[line
.leading
] == '[' then
209 pos
= line
.leading
+ 1
210 pos
= md
.read_until
(id
, pos
, ']')
211 if not id
.is_empty
and pos
>= 0 and pos
+ 2 < line
.value
.length
then
212 if line
.value
[pos
+ 1] == ':' then
214 pos
= md
.skip_spaces
(pos
)
215 if pos
>= 0 and line
.value
[pos
] == '<' then
217 pos
= md
.read_until
(link
, pos
, '>')
219 else if pos
>= 0 then
220 pos
= md
.read_until
(link
, pos
, ' ', '\n')
222 if not link
.is_empty
then
223 pos
= md
.skip_spaces
(pos
)
224 if pos
> 0 and pos
< line
.value
.length
then
225 var c
= line
.value
[pos
]
226 if c
== '\"' or c
== '\'' or c == '(' then
229 pos = md.read_until(comment, pos, ')')
231 pos = md.read_until(comment, pos, c)
233 if pos > 0 then is_link_ref = true
242 if is_link_ref and not id.is_empty and not link.is_empty then
243 var lr = new LinkRef.with_title(link.write_to_string, comment.write_to_string)
244 add_link_ref(id.write_to_string, lr)
245 if comment.is_empty then last_link_ref = lr
248 comment = new FlatBuffer
249 if not line.is_empty and last_link_ref != null then
251 var c = line.value[pos]
252 if c == '\
"' or c == '\'' or c == '(' then
255 pos = md.read_until(comment, pos, ')')
257 pos = md.read_until(comment, pos, c)
260 var last_link_ref = self.last_link_ref
261 if not comment.is_empty and last_link_ref != null then
262 last_link_ref.title = comment.write_to_string
265 if comment.is_empty then return false
271 # This list will be needed during output to expand links.
272 var link_refs: Map[String, LinkRef] = new HashMap[String, LinkRef]
274 # Last encountered link ref (for multiline definitions)
276 # Markdown allows link refs to be defined over two lines:
279 # [id]: http://example.com/longish/path/to/resource/here
280 # "Optional Title Here"
283 private var last_link_ref: nullable LinkRef = null
285 # Add a link ref to the list
286 fun add_link_ref(key: String, ref: LinkRef) do link_refs[key.to_lower] = ref
288 # Recursively split a `block`.
290 # The block is splitted according to the type of lines it contains.
291 # Some blocks can be splited again recursively like lists.
292 # The `in_list` mode is used to recurse on list and build
293 # nested paragraphs or code blocks.
294 fun recurse(root: MDBlock, in_list: Bool) do
295 var old_mode = self.in_list
296 var old_root = self.current_block
297 self.in_list = in_list
299 var line = root.first_line
300 while line != null and line.is_empty do
302 if line == null then return
307 while current_line != null do
308 line_kind(current_line.as(not null)).process(self)
310 self.in_list = old_mode
311 self.current_block = old_root
314 # Currently processed line.
315 # Used when visiting blocks with `recurse`.
316 var current_line: nullable MDLine = null is writable
318 # Currently processed block.
319 # Used when visiting blocks with `recurse`.
320 var current_block: nullable MDBlock = null is writable
322 # Is the current recursion in list mode?
323 # Used when visiting blocks with `recurse`
324 private var in_list = false
328 fun line_kind(md: MDLine): Line do
330 var leading = md.leading
331 var trailing = md.trailing
332 if md.is_empty then return new LineEmpty
333 if md.leading > 3 then return new LineCode
334 if value[leading] == '#' then return new LineHeadline
335 if value[leading] == '>' then return new LineBlockquote
338 if value.length - leading - trailing > 2 then
339 if value[leading] == '`' and md.count_chars_start('`') >= 3 then
342 if value[leading] == '~' and md.count_chars_start('~') >= 3 then
348 if value.length - leading - trailing > 2 and
349 (value[leading] == '*' or value[leading] == '-' or value[leading] == '_') then
350 if md.count_chars(value[leading]) >= 3 then
355 if value.length - leading >= 2 and value[leading + 1] == ' ' then
356 var c = value[leading]
357 if c == '*' or c == '-' or c == '+' then return new LineUList
360 if value.length - leading >= 3 and value[leading].is_digit then
362 while i < value.length and value[i].is_digit do i += 1
363 if i + 1 < value.length and value[i] == '.' and value[i + 1] == ' ' then
368 if value[leading] == '<' and md.check_html then return new LineXML
371 if next != null and not next.is_empty then
372 if next.count_chars('=') > 0 then
373 return new LineHeadline1
375 if next.count_chars('-') > 0 then
376 return new LineHeadline2
382 # Get the token kind at `pos`.
383 fun token_at(text: Text, pos: Int): Token do
395 if pos + 1 < text.length then
400 if pos + 2 < text.length then
410 loc = new MDLocation(
411 current_loc.line_start,
412 current_loc.column_start + pos,
413 current_loc.line_start,
414 current_loc.column_start + pos)
419 if c0 != ' ' or c2 != ' ' then
420 return new TokenStrongStar(loc, pos, c)
422 return new TokenEmStar(loc, pos, c)
425 if c0 != ' ' or c1 != ' ' then
426 return new TokenEmStar(loc, pos, c)
428 return new TokenNone(loc, pos, c)
430 else if c == '_' then
432 if c0 != ' ' or c2 != ' ' then
433 return new TokenStrongUnderscore(loc, pos, c)
435 return new TokenEmUnderscore(loc, pos, c)
439 if (c0.is_letter or c0.is_digit) and c0 != '_' and
440 (c1.is_letter or c1.is_digit) then
441 return new TokenNone(loc, pos, c)
443 return new TokenEmUnderscore(loc, pos, c)
446 if c0 != ' ' or c1 != ' ' then
447 return new TokenEmUnderscore(loc, pos, c)
449 return new TokenNone(loc, pos, c)
451 else if c == '!' then
452 if c1 == '[' then return new TokenImage(loc, pos, c)
453 return new TokenNone(loc, pos, c)
454 else if c == '[' then
455 return new TokenLink(loc, pos, c)
456 else if c == ']' then
457 return new TokenNone(loc, pos, c)
458 else if c == '`' then
460 return new TokenCodeDouble(loc, pos, c)
462 return new TokenCodeSingle(loc, pos, c)
464 else if c == '\\' then
465 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
466 return new TokenEscape(loc
, pos
, c
)
468 return new TokenNone(loc
, pos
, c
)
470 else if c
== '<' then
471 return new TokenHTML(loc
, pos
, c
)
472 else if c
== '&' then
473 return new TokenEntity(loc
, pos
, c
)
476 if c
== '~' and c1
== '~' then
477 return new TokenStrike(loc
, pos
, c
)
480 return new TokenNone(loc
, pos
, c
)
484 # Find the position of a `token` in `self`.
485 fun find_token
(text
: Text, start
: Int, token
: Token): Int do
487 while pos
< text
.length
do
488 if token_at
(text
, pos
).is_same_type
(token
) then
496 # Kind of decorator used for decoration.
497 type DECORATOR: Decorator
499 # Decorator used for output.
500 # Default is `HTMLDecorator`
501 var decorator
: DECORATOR is writable, lazy
do
502 return new HTMLDecorator
505 # Create a new `MarkdownEmitter` using a custom `decorator`.
506 init with_decorator
(decorator
: DECORATOR) do
507 self.decorator
= decorator
510 # Output `block` using `decorator` in the current buffer.
511 fun emit
(block
: Block): Text do
512 var buffer
= push_buffer
518 # Output the content of `block`.
519 fun emit_in
(block
: Block) do block
.emit_in
(self)
521 # Transform and emit mardown text
522 fun emit_text
(text
: Text) do emit_text_until
(text
, 0, null)
524 # Transform and emit mardown text starting at `start` and
525 # until a token with the same type as `token` is found.
526 # Go until the end of `text` if `token` is null.
527 fun emit_text_until
(text
: Text, start
: Int, token
: nullable Token): Int do
528 var old_text
= current_text
529 var old_pos
= current_pos
532 while current_pos
< text
.length
do
533 if text
[current_pos
] == '\n' then
534 current_loc
.line_start
+= 1
535 current_loc
.column_start
= -current_pos
537 var mt
= token_at
(text
, current_pos
)
538 if (token
!= null and not token
isa TokenNone) and
539 (mt
.is_same_type
(token
) or
540 (token
isa TokenEmStar and mt
isa TokenStrongStar) or
541 (token
isa TokenEmUnderscore and mt
isa TokenStrongUnderscore)) then
547 current_text
= old_text
548 current_pos
= old_pos
552 # Currently processed position in `current_text`.
553 # Used when visiting inline production with `emit_text_until`.
554 private var current_pos
: Int = -1
556 # Currently processed text.
557 # Used when visiting inline production with `emit_text_until`.
558 private var current_text
: nullable Text = null
561 private var buffer_stack
= new List[FlatBuffer]
563 # Push a new buffer on the stack.
564 private fun push_buffer
: FlatBuffer do
565 var buffer
= new FlatBuffer
566 buffer_stack
.add buffer
570 # Pop the last buffer.
571 private fun pop_buffer
do buffer_stack
.pop
573 # Current output buffer.
574 private fun current_buffer
: FlatBuffer do
575 assert not buffer_stack
.is_empty
576 return buffer_stack
.last
580 private var loc_stack
= new List[MDLocation]
582 # Push a new MDLocation on the stack.
583 private fun push_loc
(location
: MDLocation) do loc_stack
.add location
585 # Pop the last buffer.
586 private fun pop_loc
: MDLocation do return loc_stack
.pop
588 # Current output buffer.
589 private fun current_loc
: MDLocation do
590 assert not loc_stack
.is_empty
591 return loc_stack
.last
594 # Append `e` to current buffer.
595 fun add
(e
: Writable) do
597 current_buffer
.append e
599 current_buffer
.append e
.write_to_string
603 # Append `c` to current buffer.
608 # Append a "\n" line break.
609 fun addn
do addc
'\n'
613 # Links that are specified somewhere in the mardown document to be reused as shortcuts.
616 # [1]: http://example.com/ "Optional title"
623 # Optional link title
624 var title
: nullable String = null
626 # Is the link an abreviation?
627 var is_abbrev
= false
629 # Create a link with a title.
630 init with_title
(link
: String, title
: nullable String) do
636 # A `Decorator` is used to emit mardown into a specific format.
637 # Default decorator used is `HTMLDecorator`.
640 # Kind of processor used
641 type PROCESSOR: MarkdownProcessor
643 # Render a single plain char.
645 # Redefine this method to add special escaping for plain text.
646 fun add_char
(v
: PROCESSOR, c
: Char) do v
.addc c
648 # Render a ruler block.
649 fun add_ruler
(v
: PROCESSOR, block
: BlockRuler) is abstract
651 # Render a headline block with corresponding level.
652 fun add_headline
(v
: PROCESSOR, block
: BlockHeadline) is abstract
654 # Render a paragraph block.
655 fun add_paragraph
(v
: PROCESSOR, block
: BlockParagraph) is abstract
657 # Render a code or fence block.
658 fun add_code
(v
: PROCESSOR, block
: BlockCode) is abstract
660 # Render a blockquote.
661 fun add_blockquote
(v
: PROCESSOR, block
: BlockQuote) is abstract
663 # Render an unordered list.
664 fun add_unorderedlist
(v
: PROCESSOR, block
: BlockUnorderedList) is abstract
666 # Render an ordered list.
667 fun add_orderedlist
(v
: PROCESSOR, block
: BlockOrderedList) is abstract
669 # Render a list item.
670 fun add_listitem
(v
: PROCESSOR, block
: BlockListItem) is abstract
672 # Render an emphasis text.
673 fun add_em
(v
: PROCESSOR, text
: Text) is abstract
675 # Render a strong text.
676 fun add_strong
(v
: PROCESSOR, text
: Text) is abstract
678 # Render a strike text.
680 # Extended mode only (see `MarkdownProcessor::ext_mode`)
681 fun add_strike
(v
: PROCESSOR, text
: Text) is abstract
684 fun add_link
(v
: PROCESSOR, link
: Text, name
: Text, comment
: nullable Text) is abstract
687 fun add_image
(v
: PROCESSOR, link
: Text, name
: Text, comment
: nullable Text) is abstract
689 # Render an abbreviation.
690 fun add_abbr
(v
: PROCESSOR, name
: Text, comment
: Text) is abstract
692 # Render a code span reading from a buffer.
693 fun add_span_code
(v
: PROCESSOR, buffer
: Text, from
, to
: Int) is abstract
695 # Render a text and escape it.
696 fun append_value
(v
: PROCESSOR, value
: Text) is abstract
698 # Render code text from buffer and escape it.
699 fun append_code
(v
: PROCESSOR, buffer
: Text, from
, to
: Int) is abstract
701 # Render a character escape.
702 fun escape_char
(v
: PROCESSOR, char
: Char) is abstract
704 # Render a line break
705 fun add_line_break
(v
: PROCESSOR) is abstract
707 # Generate a new html valid id from a `String`.
708 fun strip_id
(txt
: String): String is abstract
710 # Found headlines during the processing labeled by their ids.
711 fun headlines
: ArrayMap[String, HeadLine] is abstract
714 # Class representing a markdown headline.
716 # Unique identifier of this headline.
719 # Text of the headline.
722 # Level of this headline.
724 # According toe the markdown specification, level must be in `[1..6]`.
728 # `Decorator` that outputs HTML.
732 redef var headlines
= new ArrayMap[String, HeadLine]
734 redef fun add_ruler
(v
, block
) do v
.add
"<hr/>\n"
736 redef fun add_headline
(v
, block
) do
738 var line
= block
.block
.first_line
739 if line
== null then return
741 var id
= strip_id
(txt
)
742 var lvl
= block
.depth
743 headlines
[id
] = new HeadLine(id
, txt
, lvl
)
745 v
.add
"<h{lvl} id=\"{id}\
">"
750 redef fun add_paragraph
(v
, block
) do
756 redef fun add_code
(v
, block
) do
757 var meta
= block
.meta
759 v
.add
"<pre class=\""
760 append_value(v, meta)
766 v
.add
"</code></pre>\n"
769 redef fun add_blockquote
(v
, block
) do
770 v
.add
"<blockquote>\n"
772 v
.add
"</blockquote>\n"
775 redef fun add_unorderedlist
(v
, block
) do
781 redef fun add_orderedlist
(v
, block
) do
787 redef fun add_listitem
(v
, block
) do
793 redef fun add_em
(v
, text
) do
799 redef fun add_strong
(v
, text
) do
805 redef fun add_strike
(v
, text
) do
811 redef fun add_image
(v
, link
, name
, comment
) do
813 append_value(v, link)
815 append_value(v, name)
817 if comment
!= null and not comment
.is_empty
then
819 append_value(v, comment)
825 redef fun add_link
(v
, link
, name
, comment
) do
827 append_value(v, link)
829 if comment
!= null and not comment
.is_empty
then
831 append_value(v, comment)
839 redef fun add_abbr
(v
, name
, comment
) do
840 v
.add
"<abbr title=\""
841 append_value(v, comment)
847 redef fun add_span_code
(v
, text
, from
, to
) do
849 append_code
(v
, text
, from
, to
)
853 redef fun add_line_break
(v
) do
857 redef fun append_value
(v
, text
) do for c
in text
do escape_char
(v
, c
)
859 redef fun escape_char
(v
, c
) do
862 else if c
== '<' then
864 else if c
== '>' then
866 else if c
== '"' then
868 else if c
== '\'' then
875 redef fun append_code(v, buffer, from, to) do
876 for i in [from..to[ do
880 else if c == '<' then
882 else if c == '>' then
890 redef fun strip_id(txt) do
892 var b = new FlatBuffer
897 if not c.is_letter and
899 not allowed_id_chars.has(c) then continue
905 # check for multiple id definitions
906 if headlines.has_key(key) then
909 while headlines.has_key(key) do
917 private var allowed_id_chars: Array[Char] = ['-', '_
', ':', '.']
920 # Location in a Markdown input.
923 # Starting line number (starting from 1).
926 # Starting column number (starting from 1).
927 var column_start: Int
929 # Stopping line number (starting from 1).
932 # Stopping column number (starting from 1).
935 redef fun to_s do return "{line_start},{column_start}--{line_end},{column_end}"
937 # Return a copy of `self`.
938 fun copy: MDLocation do
939 return new MDLocation(line_start, column_start, line_end, column_end)
943 # A block of markdown lines.
944 # A `MDBlock` can contains lines and/or sub-blocks.
947 # Position of `self` in the input.
948 var location: MDLocation
952 var kind: Block = new BlockNone(self) is writable
955 var first_line: nullable MDLine = null is writable
958 var last_line: nullable MDLine = null is writable
960 # First sub-block if any.
961 var first_block: nullable MDBlock = null is writable
963 # Last sub-block if any.
964 var last_block: nullable MDBlock = null is writable
966 # Previous block if any.
967 var prev: nullable MDBlock = null is writable
970 var next: nullable MDBlock = null is writable
972 # Does this block contain subblocks?
973 fun has_blocks: Bool do return first_block != null
976 fun count_blocks: Int do
978 var block = first_block
979 while block != null do
986 # Does this block contain lines?
987 fun has_lines: Bool do return first_line != null
990 fun count_lines: Int do
992 var line = first_line
993 while line != null do
1000 # Split `self` creating a new sub-block having `line` has `last_line`.
1001 fun split(line: MDLine): MDBlock do
1002 # location for new block
1003 var new_loc = new MDLocation(
1004 first_line.as(not null).location.line_start,
1005 first_line.as(not null).location.column_start,
1006 line.location.line_end,
1007 line.location.column_end)
1009 var block = new MDBlock(new_loc)
1010 block.first_line = first_line
1011 block.last_line = line
1012 first_line = line.next
1014 if first_line == null then
1017 first_line.as(not null).prev = null
1018 # update current block loc
1019 location.line_start = first_line.as(not null).location.line_start
1020 location.column_start = first_line.as(not null).location.column_start
1022 if first_block == null then
1026 last_block.as(not null).next = block
1032 # Add a `line` to this block.
1033 fun add_line(line: MDLine) do
1034 if last_line == null then
1038 last_line.as(not null).next_empty = line.is_empty
1039 line.prev_empty = last_line.as(not null).is_empty
1040 line.prev = last_line
1041 last_line.as(not null).next = line
1046 # Remove `line` from this block.
1047 fun remove_line(line: MDLine) do
1048 if line.prev == null then
1049 first_line = line.next
1051 line.prev.as(not null).next = line.next
1053 if line.next == null then
1054 last_line = line.prev
1056 line.next.as(not null).prev = line.prev
1062 # Remove leading empty lines.
1063 fun remove_leading_empty_lines: Bool do
1064 var was_empty = false
1065 var line = first_line
1066 while line != null and line.is_empty do
1074 # Remove trailing empty lines.
1075 fun remove_trailing_empty_lines: Bool do
1076 var was_empty = false
1077 var line = last_line
1078 while line != null and line.is_empty do
1086 # Remove leading and trailing empty lines.
1087 fun remove_surrounding_empty_lines: Bool do
1088 var was_empty = false
1089 if remove_leading_empty_lines then was_empty = true
1090 if remove_trailing_empty_lines then was_empty = true
1094 # Remove list markers and up to 4 leading spaces.
1095 # Used to clean nested lists.
1096 fun remove_list_indent(v: MarkdownProcessor) do
1097 var line = first_line
1098 while line != null do
1099 if not line.is_empty then
1100 var kind = v.line_kind(line)
1101 if kind isa LineList then
1102 line.value = kind.extract_value(line)
1104 line.value = line.value.substring_from(line.leading.min(4))
1106 line.leading = line.process_leading
1112 # Collect block line text.
1114 var text = new FlatBuffer
1115 var line = first_line
1116 while line != null do
1117 if not line.is_empty then
1118 text.append line.text
1123 var block = first_block
1124 while block != null do
1125 text.append block.text
1129 return text.write_to_string
1133 # Representation of a markdown block in the AST.
1134 # Each `Block` is linked to a `MDBlock` that contains mardown code.
1135 abstract class Block
1137 # The markdown block `self` is related to.
1140 # Output `self` using `v.decorator`.
1141 fun emit(v: MarkdownProcessor) do v.emit_in(self)
1143 # Emit the containts of `self`, lines or blocks.
1144 fun emit_in(v: MarkdownProcessor) do
1145 block.remove_surrounding_empty_lines
1146 if block.has_lines then
1153 # Emit lines contained in `block`.
1154 fun emit_lines(v: MarkdownProcessor) do
1155 var tpl = v.push_buffer
1156 var line = block.first_line
1157 while line != null do
1158 if not line.is_empty then
1159 v.add line.value.substring(line.leading, line.value.length - line.trailing)
1160 if line.trailing >= 2 then v.decorator.add_line_break(v)
1162 if line.next != null then
1171 # Emit sub-blocks contained in `block`.
1172 fun emit_blocks(v: MarkdownProcessor) do
1173 var block = self.block.first_block
1174 while block != null do
1175 v.push_loc(block.location)
1182 # The raw content of the block as a multi-line string.
1183 fun raw_content: String do
1184 var infence = self isa BlockFence
1185 var text = new FlatBuffer
1186 var line = self.block.first_line
1187 while line != null do
1188 if not line.is_empty then
1189 var str = line.value
1190 if not infence and str.has_prefix(" ") then
1191 text.append str.substring(4, str.length - line.trailing)
1199 return text.write_to_string
1203 # A block without any markdown specificities.
1205 # Actually use the same implementation than `BlockCode`,
1206 # this class is only used for typing purposes.
1211 # A markdown blockquote.
1215 redef fun emit(v) do v.decorator.add_blockquote(v, self)
1217 # Remove blockquote markers.
1218 private fun remove_block_quote_prefix(block: MDBlock) do
1219 var line = block.first_line
1220 while line != null do
1221 if not line.is_empty then
1222 if line.value[line.leading] == '>' then
1223 var rem = line.leading + 1
1224 if line.leading + 1 < line.value.length and
1225 line.value[line.leading + 1] == ' ' then
1228 line.value = line.value.substring_from(rem)
1229 line.leading = line.process_leading
1237 # A markdown code block.
1241 # Any string found after fence token.
1242 var meta: nullable Text
1244 # Number of char to skip at the beginning of the line.
1246 # Block code lines start at 4 spaces.
1247 protected var line_start = 4
1249 redef fun emit(v) do v.decorator.add_code(v, self)
1251 redef fun emit_lines(v) do
1252 var line = block.first_line
1253 while line != null do
1254 if not line.is_empty then
1255 v.decorator.append_code(v, line.value, line_start, line.value.length)
1263 # A markdown code-fence block.
1265 # Actually use the same implementation than `BlockCode`,
1266 # this class is only used for typing purposes.
1270 # Fence code lines start at 0 spaces.
1271 redef var line_start = 0
1274 # A markdown headline.
1278 redef fun emit(v) do
1279 var loc = block.location.copy
1280 loc.column_start += start
1282 v.decorator.add_headline(v, self)
1286 private var start = 0
1288 # Depth of the headline used to determine the headline level.
1291 # Remove healine marks from lines contained in `self`.
1292 private fun transform_headline(block: MDBlock) do
1293 if depth > 0 then return
1295 var line = block.first_line
1296 if line == null then return
1297 if line.is_empty then return
1298 var start = line.leading
1299 while start < line.value.length and line.value[start] == '#' do
1303 while start
< line
.value
.length
and line
.value
[start
] == ' ' do
1306 if start
>= line
.value
.length
then
1307 line
.is_empty
= true
1309 var nend
= line
.value
.length
- line
.trailing
- 1
1310 while line
.value
[nend
] == '#' do nend
-= 1
1311 while line
.value
[nend
] == ' ' do nend
-= 1
1312 line
.value
= line
.value
.substring
(start
, nend
- start
+ 1)
1317 depth
= level
.min
(6)
1321 # A markdown list item block.
1325 redef fun emit
(v
) do v
.decorator
.add_listitem
(v
, self)
1328 # A markdown list block.
1329 # Can be either an ordered or unordered list, this class is mainly used to factorize code.
1330 abstract class BlockList
1333 # Split list block into list items sub-blocks.
1334 private fun init_block
(v
: MarkdownProcessor) do
1335 var line
= block
.first_line
1336 if line
== null then return
1338 while line
!= null do
1339 var t
= v
.line_kind
(line
)
1340 if t
isa LineList or
1341 (not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1342 not (t
isa LineList))) then
1343 var sblock
= block
.split
(line
.prev
.as(not null))
1344 sblock
.kind
= new BlockListItem(sblock
)
1348 var sblock
= block
.split
(block
.last_line
.as(not null))
1349 sblock
.kind
= new BlockListItem(sblock
)
1352 # Expand list items as paragraphs if needed.
1353 private fun expand_paragraphs
(block
: MDBlock) do
1354 var outer
= block
.first_block
1355 var inner
: nullable MDBlock
1356 var has_paragraph
= false
1357 while outer
!= null and not has_paragraph
do
1358 if outer
.kind
isa BlockListItem then
1359 inner
= outer
.first_block
1360 while inner
!= null and not has_paragraph
do
1361 if inner
.kind
isa BlockParagraph then
1362 has_paragraph
= true
1369 if has_paragraph
then
1370 outer
= block
.first_block
1371 while outer
!= null do
1372 if outer
.kind
isa BlockListItem then
1373 inner
= outer
.first_block
1374 while inner
!= null do
1375 if inner
.kind
isa BlockNone then
1376 inner
.kind
= new BlockParagraph(inner
)
1387 # A markdown ordered list.
1388 class BlockOrderedList
1391 redef fun emit
(v
) do v
.decorator
.add_orderedlist
(v
, self)
1394 # A markdown unordred list.
1395 class BlockUnorderedList
1398 redef fun emit
(v
) do v
.decorator
.add_unorderedlist
(v
, self)
1401 # A markdown paragraph block.
1402 class BlockParagraph
1405 redef fun emit
(v
) do v
.decorator
.add_paragraph
(v
, self)
1412 redef fun emit
(v
) do v
.decorator
.add_ruler
(v
, self)
1415 # Xml blocks that can be found in markdown markup.
1419 redef fun emit_lines
(v
) do
1420 var line
= block
.first_line
1421 while line
!= null do
1422 if not line
.is_empty
then v
.add line
.value
1432 # Location of `self` in the original input.
1433 var location
: MDLocation
1435 # Text contained in this line.
1436 var value
: String is writable
1438 # Is this line empty?
1439 # Lines containing only spaces are considered empty.
1440 var is_empty
: Bool = true is writable
1442 # Previous line in `MDBlock` or null if first line.
1443 var prev
: nullable MDLine = null is writable
1445 # Next line in `MDBlock` or null if last line.
1446 var next
: nullable MDLine = null is writable
1448 # Is the previous line empty?
1449 var prev_empty
: Bool = false is writable
1451 # Is the next line empty?
1452 var next_empty
: Bool = false is writable
1454 # Initialize a new MDLine from its string value
1456 self.leading
= process_leading
1457 if leading
!= value
.length
then
1458 self.is_empty
= false
1459 self.trailing
= process_trailing
1463 # Set `value` as an empty String and update `leading`, `trailing` and is_`empty`.
1469 if prev
!= null then prev
.as(not null).next_empty
= true
1470 if next
!= null then next
.as(not null).prev_empty
= true
1473 # Number or leading spaces on this line.
1474 var leading
: Int = 0 is writable
1476 # Compute `leading` depending on `value`.
1477 fun process_leading
: Int do
1479 var value
= self.value
1480 while count
< value
.length
and value
[count
] == ' ' do count
+= 1
1481 if leading
== value
.length
then clear
1485 # Number of trailing spaces on this line.
1486 var trailing
: Int = 0 is writable
1488 # Compute `trailing` depending on `value`.
1489 fun process_trailing
: Int do
1491 var value
= self.value
1492 while value
[value
.length
- count
- 1] == ' ' do
1498 # Count the amount of `ch` in this line.
1499 # Return A value > 0 if this line only consists of `ch` end spaces.
1500 fun count_chars
(ch
: Char): Int do
1516 # Count the amount of `ch` at the start of this line ignoring spaces.
1517 fun count_chars_start
(ch
: Char): Int do
1532 # Last XML line if any.
1533 private var xml_end_line
: nullable MDLine = null
1535 # Does `value` contains valid XML markup?
1536 private fun check_html
: Bool do
1537 var tags
= new Array[String]
1538 var tmp
= new FlatBuffer
1540 if pos
+ 1 < value
.length
and value
[pos
+ 1] == '!' then
1541 if read_xml_comment
(self, pos
) > 0 then return true
1543 pos
= value
.read_xml
(tmp
, pos
, false)
1547 if not tag
.is_html_block
then
1555 var line
: nullable MDLine = self
1556 while line
!= null do
1557 while pos
< line
.value
.length
and line
.value
[pos
] != '<' do
1560 if pos
>= line
.value
.length
then
1561 if pos
- 2 >= 0 and line
.value
[pos
- 2] == '/' then
1563 if tags
.is_empty
then
1571 tmp
= new FlatBuffer
1572 var new_pos
= line
.value
.read_xml
(tmp
, pos
, false)
1575 if tag
.is_html_block
and not tag
== "hr" then
1576 if tmp
[1] == '/' then
1577 if tags
.last
!= tag
then
1585 if tags
.is_empty
then
1595 return tags
.is_empty
1600 # Read a XML comment.
1601 # Used by `check_html`.
1602 private fun read_xml_comment
(first_line
: MDLine, start
: Int): Int do
1603 var line
: nullable MDLine = first_line
1604 if start
+ 3 < line
.as(not null).value
.length
then
1605 if line
.as(not null).value
[2] == '-' and line
.as(not null).value
[3] == '-' then
1607 while line
!= null do
1608 while pos
< line
.value
.length
and line
.value
[pos
] != '-' do
1611 if pos
== line
.value
.length
then
1615 if pos
+ 2 < line
.value
.length
then
1616 if line
.value
[pos
+ 1] == '-' and line
.value
[pos
+ 2] == '>' then
1617 first_line
.xml_end_line
= line
1629 # Extract the text of `self` without leading and trailing.
1630 fun text
: String do return value
.substring
(leading
, value
.length
- trailing
)
1637 # See `MarkdownProcessor::recurse`.
1638 fun process
(v
: MarkdownProcessor) is abstract
1641 # An empty markdown line.
1645 redef fun process
(v
) do
1646 v
.current_line
= v
.current_line
.as(not null).next
1650 # A non-specific markdown construction.
1651 # Mainly used as part of another line construct such as paragraphs or lists.
1655 redef fun process
(v
) do
1656 var line
= v
.current_line
1658 var was_empty
= line
.as(not null).prev_empty
1659 while line
!= null and not line
.is_empty
do
1660 var t
= v
.line_kind
(line
)
1661 if (v
.in_list
or v
.ext_mode
) and t
isa LineList then
1664 if v
.ext_mode
and (t
isa LineCode or t
isa LineFence) then
1667 if t
isa LineHeadline or t
isa LineHeadline1 or t
isa LineHeadline2 or
1668 t
isa LineHR or t
isa LineBlockquote or t
isa LineXML then
1674 var current_block
= v
.current_block
.as(not null)
1675 if line
!= null and not line
.is_empty
then
1676 var block
= current_block
.split
(line
.prev
.as(not null))
1677 if v
.in_list
and not was_empty
then
1678 block
.kind
= new BlockNone(block
)
1680 block
.kind
= new BlockParagraph(block
)
1682 current_block
.remove_leading_empty_lines
1685 if line
!= null then
1686 block
= current_block
.split
(line
)
1688 block
= current_block
.split
(current_block
.last_line
.as(not null))
1690 if v
.in_list
and (line
== null or not line
.is_empty
) and not was_empty
then
1691 block
.kind
= new BlockNone(block
)
1693 block
.kind
= new BlockParagraph(block
)
1695 current_block
.remove_leading_empty_lines
1697 v
.current_line
= current_block
.first_line
1701 # A line of markdown code.
1705 redef fun process
(v
) do
1706 var line
= v
.current_line
1708 while line
!= null and (line
.is_empty
or v
.line_kind
(line
) isa LineCode) do
1711 # split at block end line
1712 var current_block
= v
.current_block
.as(not null)
1714 if line
!= null then
1715 block
= current_block
.split
(line
.prev
.as(not null))
1717 block
= current_block
.split
(current_block
.last_line
.as(not null))
1719 block
.kind
= new BlockCode(block
)
1720 block
.remove_surrounding_empty_lines
1721 v
.current_line
= current_block
.first_line
1725 # A line of raw XML.
1729 redef fun process
(v
) do
1730 var line
= v
.current_line
1731 if line
== null then return
1732 var current_block
= v
.current_block
.as(not null)
1733 var prev
= line
.prev
1734 if prev
!= null then current_block
.split
(prev
)
1735 var block
= current_block
.split
(line
.xml_end_line
.as(not null))
1736 block
.kind
= new BlockXML(block
)
1737 current_block
.remove_leading_empty_lines
1738 v
.current_line
= current_block
.first_line
1742 # A markdown blockquote line.
1743 class LineBlockquote
1746 redef fun process
(v
) do
1747 var line
= v
.current_line
1748 var current_block
= v
.current_block
.as(not null)
1750 while line
!= null do
1751 if not line
.is_empty
and (line
.prev_empty
and
1752 line
.leading
== 0 and
1753 not v
.line_kind
(line
) isa LineBlockquote) then break
1758 if line
!= null then
1759 block
= current_block
.split
(line
.prev
.as(not null))
1761 block
= current_block
.split
(current_block
.last_line
.as(not null))
1763 var kind
= new BlockQuote(block
)
1765 block
.remove_surrounding_empty_lines
1766 kind
.remove_block_quote_prefix
(block
)
1767 v
.current_line
= line
1768 v
.recurse
(block
, false)
1769 v
.current_line
= current_block
.first_line
1773 # A markdown ruler line.
1777 redef fun process
(v
) do
1778 var line
= v
.current_line
1779 if line
== null then return
1780 var current_block
= v
.current_block
.as(not null)
1781 if line
.prev
!= null then current_block
.split
(line
.prev
.as(not null))
1782 var block
= current_block
.split
(line
)
1783 block
.kind
= new BlockRuler(block
)
1784 current_block
.remove_leading_empty_lines
1785 v
.current_line
= current_block
.first_line
1789 # A markdown fence code line.
1793 redef fun process
(v
) do
1795 var line
= v
.current_line
.as(not null).next
1796 var current_block
= v
.current_block
.as(not null)
1797 while line
!= null do
1798 if v
.line_kind
(line
) isa LineFence then break
1801 if line
!= null then
1806 if line
!= null then
1807 block
= current_block
.split
(line
.prev
.as(not null))
1809 block
= current_block
.split
(current_block
.last_line
.as(not null))
1811 block
.remove_surrounding_empty_lines
1812 var meta
= block
.first_line
.as(not null).value
.meta_from_fence
1813 block
.kind
= new BlockFence(block
, meta
)
1814 block
.first_line
.as(not null).clear
1815 var last
= block
.last_line
1816 if last
!= null and v
.line_kind
(last
) isa LineFence then
1817 block
.last_line
.as(not null).clear
1819 block
.remove_surrounding_empty_lines
1820 v
.current_line
= line
1824 # A markdown headline.
1828 redef fun process
(v
) do
1829 var line
= v
.current_line
1830 if line
== null then return
1831 var current_block
= v
.current_block
.as(not null)
1832 var lprev
= line
.prev
1833 if lprev
!= null then current_block
.split
(lprev
)
1834 var block
= current_block
.split
(line
)
1835 var kind
= new BlockHeadline(block
)
1837 kind
.transform_headline
(block
)
1838 current_block
.remove_leading_empty_lines
1839 v
.current_line
= current_block
.first_line
1843 # A markdown headline of level 1.
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 line
.next
.as(not null).clear
1854 var block
= current_block
.split
(line
)
1855 var kind
= new BlockHeadline(block
)
1857 kind
.transform_headline
(block
)
1859 current_block
.remove_leading_empty_lines
1860 v
.current_line
= current_block
.first_line
1864 # A markdown headline of level 2.
1868 redef fun process
(v
) do
1869 var line
= v
.current_line
1870 if line
== null then return
1871 var current_block
= v
.current_block
.as(not null)
1872 var lprev
= line
.prev
1873 if lprev
!= null then current_block
.split
(lprev
)
1874 line
.next
.as(not null).clear
1875 var block
= current_block
.split
(line
)
1876 var kind
= new BlockHeadline(block
)
1878 kind
.transform_headline
(block
)
1880 current_block
.remove_leading_empty_lines
1881 v
.current_line
= current_block
.first_line
1885 # A markdown list line.
1886 # Mainly used to factorize code between ordered and unordered lists.
1887 abstract class LineList
1890 redef fun process
(v
) do
1891 var line
= v
.current_line
1893 while line
!= null do
1894 var t
= v
.line_kind
(line
)
1895 if not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1896 not t
isa LineList) then break
1900 var current_block
= v
.current_block
.as(not null)
1902 if line
!= null then
1903 list
= current_block
.split
(line
.prev
.as(not null))
1905 list
= current_block
.split
(current_block
.last_line
.as(not null))
1907 var kind
= block_kind
(list
)
1909 list
.first_line
.as(not null).prev_empty
= false
1910 list
.last_line
.as(not null).next_empty
= false
1911 list
.remove_surrounding_empty_lines
1912 list
.first_line
.as(not null).prev_empty
= false
1913 list
.last_line
.as(not null).next_empty
= false
1915 var block
= list
.first_block
1916 while block
!= null do
1917 block
.remove_list_indent
(v
)
1918 v
.recurse
(block
, true)
1921 kind
.expand_paragraphs
(list
)
1922 v
.current_line
= line
1925 # Create a new block kind based on this line.
1926 protected fun block_kind
(block
: MDBlock): BlockList is abstract
1928 # Extract string value from `MDLine`.
1929 protected fun extract_value
(line
: MDLine): String is abstract
1932 # An ordered list line.
1936 redef fun block_kind
(block
) do return new BlockOrderedList(block
)
1938 redef fun extract_value
(line
) do
1939 return line
.value
.substring_from
(line
.value
.index_of
('.') + 2)
1943 # An unordered list line.
1947 redef fun block_kind
(block
) do return new BlockUnorderedList(block
)
1949 redef fun extract_value
(line
) do
1950 return line
.value
.substring_from
(line
.leading
+ 2)
1954 # A token represent a character in the markdown input.
1955 # Some tokens have a specific markup behaviour that is handled here.
1956 abstract class Token
1958 # Location of `self` in the original input.
1959 var location
: nullable MDLocation
1961 # Position of `self` in input independant from lines.
1964 # Character found at `pos` in the markdown input.
1967 # Output that token using `MarkdownEmitter::decorator`.
1968 fun emit
(v
: MarkdownProcessor) do v
.decorator
.add_char
(v
, char
)
1971 # A token without a specific meaning.
1976 # An emphasis token.
1977 abstract class TokenEm
1980 redef fun emit
(v
) do
1981 var tmp
= v
.push_buffer
1982 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 1, self)
1985 v
.decorator
.add_em
(v
, tmp
)
1993 # An emphasis star token.
1998 # An emphasis underscore token.
1999 class TokenEmUnderscore
2004 abstract class TokenStrong
2007 redef fun emit
(v
) do
2008 var tmp
= v
.push_buffer
2009 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2012 v
.decorator
.add_strong
(v
, tmp
)
2013 v
.current_pos
= b
+ 1
2020 # A strong star token.
2021 class TokenStrongStar
2025 # A strong underscore token.
2026 class TokenStrongUnderscore
2031 # This class is mainly used to factorize work between single and double quoted span codes.
2032 abstract class TokenCode
2035 redef fun emit
(v
) do
2036 var current_text
= v
.current_text
.as(not null)
2037 var a
= pos
+ next_pos
+ 1
2038 var b
= v
.find_token
(current_text
, a
, self)
2040 v
.current_pos
= b
+ next_pos
2041 while a
< b
and current_text
[a
] == ' ' do a
+= 1
2043 while current_text
[b
- 1] == ' ' do b
-= 1
2044 v
.decorator
.add_span_code
(v
, current_text
, a
, b
)
2051 private fun next_pos
: Int is abstract
2054 # A span code token.
2055 class TokenCodeSingle
2058 redef fun next_pos
do return 0
2061 # A doubled span code token.
2062 class TokenCodeDouble
2065 redef fun next_pos
do return 1
2068 # A link or image token.
2069 # This class is mainly used to factorize work between images and links.
2070 abstract class TokenLinkOrImage
2074 var link
: nullable Text = null
2077 var name
: nullable Text = null
2080 var comment
: nullable Text = null
2082 # Is the link construct an abbreviation?
2083 var is_abbrev
= false
2085 redef fun emit
(v
) do
2086 var tmp
= new FlatBuffer
2087 var b
= check_link
(v
, tmp
, pos
, self)
2096 # Emit the hyperlink as link or image.
2097 private fun emit_hyper
(v
: MarkdownProcessor) is abstract
2099 # Check if the link is a valid link.
2100 private fun check_link
(v
: MarkdownProcessor, out
: FlatBuffer, start
: Int, token
: Token): Int do
2101 var md
= v
.current_text
2102 if md
== null then return -1
2104 if token
isa TokenLink then
2109 var tmp
= new FlatBuffer
2110 pos
= md
.read_md_link_id
(tmp
, pos
)
2111 if pos
< start
then return -1
2115 pos
= md
.skip_spaces
(pos
)
2117 var tid
= name
.as(not null).write_to_string
.to_lower
2118 if v
.link_refs
.has_key
(tid
) then
2119 var lr
= v
.link_refs
[tid
]
2120 is_abbrev
= lr
.is_abbrev
2127 else if md
[pos
] == '(' then
2129 pos
= md
.skip_spaces
(pos
)
2130 if pos
< start
then return -1
2131 tmp
= new FlatBuffer
2132 var use_lt
= md
[pos
] == '<'
2134 pos
= md
.read_until
(tmp
, pos
+ 1, '>')
2136 pos
= md
.read_md_link
(tmp
, pos
)
2138 if pos
< start
then return -1
2139 if use_lt
then pos
+= 1
2140 link
= tmp
.write_to_string
2141 if md
[pos
] == ' ' then
2142 pos
= md
.skip_spaces
(pos
)
2143 if pos
> start
and md
[pos
] == '"' then
2145 tmp
= new FlatBuffer
2146 pos
= md
.read_until
(tmp
, pos
, '"')
2147 if pos
< start
then return -1
2148 comment
= tmp
.write_to_string
2150 pos
= md
.skip_spaces
(pos
)
2151 if pos
== -1 then return -1
2154 if pos
< start
then return -1
2155 if md
[pos
] != ')' then return -1
2156 else if md
[pos
] == '[' then
2158 tmp
= new FlatBuffer
2159 pos
= md
.read_raw_until
(tmp
, pos
, ']')
2160 if pos
< start
then return -1
2162 if tmp
.length
> 0 then
2167 var tid
= id
.as(not null).write_to_string
.to_lower
2168 if v
.link_refs
.has_key
(tid
) then
2169 var lr
= v
.link_refs
[tid
]
2174 var tid
= name
.as(not null).write_to_string
.replace
("\n", " ").to_lower
2175 if v
.link_refs
.has_key
(tid
) then
2176 var lr
= v
.link_refs
[tid
]
2184 if link
== null then return -1
2189 # A markdown link token.
2191 super TokenLinkOrImage
2193 redef fun emit_hyper
(v
) do
2194 if is_abbrev
and comment
!= null then
2195 v
.decorator
.add_abbr
(v
, name
.as(not null), comment
.as(not null))
2197 v
.decorator
.add_link
(v
, link
.as(not null), name
.as(not null), comment
)
2202 # A markdown image token.
2204 super TokenLinkOrImage
2206 redef fun emit_hyper
(v
) do
2207 v
.decorator
.add_image
(v
, link
.as(not null), name
.as(not null), comment
)
2215 redef fun emit
(v
) do
2216 var tmp
= new FlatBuffer
2217 var b
= check_html
(v
, tmp
, v
.current_text
.as(not null), v
.current_pos
)
2222 v
.decorator
.escape_char
(v
, char
)
2226 # Is the HTML valid?
2227 # Also take care of link and mailto shortcuts.
2228 private fun check_html
(v
: MarkdownProcessor, out
: FlatBuffer, md
: Text, start
: Int): Int do
2229 # check for auto links
2230 var tmp
= new FlatBuffer
2231 var pos
= md
.read_until
(tmp
, start
+ 1, ':', ' ', '>', '\n')
2232 if pos
!= -1 and md
[pos
] == ':' and tmp
.is_link_prefix
then
2233 pos
= md
.read_until
(tmp
, pos
, '>')
2235 var link
= tmp
.write_to_string
2236 v
.decorator
.add_link
(v
, link
, link
, null)
2240 # TODO check for mailto
2241 # check for inline html
2242 if start
+ 2 < md
.length
then
2243 return md
.read_xml
(out
, start
, true)
2249 # An HTML entity token.
2253 redef fun emit
(v
) do
2254 var tmp
= new FlatBuffer
2255 var b
= check_entity
(tmp
, v
.current_text
.as(not null), pos
)
2260 v
.decorator
.escape_char
(v
, char
)
2264 # Is the entity valid?
2265 private fun check_entity
(out
: FlatBuffer, md
: Text, start
: Int): Int do
2266 var pos
= md
.read_until
(out
, start
, ';')
2267 if pos
< 0 or out
.length
< 3 then
2270 if out
[1] == '#' then
2271 if out
[2] == 'x' or out
[2] == 'X' then
2272 if out
.length
< 4 then return -1
2273 for i
in [3..out
.length
[ do
2275 if (c
< '0' or c
> '9') and (c
< 'a' and c
> 'f') and (c
< 'A' and c
> 'F') then
2280 for i
in [2..out
.length
[ do
2282 if c
< '0' or c
> '9' then return -1
2287 for i
in [1..out
.length
[ do
2289 if not c
.is_digit
and not c
.is_letter
then return -1
2292 # TODO check entity is valid
2293 # if out.is_entity then
2303 # A markdown escape token.
2307 redef fun emit
(v
) do
2309 v
.addc v
.current_text
.as(not null)[v
.current_pos
]
2313 # A markdown strike token.
2315 # Extended mode only (see `MarkdownProcessor::ext_mode`)
2319 redef fun emit
(v
) do
2320 var tmp
= v
.push_buffer
2321 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2324 v
.decorator
.add_strike
(v
, tmp
)
2325 v
.current_pos
= b
+ 1
2334 # Get the position of the next non-space character.
2335 private fun skip_spaces
(start
: Int): Int do
2337 while pos
> -1 and pos
< length
and (self[pos
] == ' ' or self[pos
] == '\n') do
2340 if pos
< length
then return pos
2344 # Read `self` until `nend` and append it to the `out` buffer.
2345 # Escape markdown special chars.
2346 private fun read_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2348 while pos
< length
do
2350 if c
== '\\' and pos
+ 1 < length
then
2351 pos
= escape
(out
, self[pos
+ 1], pos
)
2353 for n
in nend
do if c
== n
then break label
2358 if pos
== length
then return -1
2362 # Read `self` as raw text until `nend` and append it to the `out` buffer.
2363 # No escape is made.
2364 private fun read_raw_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2366 while pos
< length
do
2368 var end_reached
= false
2375 if end_reached
then break
2379 if pos
== length
then return -1
2383 # Read `self` as XML until `to` and append it to the `out` buffer.
2384 # Escape HTML special chars.
2385 private fun read_xml_until
(out
: FlatBuffer, from
: Int, to
: Char...): Int do
2388 var str_char
: nullable Char = null
2389 while pos
< length
do
2395 if pos
< length
then
2401 if c
== str_char
then
2408 if c
== '"' or c
== '\'' then
2413 var end_reached = false
2414 for n in [0..to.length[ do
2420 if end_reached then break
2425 if pos == length then return -1
2429 # Read `self` as XML and append it to the `out` buffer.
2430 # Safe mode can be activated to limit reading to valid xml.
2431 private fun read_xml(out: FlatBuffer, start: Int, safe_mode: Bool): Int do
2434 var is_close_tag = false
2435 if start + 1 >= length then return -1
2436 if self[start + 1] == '/' then
2439 else if self[start + 1] == '!' then
2443 is_close_tag = false
2447 var tmp = new FlatBuffer
2448 pos = read_xml_until(tmp, pos, ' ', '/', '>')
2449 if pos == -1 then return -1
2450 var tag = tmp.write_to_string.trim.to_lower
2451 if not tag.is_valid_html_tag then
2454 else if tag.is_html_unsafe then
2457 if is_close_tag then out.add '/'
2461 if is_close_tag then out.add '/'
2466 if is_close_tag then out.add '/'
2467 pos = read_xml_until(out, pos, ' ', '/', '>')
2469 if pos == -1 then return -1
2470 pos = read_xml_until(out, pos, '/', '>')
2471 if pos == -1 then return -1
2472 if self[pos] == '/' then
2474 pos = self.read_xml_until(out, pos + 1, '>')
2475 if pos == -1 then return -1
2477 if self[pos] == '>' then
2488 # Read a markdown link address and append it to the `out` buffer.
2489 private fun read_md_link(out: FlatBuffer, start: Int): Int do
2492 while pos < length do
2494 if c == '\\
' and pos + 1 < length then
2495 pos = escape(out, self[pos + 1], pos)
2497 var end_reached = false
2500 else if c == ' ' then
2501 if counter == 1 then end_reached = true
2502 else if c == ')' then
2504 if counter == 0 then end_reached = true
2506 if end_reached then break
2511 if pos == length then return -1
2515 # Read a markdown link text and append it to the `out` buffer.
2516 private fun read_md_link_id(out: FlatBuffer, start: Int): Int do
2519 while pos < length do
2521 var end_reached = false
2525 else if c == ']' then
2527 if counter == 0 then
2535 if end_reached then break
2538 if pos == length then return -1
2542 # Extract the XML tag name from a XML tag.
2543 private fun xml_tag: String do
2544 var tpl = new FlatBuffer
2546 if pos < length and self[1] == '/' then pos += 1
2547 while pos < length - 1 and (self[pos].is_digit or self[pos].is_letter) do
2551 return tpl.write_to_string.to_lower
2554 private fun is_valid_html_tag: Bool do
2555 if is_empty then return false
2557 if not c.is_alpha then return false
2562 # Read and escape the markdown contained in `self`.
2563 private fun escape(out: FlatBuffer, c: Char, pos: Int): Int do
2564 if c == '\\
' or c == '[' or c == ']' or c == '(' or c == ')' or c == '{' or
2565 c == '}' or c == '#' or c == '"' or c == '\'' or c == '.' or c == '<' or
2566 c
== '>' or c
== '*' or c
== '+' or c
== '-' or c
== '_' or c
== '!' or
2567 c
== '`' or c
== '~' or c
== '^' then
2575 # Extract string found at end of fence opening.
2576 private fun meta_from_fence
: nullable Text do
2577 for i
in [0..chars
.length
[ do
2579 if c
!= ' ' and c
!= '`' and c
!= '~' then
2580 return substring_from
(i
).trim
2586 # Is `self` an unsafe HTML element?
2587 private fun is_html_unsafe
: Bool do return html_unsafe_tags
.has
(self.write_to_string
)
2589 # Is `self` a HRML block element?
2590 private fun is_html_block
: Bool do return html_block_tags
.has
(self.write_to_string
)
2592 # Is `self` a link prefix?
2593 private fun is_link_prefix
: Bool do return html_link_prefixes
.has
(self.write_to_string
)
2595 private fun html_unsafe_tags
: Array[String] do return once
["applet", "head", "body", "frame", "frameset", "iframe", "script", "object"]
2597 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"]
2599 private fun html_link_prefixes
: Array[String] do return once
["http", "https", "ftp", "ftps"]
2604 # Parse `self` as markdown and return the HTML representation
2606 # var md = "**Hello World!**"
2607 # var html = md.md_to_html
2608 # assert html == "<p><strong>Hello World!</strong></p>\n"
2609 fun md_to_html
: Writable do
2610 var processor
= new MarkdownProcessor
2611 return processor
.process
(self)