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 init do self.emitter
= new MarkdownEmitter(self)
138 # Process the mardown `input` string and return the processed output.
139 fun process
(input
: String): Writable do
146 var parent
= read_lines
(input
)
147 parent
.remove_surrounding_empty_lines
148 recurse
(parent
, false)
149 # output processed text
150 return emitter
.emit
(parent
.kind
)
153 # Split `input` string into `MDLines` and create a parent `MDBlock` with it.
154 private fun read_lines
(input
: String): MDBlock do
155 var block
= new MDBlock(new MDLocation(1, 1, 1, 1))
156 var value
= new FlatBuffer
162 while i
< input
.length
do
166 while not eol
and i
< input
.length
do
171 else if c
== '\t' then
172 var np
= pos
+ (4 - (pos
& 3))
185 var loc
= new MDLocation(line_pos
, 1, line_pos
, col_pos
)
186 var line
= new MDLine(loc
, value
.write_to_string
)
187 var is_link_ref
= check_link_ref
(line
)
189 if not is_link_ref
then block
.add_line line
195 # Check if line is a block link definition.
196 # Return `true` if line contains a valid link ref and save it into `link_refs`.
197 private fun check_link_ref
(line
: MDLine): Bool do
199 var is_link_ref
= false
200 var id
= new FlatBuffer
201 var link
= new FlatBuffer
202 var comment
= new FlatBuffer
204 if not line
.is_empty
and line
.leading
< 4 and line
.value
[line
.leading
] == '[' then
205 pos
= line
.leading
+ 1
206 pos
= md
.read_until
(id
, pos
, ']')
207 if not id
.is_empty
and pos
+ 2 < line
.value
.length
then
208 if line
.value
[pos
+ 1] == ':' then
210 pos
= md
.skip_spaces
(pos
)
211 if line
.value
[pos
] == '<' then
213 pos
= md
.read_until
(link
, pos
, '>')
216 pos
= md
.read_until
(link
, pos
, ' ', '\n')
218 if not link
.is_empty
then
219 pos
= md
.skip_spaces
(pos
)
220 if pos
> 0 and pos
< line
.value
.length
then
221 var c
= line
.value
[pos
]
222 if c
== '\"' or c
== '\'' or c == '(' then
225 pos = md.read_until(comment, pos, ')')
227 pos = md.read_until(comment, pos, c)
229 if pos > 0 then is_link_ref = true
238 if is_link_ref and not id.is_empty and not link.is_empty then
239 var lr = new LinkRef.with_title(link.write_to_string, comment.write_to_string)
240 add_link_ref(id.write_to_string, lr)
241 if comment.is_empty then last_link_ref = lr
244 comment = new FlatBuffer
245 if not line.is_empty and last_link_ref != null then
247 var c = line.value[pos]
248 if c == '\
"' or c == '\'' or c == '(' then
251 pos = md.read_until(comment, pos, ')')
253 pos = md.read_until(comment, pos, c)
256 if not comment.is_empty then last_link_ref.title = comment.write_to_string
258 if comment.is_empty then return false
264 # This list will be needed during output to expand links.
265 var link_refs: Map[String, LinkRef] = new HashMap[String, LinkRef]
267 # Last encountered link ref (for multiline definitions)
269 # Markdown allows link refs to be defined over two lines:
272 # [id]: http://example.com/longish/path/to/resource/here
273 # "Optional Title Here"
276 private var last_link_ref: nullable LinkRef = null
278 # Add a link ref to the list
279 fun add_link_ref(key: String, ref: LinkRef) do link_refs[key.to_lower] = ref
281 # Recursively split a `block`.
283 # The block is splitted according to the type of lines it contains.
284 # Some blocks can be splited again recursively like lists.
285 # The `in_list` mode is used to recurse on list and build
286 # nested paragraphs or code blocks.
287 fun recurse(root: MDBlock, in_list: Bool) do
288 var old_mode = self.in_list
289 var old_root = self.current_block
290 self.in_list = in_list
292 var line = root.first_line
293 while line != null and line.is_empty do
295 if line == null then return
300 while current_line != null do
301 line_kind(current_line.as(not null)).process(self)
303 self.in_list = old_mode
304 self.current_block = old_root
307 # Currently processed line.
308 # Used when visiting blocks with `recurse`.
309 var current_line: nullable MDLine = null is writable
311 # Currently processed block.
312 # Used when visiting blocks with `recurse`.
313 var current_block: nullable MDBlock = null is writable
315 # Is the current recursion in list mode?
316 # Used when visiting blocks with `recurse`
317 private var in_list = false
321 fun line_kind(md: MDLine): Line do
323 var leading = md.leading
324 var trailing = md.trailing
325 if md.is_empty then return new LineEmpty
326 if md.leading > 3 then return new LineCode
327 if value[leading] == '#' then return new LineHeadline
328 if value[leading] == '>' then return new LineBlockquote
331 if value.length - leading - trailing > 2 then
332 if value[leading] == '`' and md.count_chars_start('`') >= 3 then
335 if value[leading] == '~' and md.count_chars_start('~') >= 3 then
341 if value.length - leading - trailing > 2 and
342 (value[leading] == '*' or value[leading] == '-' or value[leading] == '_') then
343 if md.count_chars(value[leading]) >= 3 then
348 if value.length - leading >= 2 and value[leading + 1] == ' ' then
349 var c = value[leading]
350 if c == '*' or c == '-' or c == '+' then return new LineUList
353 if value.length - leading >= 3 and value[leading].is_digit then
355 while i < value.length and value[i].is_digit do i += 1
356 if i + 1 < value.length and value[i] == '.' and value[i + 1] == ' ' then
361 if value[leading] == '<' and md.check_html then return new LineXML
364 if next != null and not next.is_empty then
365 if next.count_chars('=') > 0 then
366 return new LineHeadline1
368 if next.count_chars('-') > 0 then
369 return new LineHeadline2
375 # Get the token kind at `pos`.
376 fun token_at(text: Text, pos: Int): Token do
388 if pos + 1 < text.length then
393 if pos + 2 < text.length then
399 var loc = new MDLocation(
400 current_loc.line_start,
401 current_loc.column_start + pos,
402 current_loc.line_start,
403 current_loc.column_start + pos)
407 if c0 != ' ' or c2 != ' ' then
408 return new TokenStrongStar(loc, pos, c)
410 return new TokenEmStar(loc, pos, c)
413 if c0 != ' ' or c1 != ' ' then
414 return new TokenEmStar(loc, pos, c)
416 return new TokenNone(loc, pos, c)
418 else if c == '_' then
420 if c0 != ' ' or c2 != ' 'then
421 return new TokenStrongUnderscore(loc, pos, c)
423 return new TokenEmUnderscore(loc, pos, c)
427 if (c0.is_letter or c0.is_digit) and c0 != '_' and
428 (c1.is_letter or c1.is_digit) then
429 return new TokenNone(loc, pos, c)
431 return new TokenEmUnderscore(loc, pos, c)
434 if c0 != ' ' or c1 != ' ' then
435 return new TokenEmUnderscore(loc, pos, c)
437 return new TokenNone(loc, pos, c)
439 else if c == '!' then
440 if c1 == '[' then return new TokenImage(loc, pos, c)
441 return new TokenNone(loc, pos, c)
442 else if c == '[' then
443 return new TokenLink(loc, pos, c)
444 else if c == ']' then
445 return new TokenNone(loc, pos, c)
446 else if c == '`' then
448 return new TokenCodeDouble(loc, pos, c)
450 return new TokenCodeSingle(loc, pos, c)
452 else if c == '\\' then
453 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
454 return new TokenEscape(loc
, pos
, c
)
456 return new TokenNone(loc
, pos
, c
)
458 else if c
== '<' then
459 return new TokenHTML(loc
, pos
, c
)
460 else if c
== '&' then
461 return new TokenEntity(loc
, pos
, c
)
464 if c
== '~' and c1
== '~' then
465 return new TokenStrike(loc
, pos
, c
)
468 return new TokenNone(loc
, pos
, c
)
472 # Find the position of a `token` in `self`.
473 fun find_token
(text
: Text, start
: Int, token
: Token): Int do
475 while pos
< text
.length
do
476 if token_at
(text
, pos
).is_same_type
(token
) then
484 # Location used for next parsed token.
486 # This location can be changed by the emitter to adjust with `\n` found
488 private fun current_loc
: MDLocation do return emitter
.current_loc
491 # Emit output corresponding to blocks content.
493 # Blocks are created by a previous pass in `MarkdownProcessor`.
494 # The emitter use a `Decorator` to select the output format.
495 class MarkdownEmitter
497 # Kind of processor used for parsing.
498 type PROCESSOR: MarkdownProcessor
500 # Processor containing link refs.
501 var processor
: PROCESSOR
503 # Kind of decorator used for decoration.
504 type DECORATOR: Decorator
506 # Decorator used for output.
507 # Default is `HTMLDecorator`
508 var decorator
: DECORATOR is writable, lazy
do
509 return new HTMLDecorator
512 # Create a new `MarkdownEmitter` using a custom `decorator`.
513 init with_decorator
(processor
: PROCESSOR, decorator
: DECORATOR) do
515 self.decorator
= decorator
518 # Output `block` using `decorator` in the current buffer.
519 fun emit
(block
: Block): Text do
520 var buffer
= push_buffer
526 # Output the content of `block`.
527 fun emit_in
(block
: Block) do block
.emit_in
(self)
529 # Transform and emit mardown text
530 fun emit_text
(text
: Text) do emit_text_until
(text
, 0, null)
532 # Transform and emit mardown text starting at `start` and
533 # until a token with the same type as `token` is found.
534 # Go until the end of `text` if `token` is null.
535 fun emit_text_until
(text
: Text, start
: Int, token
: nullable Token): Int do
536 var old_text
= current_text
537 var old_pos
= current_pos
540 while current_pos
< text
.length
do
541 if text
[current_pos
] == '\n' then
542 current_loc
.line_start
+= 1
543 current_loc
.column_start
= -current_pos
545 var mt
= processor
.token_at
(text
, current_pos
)
546 if (token
!= null and not token
isa TokenNone) and
547 (mt
.is_same_type
(token
) or
548 (token
isa TokenEmStar and mt
isa TokenStrongStar) or
549 (token
isa TokenEmUnderscore and mt
isa TokenStrongUnderscore)) then
555 current_text
= old_text
556 current_pos
= old_pos
560 # Currently processed position in `current_text`.
561 # Used when visiting inline production with `emit_text_until`.
562 private var current_pos
: Int = -1
564 # Currently processed text.
565 # Used when visiting inline production with `emit_text_until`.
566 private var current_text
: nullable Text = null
569 private var buffer_stack
= new List[FlatBuffer]
571 # Push a new buffer on the stack.
572 private fun push_buffer
: FlatBuffer do
573 var buffer
= new FlatBuffer
574 buffer_stack
.add buffer
578 # Pop the last buffer.
579 private fun pop_buffer
do buffer_stack
.pop
581 # Current output buffer.
582 private fun current_buffer
: FlatBuffer do
583 assert not buffer_stack
.is_empty
584 return buffer_stack
.last
588 private var loc_stack
= new List[MDLocation]
590 # Push a new MDLocation on the stack.
591 private fun push_loc
(location
: MDLocation) do loc_stack
.add location
593 # Pop the last buffer.
594 private fun pop_loc
: MDLocation do return loc_stack
.pop
596 # Current output buffer.
597 private fun current_loc
: MDLocation do
598 assert not loc_stack
.is_empty
599 return loc_stack
.last
602 # Append `e` to current buffer.
603 fun add
(e
: Writable) do
605 current_buffer
.append e
607 current_buffer
.append e
.write_to_string
611 # Append `c` to current buffer.
612 fun addc
(c
: Char) do add c
.to_s
614 # Append a "\n" line break.
619 # Links that are specified somewhere in the mardown document to be reused as shortcuts.
622 # [1]: http://example.com/ "Optional title"
629 # Optional link title
630 var title
: nullable String = null
632 # Is the link an abreviation?
633 var is_abbrev
= false
635 # Create a link with a title.
636 init with_title
(link
: String, title
: nullable String) do
642 # A `Decorator` is used to emit mardown into a specific format.
643 # Default decorator used is `HTMLDecorator`.
646 # Kind of emitter used for decoration.
647 type EMITTER: MarkdownEmitter
649 # Render a single plain char.
651 # Redefine this method to add special escaping for plain text.
652 fun add_char
(v
: EMITTER, c
: Char) do v
.addc c
654 # Render a ruler block.
655 fun add_ruler
(v
: EMITTER, block
: BlockRuler) is abstract
657 # Render a headline block with corresponding level.
658 fun add_headline
(v
: EMITTER, block
: BlockHeadline) is abstract
660 # Render a paragraph block.
661 fun add_paragraph
(v
: EMITTER, block
: BlockParagraph) is abstract
663 # Render a code or fence block.
664 fun add_code
(v
: EMITTER, block
: BlockCode) is abstract
666 # Render a blockquote.
667 fun add_blockquote
(v
: EMITTER, block
: BlockQuote) is abstract
669 # Render an unordered list.
670 fun add_unorderedlist
(v
: EMITTER, block
: BlockUnorderedList) is abstract
672 # Render an ordered list.
673 fun add_orderedlist
(v
: EMITTER, block
: BlockOrderedList) is abstract
675 # Render a list item.
676 fun add_listitem
(v
: EMITTER, block
: BlockListItem) is abstract
678 # Render an emphasis text.
679 fun add_em
(v
: EMITTER, text
: Text) is abstract
681 # Render a strong text.
682 fun add_strong
(v
: EMITTER, text
: Text) is abstract
684 # Render a strike text.
686 # Extended mode only (see `MarkdownProcessor::ext_mode`)
687 fun add_strike
(v
: EMITTER, text
: Text) is abstract
690 fun add_link
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
693 fun add_image
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
695 # Render an abbreviation.
696 fun add_abbr
(v
: EMITTER, name
: Text, comment
: Text) is abstract
698 # Render a code span reading from a buffer.
699 fun add_span_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
701 # Render a text and escape it.
702 fun append_value
(v
: EMITTER, value
: Text) is abstract
704 # Render code text from buffer and escape it.
705 fun append_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
707 # Render a character escape.
708 fun escape_char
(v
: EMITTER, char
: Char) is abstract
710 # Render a line break
711 fun add_line_break
(v
: EMITTER) is abstract
713 # Generate a new html valid id from a `String`.
714 fun strip_id
(txt
: String): String is abstract
716 # Found headlines during the processing labeled by their ids.
717 fun headlines
: ArrayMap[String, HeadLine] is abstract
720 # Class representing a markdown headline.
722 # Unique identifier of this headline.
725 # Text of the headline.
728 # Level of this headline.
730 # According toe the markdown specification, level must be in `[1..6]`.
734 # `Decorator` that outputs HTML.
738 redef var headlines
= new ArrayMap[String, HeadLine]
740 redef fun add_ruler
(v
, block
) do v
.add
"<hr/>\n"
742 redef fun add_headline
(v
, block
) do
744 var txt
= block
.block
.first_line
.value
745 var id
= strip_id
(txt
)
746 var lvl
= block
.depth
747 headlines
[id
] = new HeadLine(id
, txt
, lvl
)
749 v
.add
"<h{lvl} id=\"{id}\
">"
754 redef fun add_paragraph
(v
, block
) do
760 redef fun add_code
(v
, block
) do
761 if block
isa BlockFence and block
.meta
!= null then
762 v
.add
"<pre class=\"{block.meta.to_s}\
"><code>"
767 v
.add
"</code></pre>\n"
770 redef fun add_blockquote
(v
, block
) do
771 v
.add
"<blockquote>\n"
773 v
.add
"</blockquote>\n"
776 redef fun add_unorderedlist
(v
, block
) do
782 redef fun add_orderedlist
(v
, block
) do
788 redef fun add_listitem
(v
, block
) do
794 redef fun add_em
(v
, text
) do
800 redef fun add_strong
(v
, text
) do
806 redef fun add_strike
(v
, text
) do
812 redef fun add_image
(v
, link
, name
, comment
) do
814 append_value(v, link)
816 append_value(v, name)
818 if comment
!= null and not comment
.is_empty
then
820 append_value(v, comment)
826 redef fun add_link
(v
, link
, name
, comment
) do
828 append_value(v, link)
830 if comment
!= null and not comment
.is_empty
then
832 append_value(v, comment)
840 redef fun add_abbr
(v
, name
, comment
) do
841 v
.add
"<abbr title=\""
842 append_value(v, comment)
848 redef fun add_span_code
(v
, text
, from
, to
) do
850 append_code
(v
, text
, from
, to
)
854 redef fun add_line_break
(v
) do
858 redef fun append_value
(v
, text
) do for c
in text
do escape_char
(v
, c
)
860 redef fun escape_char
(v
, c
) do
863 else if c
== '<' then
865 else if c
== '>' then
867 else if c
== '"' then
869 else if c
== '\'' then
876 redef fun append_code(v, buffer, from, to) do
877 for i in [from..to[ do
881 else if c == '<' then
883 else if c == '>' then
891 redef fun strip_id(txt) do
893 var b = new FlatBuffer
898 if not c.is_letter and
900 not allowed_id_chars.has(c) then continue
906 # check for multiple id definitions
907 if headlines.has_key(key) then
910 while headlines.has_key(key) do
918 private var allowed_id_chars: Array[Char] = ['-', '_
', ':', '.']
921 # Location in a Markdown input.
924 # Starting line number (starting from 1).
927 # Starting column number (starting from 1).
928 var column_start: Int
930 # Stopping line number (starting from 1).
933 # Stopping column number (starting from 1).
936 redef fun to_s do return "{line_start},{column_start}--{line_end},{column_end}"
938 # Return a copy of `self`.
939 fun copy: MDLocation do
940 return new MDLocation(line_start, column_start, line_end, column_end)
944 # A block of markdown lines.
945 # A `MDBlock` can contains lines and/or sub-blocks.
948 # Position of `self` in the input.
949 var location: MDLocation
953 var kind: Block = new BlockNone(self) is writable
956 var first_line: nullable MDLine = null is writable
959 var last_line: nullable MDLine = null is writable
961 # First sub-block if any.
962 var first_block: nullable MDBlock = null is writable
964 # Last sub-block if any.
965 var last_block: nullable MDBlock = null is writable
967 # Previous block if any.
968 var prev: nullable MDBlock = null is writable
971 var next: nullable MDBlock = null is writable
973 # Does this block contain subblocks?
974 fun has_blocks: Bool do return first_block != null
977 fun count_blocks: Int do
979 var block = first_block
980 while block != null do
987 # Does this block contain lines?
988 fun has_lines: Bool do return first_line != null
991 fun count_lines: Int do
993 var line = first_line
994 while line != null do
1001 # Split `self` creating a new sub-block having `line` has `last_line`.
1002 fun split(line: MDLine): MDBlock do
1003 # location for new block
1004 var new_loc = new MDLocation(
1005 first_line.location.line_start,
1006 first_line.location.column_start,
1007 line.location.line_end,
1008 line.location.column_end)
1010 var block = new MDBlock(new_loc)
1011 block.first_line = first_line
1012 block.last_line = line
1013 first_line = line.next
1015 if first_line == null then
1018 first_line.prev = null
1019 # update current block loc
1020 location.line_start = first_line.location.line_start
1021 location.column_start = first_line.location.column_start
1023 if first_block == null then
1027 last_block.next = block
1033 # Add a `line` to this block.
1034 fun add_line(line: MDLine) do
1035 if last_line == null then
1039 last_line.next_empty = line.is_empty
1040 line.prev_empty = last_line.is_empty
1041 line.prev = last_line
1042 last_line.next = line
1047 # Remove `line` from this block.
1048 fun remove_line(line: MDLine) do
1049 if line.prev == null then
1050 first_line = line.next
1052 line.prev.next = line.next
1054 if line.next == null then
1055 last_line = line.prev
1057 line.next.prev = line.prev
1063 # Remove leading empty lines.
1064 fun remove_leading_empty_lines: Bool do
1065 var was_empty = false
1066 var line = first_line
1067 while line != null and line.is_empty do
1075 # Remove trailing empty lines.
1076 fun remove_trailing_empty_lines: Bool do
1077 var was_empty = false
1078 var line = last_line
1079 while line != null and line.is_empty do
1087 # Remove leading and trailing empty lines.
1088 fun remove_surrounding_empty_lines: Bool do
1089 var was_empty = false
1090 if remove_leading_empty_lines then was_empty = true
1091 if remove_trailing_empty_lines then was_empty = true
1095 # Remove list markers and up to 4 leading spaces.
1096 # Used to clean nested lists.
1097 fun remove_list_indent(v: MarkdownProcessor) do
1098 var line = first_line
1099 while line != null do
1100 if not line.is_empty then
1101 var kind = v.line_kind(line)
1102 if kind isa LineList then
1103 line.value = kind.extract_value(line)
1105 line.value = line.value.substring_from(line.leading.min(4))
1107 line.leading = line.process_leading
1113 # Collect block line text.
1115 var text = new FlatBuffer
1116 var line = first_line
1117 while line != null do
1118 if not line.is_empty then
1119 text.append line.text
1124 return text.write_to_string
1128 # Representation of a markdown block in the AST.
1129 # Each `Block` is linked to a `MDBlock` that contains mardown code.
1130 abstract class Block
1132 # The markdown block `self` is related to.
1135 # Output `self` using `v.decorator`.
1136 fun emit(v: MarkdownEmitter) do v.emit_in(self)
1138 # Emit the containts of `self`, lines or blocks.
1139 fun emit_in(v: MarkdownEmitter) do
1140 block.remove_surrounding_empty_lines
1141 if block.has_lines then
1148 # Emit lines contained in `block`.
1149 fun emit_lines(v: MarkdownEmitter) do
1150 var tpl = v.push_buffer
1151 var line = block.first_line
1152 while line != null do
1153 if not line.is_empty then
1154 v.add line.value.substring(line.leading, line.value.length - line.trailing)
1155 if line.trailing >= 2 then v.decorator.add_line_break(v)
1157 if line.next != null then
1166 # Emit sub-blocks contained in `block`.
1167 fun emit_blocks(v: MarkdownEmitter) do
1168 var block = self.block.first_block
1169 while block != null do
1170 v.push_loc(block.location)
1178 # A block without any markdown specificities.
1180 # Actually use the same implementation than `BlockCode`,
1181 # this class is only used for typing purposes.
1186 # A markdown blockquote.
1190 redef fun emit(v) do v.decorator.add_blockquote(v, self)
1192 # Remove blockquote markers.
1193 private fun remove_block_quote_prefix(block: MDBlock) do
1194 var line = block.first_line
1195 while line != null do
1196 if not line.is_empty then
1197 if line.value[line.leading] == '>' then
1198 var rem = line.leading + 1
1199 if line.leading + 1 < line.value.length and
1200 line.value[line.leading + 1] == ' ' then
1203 line.value = line.value.substring_from(rem)
1204 line.leading = line.process_leading
1212 # A markdown code block.
1216 # Number of char to skip at the beginning of the line.
1218 # Block code lines start at 4 spaces.
1219 protected var line_start = 4
1221 redef fun emit(v) do v.decorator.add_code(v, self)
1223 redef fun emit_lines(v) do
1224 var line = block.first_line
1225 while line != null do
1226 if not line.is_empty then
1227 v.decorator.append_code(v, line.value, line_start, line.value.length)
1235 # A markdown code-fence block.
1237 # Actually use the same implementation than `BlockCode`,
1238 # this class is only used for typing purposes.
1242 # Any string found after fence token.
1243 var meta: nullable Text
1245 # Fence code lines start at 0 spaces.
1246 redef var line_start = 0
1249 # A markdown headline.
1253 redef fun emit(v) do
1254 var loc = block.location.copy
1255 loc.column_start += start
1257 v.decorator.add_headline(v, self)
1261 private var start = 0
1263 # Depth of the headline used to determine the headline level.
1266 # Remove healine marks from lines contained in `self`.
1267 private fun transform_headline(block: MDBlock) do
1268 if depth > 0 then return
1270 var line = block.first_line
1271 if line.is_empty then return
1272 var start = line.leading
1273 while start < line.value.length and line.value[start] == '#' do
1277 while start
< line
.value
.length
and line
.value
[start
] == ' ' do
1280 if start
>= line
.value
.length
then
1281 line
.is_empty
= true
1283 var nend
= line
.value
.length
- line
.trailing
- 1
1284 while line
.value
[nend
] == '#' do nend
-= 1
1285 while line
.value
[nend
] == ' ' do nend
-= 1
1286 line
.value
= line
.value
.substring
(start
, nend
- start
+ 1)
1291 depth
= level
.min
(6)
1295 # A markdown list item block.
1299 redef fun emit
(v
) do v
.decorator
.add_listitem
(v
, self)
1302 # A markdown list block.
1303 # Can be either an ordered or unordered list, this class is mainly used to factorize code.
1304 abstract class BlockList
1307 # Split list block into list items sub-blocks.
1308 private fun init_block
(v
: MarkdownProcessor) do
1309 var line
= block
.first_line
1311 while line
!= null do
1312 var t
= v
.line_kind
(line
)
1313 if t
isa LineList or
1314 (not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1315 not (t
isa LineList))) then
1316 var sblock
= block
.split
(line
.prev
.as(not null))
1317 sblock
.kind
= new BlockListItem(sblock
)
1321 var sblock
= block
.split
(block
.last_line
.as(not null))
1322 sblock
.kind
= new BlockListItem(sblock
)
1325 # Expand list items as paragraphs if needed.
1326 private fun expand_paragraphs
(block
: MDBlock) do
1327 var outer
= block
.first_block
1328 var inner
: nullable MDBlock
1329 var has_paragraph
= false
1330 while outer
!= null and not has_paragraph
do
1331 if outer
.kind
isa BlockListItem then
1332 inner
= outer
.first_block
1333 while inner
!= null and not has_paragraph
do
1334 if inner
.kind
isa BlockParagraph then
1335 has_paragraph
= true
1342 if has_paragraph
then
1343 outer
= block
.first_block
1344 while outer
!= null do
1345 if outer
.kind
isa BlockListItem then
1346 inner
= outer
.first_block
1347 while inner
!= null do
1348 if inner
.kind
isa BlockNone then
1349 inner
.kind
= new BlockParagraph(inner
)
1360 # A markdown ordered list.
1361 class BlockOrderedList
1364 redef fun emit
(v
) do v
.decorator
.add_orderedlist
(v
, self)
1367 # A markdown unordred list.
1368 class BlockUnorderedList
1371 redef fun emit
(v
) do v
.decorator
.add_unorderedlist
(v
, self)
1374 # A markdown paragraph block.
1375 class BlockParagraph
1378 redef fun emit
(v
) do v
.decorator
.add_paragraph
(v
, self)
1385 redef fun emit
(v
) do v
.decorator
.add_ruler
(v
, self)
1388 # Xml blocks that can be found in markdown markup.
1392 redef fun emit_lines
(v
) do
1393 var line
= block
.first_line
1394 while line
!= null do
1395 if not line
.is_empty
then v
.add line
.value
1405 # Location of `self` in the original input.
1406 var location
: MDLocation
1408 # Text contained in this line.
1409 var value
: String is writable
1411 # Is this line empty?
1412 # Lines containing only spaces are considered empty.
1413 var is_empty
: Bool = true is writable
1415 # Previous line in `MDBlock` or null if first line.
1416 var prev
: nullable MDLine = null is writable
1418 # Next line in `MDBlock` or null if last line.
1419 var next
: nullable MDLine = null is writable
1421 # Is the previous line empty?
1422 var prev_empty
: Bool = false is writable
1424 # Is the next line empty?
1425 var next_empty
: Bool = false is writable
1427 # Initialize a new MDLine from its string value
1429 self.leading
= process_leading
1430 if leading
!= value
.length
then
1431 self.is_empty
= false
1432 self.trailing
= process_trailing
1436 # Set `value` as an empty String and update `leading`, `trailing` and is_`empty`.
1442 if prev
!= null then prev
.next_empty
= true
1443 if next
!= null then next
.prev_empty
= true
1446 # Number or leading spaces on this line.
1447 var leading
: Int = 0 is writable
1449 # Compute `leading` depending on `value`.
1450 fun process_leading
: Int do
1452 var value
= self.value
1453 while count
< value
.length
and value
[count
] == ' ' do count
+= 1
1454 if leading
== value
.length
then clear
1458 # Number of trailing spaces on this line.
1459 var trailing
: Int = 0 is writable
1461 # Compute `trailing` depending on `value`.
1462 fun process_trailing
: Int do
1464 var value
= self.value
1465 while value
[value
.length
- count
- 1] == ' ' do
1471 # Count the amount of `ch` in this line.
1472 # Return A value > 0 if this line only consists of `ch` end spaces.
1473 fun count_chars
(ch
: Char): Int do
1489 # Count the amount of `ch` at the start of this line ignoring spaces.
1490 fun count_chars_start
(ch
: Char): Int do
1505 # Last XML line if any.
1506 private var xml_end_line
: nullable MDLine = null
1508 # Does `value` contains valid XML markup?
1509 private fun check_html
: Bool do
1510 var tags
= new Array[String]
1511 var tmp
= new FlatBuffer
1513 if pos
+ 1 < value
.length
and value
[pos
+ 1] == '!' then
1514 if read_xml_comment
(self, pos
) > 0 then return true
1516 pos
= value
.read_xml
(tmp
, pos
, false)
1520 if not tag
.is_html_block
then
1528 var line
: nullable MDLine = self
1529 while line
!= null do
1530 while pos
< line
.value
.length
and line
.value
[pos
] != '<' do
1533 if pos
>= line
.value
.length
then
1534 if pos
- 2 >= 0 and line
.value
[pos
- 2] == '/' then
1536 if tags
.is_empty
then
1544 tmp
= new FlatBuffer
1545 var new_pos
= line
.value
.read_xml
(tmp
, pos
, false)
1548 if tag
.is_html_block
and not tag
== "hr" then
1549 if tmp
[1] == '/' then
1550 if tags
.last
!= tag
then
1558 if tags
.is_empty
then
1568 return tags
.is_empty
1573 # Read a XML comment.
1574 # Used by `check_html`.
1575 private fun read_xml_comment
(first_line
: MDLine, start
: Int): Int do
1576 var line
: nullable MDLine = first_line
1577 if start
+ 3 < line
.value
.length
then
1578 if line
.value
[2] == '-' and line
.value
[3] == '-' then
1580 while line
!= null do
1581 while pos
< line
.value
.length
and line
.value
[pos
] != '-' do
1584 if pos
== line
.value
.length
then
1588 if pos
+ 2 < line
.value
.length
then
1589 if line
.value
[pos
+ 1] == '-' and line
.value
[pos
+ 2] == '>' then
1590 first_line
.xml_end_line
= line
1602 # Extract the text of `self` without leading and trailing.
1603 fun text
: String do return value
.substring
(leading
, value
.length
- trailing
)
1610 # See `MarkdownProcessor::recurse`.
1611 fun process
(v
: MarkdownProcessor) is abstract
1614 # An empty markdown line.
1618 redef fun process
(v
) do
1619 v
.current_line
= v
.current_line
.next
1623 # A non-specific markdown construction.
1624 # Mainly used as part of another line construct such as paragraphs or lists.
1628 redef fun process
(v
) do
1629 var line
= v
.current_line
1631 var was_empty
= line
.prev_empty
1632 while line
!= null and not line
.is_empty
do
1633 var t
= v
.line_kind
(line
)
1634 if (v
.in_list
or v
.ext_mode
) and t
isa LineList then
1637 if v
.ext_mode
and (t
isa LineCode or t
isa LineFence) then
1640 if t
isa LineHeadline or t
isa LineHeadline1 or t
isa LineHeadline2 or
1641 t
isa LineHR or t
isa LineBlockquote or t
isa LineXML then
1647 if line
!= null and not line
.is_empty
then
1648 var block
= v
.current_block
.split
(line
.prev
.as(not null))
1649 if v
.in_list
and not was_empty
then
1650 block
.kind
= new BlockNone(block
)
1652 block
.kind
= new BlockParagraph(block
)
1654 v
.current_block
.remove_leading_empty_lines
1657 if line
!= null then
1658 block
= v
.current_block
.split
(line
)
1660 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1662 if v
.in_list
and (line
== null or not line
.is_empty
) and not was_empty
then
1663 block
.kind
= new BlockNone(block
)
1665 block
.kind
= new BlockParagraph(block
)
1667 v
.current_block
.remove_leading_empty_lines
1669 v
.current_line
= v
.current_block
.first_line
1673 # A line of markdown code.
1677 redef fun process
(v
) do
1678 var line
= v
.current_line
1680 while line
!= null and (line
.is_empty
or v
.line_kind
(line
) isa LineCode) do
1683 # split at block end line
1685 if line
!= null then
1686 block
= v
.current_block
.split
(line
.prev
.as(not null))
1688 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1690 block
.kind
= new BlockCode(block
)
1691 block
.remove_surrounding_empty_lines
1692 v
.current_line
= v
.current_block
.first_line
1696 # A line of raw XML.
1700 redef fun process
(v
) do
1701 var line
= v
.current_line
1702 var prev
= line
.prev
1703 if prev
!= null then v
.current_block
.split
(prev
)
1704 var block
= v
.current_block
.split
(line
.xml_end_line
.as(not null))
1705 block
.kind
= new BlockXML(block
)
1706 v
.current_block
.remove_leading_empty_lines
1707 v
.current_line
= v
.current_block
.first_line
1711 # A markdown blockquote line.
1712 class LineBlockquote
1715 redef fun process
(v
) do
1716 var line
= v
.current_line
1718 while line
!= null do
1719 if not line
.is_empty
and (line
.prev_empty
and
1720 line
.leading
== 0 and
1721 not v
.line_kind
(line
) isa LineBlockquote) then break
1726 if line
!= null then
1727 block
= v
.current_block
.split
(line
.prev
.as(not null))
1729 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1731 var kind
= new BlockQuote(block
)
1733 block
.remove_surrounding_empty_lines
1734 kind
.remove_block_quote_prefix
(block
)
1735 v
.current_line
= line
1736 v
.recurse
(block
, false)
1737 v
.current_line
= v
.current_block
.first_line
1741 # A markdown ruler line.
1745 redef fun process
(v
) do
1746 var line
= v
.current_line
1747 if line
.prev
!= null then v
.current_block
.split
(line
.prev
.as(not null))
1748 var block
= v
.current_block
.split
(line
.as(not null))
1749 block
.kind
= new BlockRuler(block
)
1750 v
.current_block
.remove_leading_empty_lines
1751 v
.current_line
= v
.current_block
.first_line
1755 # A markdown fence code line.
1759 redef fun process
(v
) do
1761 var line
= v
.current_line
.next
1762 while line
!= null do
1763 if v
.line_kind
(line
) isa LineFence then break
1766 if line
!= null then
1771 if line
!= null then
1772 block
= v
.current_block
.split
(line
.prev
.as(not null))
1774 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1776 block
.remove_surrounding_empty_lines
1777 var meta
= block
.first_line
.value
.meta_from_fence
1778 block
.kind
= new BlockFence(block
, meta
)
1779 block
.first_line
.clear
1780 var last
= block
.last_line
1781 if last
!= null and v
.line_kind
(last
) isa LineFence then
1782 block
.last_line
.clear
1784 block
.remove_surrounding_empty_lines
1785 v
.current_line
= line
1789 # A markdown headline.
1793 redef fun process
(v
) do
1794 var line
= v
.current_line
1795 var lprev
= line
.prev
1796 if lprev
!= null then v
.current_block
.split
(lprev
)
1797 var block
= v
.current_block
.split
(line
.as(not null))
1798 var kind
= new BlockHeadline(block
)
1800 kind
.transform_headline
(block
)
1801 v
.current_block
.remove_leading_empty_lines
1802 v
.current_line
= v
.current_block
.first_line
1806 # A markdown headline of level 1.
1810 redef fun process
(v
) do
1811 var line
= v
.current_line
1812 var lprev
= line
.prev
1813 if lprev
!= null then v
.current_block
.split
(lprev
)
1815 var block
= v
.current_block
.split
(line
.as(not null))
1816 var kind
= new BlockHeadline(block
)
1818 kind
.transform_headline
(block
)
1820 v
.current_block
.remove_leading_empty_lines
1821 v
.current_line
= v
.current_block
.first_line
1825 # A markdown headline of level 2.
1829 redef fun process
(v
) do
1830 var line
= v
.current_line
1831 var lprev
= line
.prev
1832 if lprev
!= null then v
.current_block
.split
(lprev
)
1834 var block
= v
.current_block
.split
(line
.as(not null))
1835 var kind
= new BlockHeadline(block
)
1837 kind
.transform_headline
(block
)
1839 v
.current_block
.remove_leading_empty_lines
1840 v
.current_line
= v
.current_block
.first_line
1844 # A markdown list line.
1845 # Mainly used to factorize code between ordered and unordered lists.
1846 abstract class LineList
1849 redef fun process
(v
) do
1850 var line
= v
.current_line
1852 while line
!= null do
1853 var t
= v
.line_kind
(line
)
1854 if not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1855 not t
isa LineList) then break
1860 if line
!= null then
1861 list
= v
.current_block
.split
(line
.prev
.as(not null))
1863 list
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1865 var kind
= block_kind
(list
)
1867 list
.first_line
.prev_empty
= false
1868 list
.last_line
.next_empty
= false
1869 list
.remove_surrounding_empty_lines
1870 list
.first_line
.prev_empty
= false
1871 list
.last_line
.next_empty
= false
1873 var block
= list
.first_block
1874 while block
!= null do
1875 block
.remove_list_indent
(v
)
1876 v
.recurse
(block
, true)
1879 kind
.expand_paragraphs
(list
)
1880 v
.current_line
= line
1883 # Create a new block kind based on this line.
1884 protected fun block_kind
(block
: MDBlock): BlockList is abstract
1886 # Extract string value from `MDLine`.
1887 protected fun extract_value
(line
: MDLine): String is abstract
1890 # An ordered list line.
1894 redef fun block_kind
(block
) do return new BlockOrderedList(block
)
1896 redef fun extract_value
(line
) do
1897 return line
.value
.substring_from
(line
.value
.index_of
('.') + 2)
1901 # An unordered list line.
1905 redef fun block_kind
(block
) do return new BlockUnorderedList(block
)
1907 redef fun extract_value
(line
) do
1908 return line
.value
.substring_from
(line
.leading
+ 2)
1912 # A token represent a character in the markdown input.
1913 # Some tokens have a specific markup behaviour that is handled here.
1914 abstract class Token
1916 # Location of `self` in the original input.
1917 var location
: MDLocation
1919 # Position of `self` in input independant from lines.
1922 # Character found at `pos` in the markdown input.
1925 # Output that token using `MarkdownEmitter::decorator`.
1926 fun emit
(v
: MarkdownEmitter) do v
.decorator
.add_char
(v
, char
)
1929 # A token without a specific meaning.
1934 # An emphasis token.
1935 abstract class TokenEm
1938 redef fun emit
(v
) do
1939 var tmp
= v
.push_buffer
1940 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 1, self)
1943 v
.decorator
.add_em
(v
, tmp
)
1951 # An emphasis star token.
1956 # An emphasis underscore token.
1957 class TokenEmUnderscore
1962 abstract class TokenStrong
1965 redef fun emit
(v
) do
1966 var tmp
= v
.push_buffer
1967 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
1970 v
.decorator
.add_strong
(v
, tmp
)
1971 v
.current_pos
= b
+ 1
1978 # A strong star token.
1979 class TokenStrongStar
1983 # A strong underscore token.
1984 class TokenStrongUnderscore
1989 # This class is mainly used to factorize work between single and double quoted span codes.
1990 abstract class TokenCode
1993 redef fun emit
(v
) do
1994 var a
= pos
+ next_pos
+ 1
1995 var b
= v
.processor
.find_token
(v
.current_text
.as(not null), a
, self)
1997 v
.current_pos
= b
+ next_pos
1998 while a
< b
and v
.current_text
[a
] == ' ' do a
+= 1
2000 while v
.current_text
[b
- 1] == ' ' do b
-= 1
2001 v
.decorator
.add_span_code
(v
, v
.current_text
.as(not null), a
, b
)
2008 private fun next_pos
: Int is abstract
2011 # A span code token.
2012 class TokenCodeSingle
2015 redef fun next_pos
do return 0
2018 # A doubled span code token.
2019 class TokenCodeDouble
2022 redef fun next_pos
do return 1
2025 # A link or image token.
2026 # This class is mainly used to factorize work between images and links.
2027 abstract class TokenLinkOrImage
2031 var link
: nullable Text = null
2034 var name
: nullable Text = null
2037 var comment
: nullable Text = null
2039 # Is the link construct an abbreviation?
2040 var is_abbrev
= false
2042 redef fun emit
(v
) do
2043 var tmp
= new FlatBuffer
2044 var b
= check_link
(v
, tmp
, pos
, self)
2053 # Emit the hyperlink as link or image.
2054 private fun emit_hyper
(v
: MarkdownEmitter) is abstract
2056 # Check if the link is a valid link.
2057 private fun check_link
(v
: MarkdownEmitter, out
: FlatBuffer, start
: Int, token
: Token): Int do
2058 var md
= v
.current_text
2060 if token
isa TokenLink then
2065 var tmp
= new FlatBuffer
2066 pos
= md
.read_md_link_id
(tmp
, pos
)
2067 if pos
< start
then return -1
2071 pos
= md
.skip_spaces
(pos
)
2073 var tid
= name
.write_to_string
.to_lower
2074 if v
.processor
.link_refs
.has_key
(tid
) then
2075 var lr
= v
.processor
.link_refs
[tid
]
2076 is_abbrev
= lr
.is_abbrev
2083 else if md
[pos
] == '(' then
2085 pos
= md
.skip_spaces
(pos
)
2086 if pos
< start
then return -1
2087 tmp
= new FlatBuffer
2088 var use_lt
= md
[pos
] == '<'
2090 pos
= md
.read_until
(tmp
, pos
+ 1, '>')
2092 pos
= md
.read_md_link
(tmp
, pos
)
2094 if pos
< start
then return -1
2095 if use_lt
then pos
+= 1
2096 link
= tmp
.write_to_string
2097 if md
[pos
] == ' ' then
2098 pos
= md
.skip_spaces
(pos
)
2099 if pos
> start
and md
[pos
] == '"' then
2101 tmp
= new FlatBuffer
2102 pos
= md
.read_until
(tmp
, pos
, '"')
2103 if pos
< start
then return -1
2104 comment
= tmp
.write_to_string
2106 pos
= md
.skip_spaces
(pos
)
2107 if pos
== -1 then return -1
2110 if pos
< start
then return -1
2111 if md
[pos
] != ')' then return -1
2112 else if md
[pos
] == '[' then
2114 tmp
= new FlatBuffer
2115 pos
= md
.read_raw_until
(tmp
, pos
, ']')
2116 if pos
< start
then return -1
2118 if tmp
.length
> 0 then
2123 var tid
= id
.write_to_string
.to_lower
2124 if v
.processor
.link_refs
.has_key
(tid
) then
2125 var lr
= v
.processor
.link_refs
[tid
]
2130 var tid
= name
.write_to_string
.replace
("\n", " ").to_lower
2131 if v
.processor
.link_refs
.has_key
(tid
) then
2132 var lr
= v
.processor
.link_refs
[tid
]
2140 if link
== null then return -1
2145 # A markdown link token.
2147 super TokenLinkOrImage
2149 redef fun emit_hyper
(v
) do
2150 if is_abbrev
and comment
!= null then
2151 v
.decorator
.add_abbr
(v
, name
.as(not null), comment
.as(not null))
2153 v
.decorator
.add_link
(v
, link
.as(not null), name
.as(not null), comment
)
2158 # A markdown image token.
2160 super TokenLinkOrImage
2162 redef fun emit_hyper
(v
) do
2163 v
.decorator
.add_image
(v
, link
.as(not null), name
.as(not null), comment
)
2171 redef fun emit
(v
) do
2172 var tmp
= new FlatBuffer
2173 var b
= check_html
(v
, tmp
, v
.current_text
.as(not null), v
.current_pos
)
2178 v
.decorator
.escape_char
(v
, char
)
2182 # Is the HTML valid?
2183 # Also take care of link and mailto shortcuts.
2184 private fun check_html
(v
: MarkdownEmitter, out
: FlatBuffer, md
: Text, start
: Int): Int do
2185 # check for auto links
2186 var tmp
= new FlatBuffer
2187 var pos
= md
.read_until
(tmp
, start
+ 1, ':', ' ', '>', '\n')
2188 if pos
!= -1 and md
[pos
] == ':' and tmp
.is_link_prefix
then
2189 pos
= md
.read_until
(tmp
, pos
, '>')
2191 var link
= tmp
.write_to_string
2192 v
.decorator
.add_link
(v
, link
, link
, null)
2196 # TODO check for mailto
2197 # check for inline html
2198 if start
+ 2 < md
.length
then
2199 return md
.read_xml
(out
, start
, true)
2205 # An HTML entity token.
2209 redef fun emit
(v
) do
2210 var tmp
= new FlatBuffer
2211 var b
= check_entity
(tmp
, v
.current_text
.as(not null), pos
)
2216 v
.decorator
.escape_char
(v
, char
)
2220 # Is the entity valid?
2221 private fun check_entity
(out
: FlatBuffer, md
: Text, start
: Int): Int do
2222 var pos
= md
.read_until
(out
, start
, ';')
2223 if pos
< 0 or out
.length
< 3 then
2226 if out
[1] == '#' then
2227 if out
[2] == 'x' or out
[2] == 'X' then
2228 if out
.length
< 4 then return -1
2229 for i
in [3..out
.length
[ do
2231 if (c
< '0' or c
> '9') and (c
< 'a' and c
> 'f') and (c
< 'A' and c
> 'F') then
2236 for i
in [2..out
.length
[ do
2238 if c
< '0' or c
> '9' then return -1
2243 for i
in [1..out
.length
[ do
2245 if not c
.is_digit
and not c
.is_letter
then return -1
2248 # TODO check entity is valid
2249 # if out.is_entity then
2259 # A markdown escape token.
2263 redef fun emit
(v
) do
2265 v
.addc v
.current_text
[v
.current_pos
]
2269 # A markdown strike token.
2271 # Extended mode only (see `MarkdownProcessor::ext_mode`)
2275 redef fun emit
(v
) do
2276 var tmp
= v
.push_buffer
2277 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2280 v
.decorator
.add_strike
(v
, tmp
)
2281 v
.current_pos
= b
+ 1
2290 # Get the position of the next non-space character.
2291 private fun skip_spaces
(start
: Int): Int do
2293 while pos
> -1 and pos
< length
and (self[pos
] == ' ' or self[pos
] == '\n') do
2296 if pos
< length
then return pos
2300 # Read `self` until `nend` and append it to the `out` buffer.
2301 # Escape markdown special chars.
2302 private fun read_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2304 while pos
< length
do
2306 if c
== '\\' and pos
+ 1 < length
then
2307 pos
= escape
(out
, self[pos
+ 1], pos
)
2309 var end_reached
= false
2316 if end_reached
then break
2321 if pos
== length
then return -1
2325 # Read `self` as raw text until `nend` and append it to the `out` buffer.
2326 # No escape is made.
2327 private fun read_raw_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2329 while pos
< length
do
2331 var end_reached
= false
2338 if end_reached
then break
2342 if pos
== length
then return -1
2346 # Read `self` as XML until `to` and append it to the `out` buffer.
2347 # Escape HTML special chars.
2348 private fun read_xml_until
(out
: FlatBuffer, from
: Int, to
: Char...): Int do
2351 var str_char
: nullable Char = null
2352 while pos
< length
do
2358 if pos
< length
then
2364 if c
== str_char
then
2371 if c
== '"' or c
== '\'' then
2376 var end_reached = false
2377 for n in [0..to.length[ do
2383 if end_reached then break
2388 if pos == length then return -1
2392 # Read `self` as XML and append it to the `out` buffer.
2393 # Safe mode can be activated to limit reading to valid xml.
2394 private fun read_xml(out: FlatBuffer, start: Int, safe_mode: Bool): Int do
2397 var is_close_tag = false
2398 if start + 1 >= length then return -1
2399 if self[start + 1] == '/' then
2402 else if self[start + 1] == '!' then
2406 is_close_tag = false
2410 var tmp = new FlatBuffer
2411 pos = read_xml_until(tmp, pos, ' ', '/', '>')
2412 if pos == -1 then return -1
2413 var tag = tmp.write_to_string.trim.to_lower
2414 if not tag.is_valid_html_tag then
2417 else if tag.is_html_unsafe then
2420 if is_close_tag then out.add '/'
2424 if is_close_tag then out.add '/'
2429 if is_close_tag then out.add '/'
2430 pos = read_xml_until(out, pos, ' ', '/', '>')
2432 if pos == -1 then return -1
2433 pos = read_xml_until(out, pos, '/', '>')
2434 if pos == -1 then return -1
2435 if self[pos] == '/' then
2437 pos = self.read_xml_until(out, pos + 1, '>')
2438 if pos == -1 then return -1
2440 if self[pos] == '>' then
2451 # Read a markdown link address and append it to the `out` buffer.
2452 private fun read_md_link(out: FlatBuffer, start: Int): Int do
2455 while pos < length do
2457 if c == '\\
' and pos + 1 < length then
2458 pos = escape(out, self[pos + 1], pos)
2460 var end_reached = false
2463 else if c == ' ' then
2464 if counter == 1 then end_reached = true
2465 else if c == ')' then
2467 if counter == 0 then end_reached = true
2469 if end_reached then break
2474 if pos == length then return -1
2478 # Read a markdown link text and append it to the `out` buffer.
2479 private fun read_md_link_id(out: FlatBuffer, start: Int): Int do
2482 while pos < length do
2484 var end_reached = false
2488 else if c == ']' then
2490 if counter == 0 then
2498 if end_reached then break
2501 if pos == length then return -1
2505 # Extract the XML tag name from a XML tag.
2506 private fun xml_tag: String do
2507 var tpl = new FlatBuffer
2509 if pos < length and self[1] == '/' then pos += 1
2510 while pos < length - 1 and (self[pos].is_digit or self[pos].is_letter) do
2514 return tpl.write_to_string.to_lower
2517 private fun is_valid_html_tag: Bool do
2518 if is_empty then return false
2520 if not c.is_alpha then return false
2525 # Read and escape the markdown contained in `self`.
2526 private fun escape(out: FlatBuffer, c: Char, pos: Int): Int do
2527 if c == '\\
' or c == '[' or c == ']' or c == '(' or c == ')' or c == '{' or
2528 c == '}' or c == '#' or c == '"' or c == '\'' or c == '.' or c == '<' or
2529 c
== '>' or c
== '*' or c
== '+' or c
== '-' or c
== '_' or c
== '!' or
2530 c
== '`' or c
== '~' or c
== '^' then
2538 # Extract string found at end of fence opening.
2539 private fun meta_from_fence
: nullable Text do
2540 for i
in [0..chars
.length
[ do
2542 if c
!= ' ' and c
!= '`' and c
!= '~' then
2543 return substring_from
(i
).trim
2549 # Is `self` an unsafe HTML element?
2550 private fun is_html_unsafe
: Bool do return html_unsafe_tags
.has
(self.write_to_string
)
2552 # Is `self` a HRML block element?
2553 private fun is_html_block
: Bool do return html_block_tags
.has
(self.write_to_string
)
2555 # Is `self` a link prefix?
2556 private fun is_link_prefix
: Bool do return html_link_prefixes
.has
(self.write_to_string
)
2558 private fun html_unsafe_tags
: Array[String] do return once
["applet", "head", "body", "frame", "frameset", "iframe", "script", "object"]
2560 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"]
2562 private fun html_link_prefixes
: Array[String] do return once
["http", "https", "ftp", "ftps"]
2567 # Parse `self` as markdown and return the HTML representation
2569 # var md = "**Hello World!**"
2570 # var html = md.md_to_html
2571 # assert html == "<p><strong>Hello World!</strong></p>\n"
2572 fun md_to_html
: Writable do
2573 var processor
= new MarkdownProcessor
2574 return processor
.process
(self)