1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
20 # Parse a markdown string and split it in blocks.
22 # Blocks are then outputed by an `MarkdownEmitter`.
26 # var proc = new MarkdownProcessor
27 # var html = proc.process("**Hello World!**")
28 # assert html == "<p><strong>Hello World!</strong></p>\n"
30 # SEE: `String::md_to_html` for a shortcut.
31 class MarkdownProcessor
33 # `MarkdownEmitter` used for ouput.
34 var emitter
: MarkdownEmitter is noinit
, protected writable
36 # Work in extended mode (default).
38 # Behavior changes when using extended mode:
40 # * Lists and code blocks end a paragraph
42 # In normal markdown the following:
46 # * and this is not a list
52 # <p>This is a paragraph
53 # * and this is not a list</p>
56 # When using extended mode this changes to:
59 # <p>This is a paragraph</p>
61 # <li>and this is not a list</li>
65 # * Fences code blocks
67 # If you don't want to indent your all your code with 4 spaces,
68 # you can wrap your code in ``` ``` ``` or `~~~`.
74 # print "Hello World!"
80 # If you want to use syntax highlighting tools, most of them need to know what kind
81 # of language they are highlighting.
82 # You can add an optional language identifier after the fence declaration to output
83 # it in the HTML render.
88 # print "# Hello World!".md_to_html
94 # <pre class="nit"><code>import markdown
96 # print "Hello World!".md_to_html
100 # * Underscores (Emphasis)
102 # Underscores in the middle of a word like:
108 # normally produces this:
111 # <p>Con<em>cat</em>this</p>
114 # With extended mode they don't result in emphasis.
117 # <p>Con_cat_this</p>
122 # Like in [GFM](https://help.github.com/articles/github-flavored-markdown),
123 # strikethrought span is marked with `~~`.
132 # <del>Mistaken text.</del>
136 # Disable attaching MDLocation to Tokens
138 # Locations are useful for some tools but they may
139 # cause an important time and space overhead.
142 var no_location
= false is writable
144 init do self.emitter
= new MarkdownEmitter(self)
146 # Process the mardown `input` string and return the processed output.
147 fun process
(input
: String): Writable do
154 var parent
= read_lines
(input
)
155 parent
.remove_surrounding_empty_lines
156 recurse
(parent
, false)
157 # output processed text
158 return emitter
.emit
(parent
.kind
)
161 # Split `input` string into `MDLines` and create a parent `MDBlock` with it.
162 private fun read_lines
(input
: String): MDBlock do
163 var block
= new MDBlock(new MDLocation(1, 1, 1, 1))
164 var value
= new FlatBuffer
170 while i
< input
.length
do
174 while not eol
and i
< input
.length
do
179 else if c
== '\r' then
180 else if c
== '\t' then
181 var np
= pos
+ (4 - (pos
& 3))
194 var loc
= new MDLocation(line_pos
, 1, line_pos
, col_pos
)
195 var line
= new MDLine(loc
, value
.write_to_string
)
196 var is_link_ref
= check_link_ref
(line
)
198 if not is_link_ref
then block
.add_line line
204 # Check if line is a block link definition.
205 # Return `true` if line contains a valid link ref and save it into `link_refs`.
206 private fun check_link_ref
(line
: MDLine): Bool do
208 var is_link_ref
= false
209 var id
= new FlatBuffer
210 var link
= new FlatBuffer
211 var comment
= new FlatBuffer
213 if not line
.is_empty
and line
.leading
< 4 and line
.value
[line
.leading
] == '[' then
214 pos
= line
.leading
+ 1
215 pos
= md
.read_until
(id
, pos
, ']')
216 if not id
.is_empty
and pos
+ 2 < line
.value
.length
then
217 if line
.value
[pos
+ 1] == ':' then
219 pos
= md
.skip_spaces
(pos
)
220 if line
.value
[pos
] == '<' then
222 pos
= md
.read_until
(link
, pos
, '>')
225 pos
= md
.read_until
(link
, pos
, ' ', '\n')
227 if not link
.is_empty
then
228 pos
= md
.skip_spaces
(pos
)
229 if pos
> 0 and pos
< line
.value
.length
then
230 var c
= line
.value
[pos
]
231 if c
== '\"' or c
== '\'' or c == '(' then
234 pos = md.read_until(comment, pos, ')')
236 pos = md.read_until(comment, pos, c)
238 if pos > 0 then is_link_ref = true
247 if is_link_ref and not id.is_empty and not link.is_empty then
248 var lr = new LinkRef.with_title(link.write_to_string, comment.write_to_string)
249 add_link_ref(id.write_to_string, lr)
250 if comment.is_empty then last_link_ref = lr
253 comment = new FlatBuffer
254 if not line.is_empty and last_link_ref != null then
256 var c = line.value[pos]
257 if c == '\
"' or c == '\'' or c == '(' then
260 pos = md.read_until(comment, pos, ')')
262 pos = md.read_until(comment, pos, c)
265 if not comment.is_empty then last_link_ref.title = comment.write_to_string
267 if comment.is_empty then return false
273 # This list will be needed during output to expand links.
274 var link_refs: Map[String, LinkRef] = new HashMap[String, LinkRef]
276 # Last encountered link ref (for multiline definitions)
278 # Markdown allows link refs to be defined over two lines:
281 # [id]: http://example.com/longish/path/to/resource/here
282 # "Optional Title Here"
285 private var last_link_ref: nullable LinkRef = null
287 # Add a link ref to the list
288 fun add_link_ref(key: String, ref: LinkRef) do link_refs[key.to_lower] = ref
290 # Recursively split a `block`.
292 # The block is splitted according to the type of lines it contains.
293 # Some blocks can be splited again recursively like lists.
294 # The `in_list` mode is used to recurse on list and build
295 # nested paragraphs or code blocks.
296 fun recurse(root: MDBlock, in_list: Bool) do
297 var old_mode = self.in_list
298 var old_root = self.current_block
299 self.in_list = in_list
301 var line = root.first_line
302 while line != null and line.is_empty do
304 if line == null then return
309 while current_line != null do
310 line_kind(current_line.as(not null)).process(self)
312 self.in_list = old_mode
313 self.current_block = old_root
316 # Currently processed line.
317 # Used when visiting blocks with `recurse`.
318 var current_line: nullable MDLine = null is writable
320 # Currently processed block.
321 # Used when visiting blocks with `recurse`.
322 var current_block: nullable MDBlock = null is writable
324 # Is the current recursion in list mode?
325 # Used when visiting blocks with `recurse`
326 private var in_list = false
330 fun line_kind(md: MDLine): Line do
332 var leading = md.leading
333 var trailing = md.trailing
334 if md.is_empty then return new LineEmpty
335 if md.leading > 3 then return new LineCode
336 if value[leading] == '#' then return new LineHeadline
337 if value[leading] == '>' then return new LineBlockquote
340 if value.length - leading - trailing > 2 then
341 if value[leading] == '`' and md.count_chars_start('`') >= 3 then
344 if value[leading] == '~' and md.count_chars_start('~') >= 3 then
350 if value.length - leading - trailing > 2 and
351 (value[leading] == '*' or value[leading] == '-' or value[leading] == '_') then
352 if md.count_chars(value[leading]) >= 3 then
357 if value.length - leading >= 2 and value[leading + 1] == ' ' then
358 var c = value[leading]
359 if c == '*' or c == '-' or c == '+' then return new LineUList
362 if value.length - leading >= 3 and value[leading].is_digit then
364 while i < value.length and value[i].is_digit do i += 1
365 if i + 1 < value.length and value[i] == '.' and value[i + 1] == ' ' then
370 if value[leading] == '<' and md.check_html then return new LineXML
373 if next != null and not next.is_empty then
374 if next.count_chars('=') > 0 then
375 return new LineHeadline1
377 if next.count_chars('-') > 0 then
378 return new LineHeadline2
384 # Get the token kind at `pos`.
385 fun token_at(text: Text, pos: Int): Token do
397 if pos + 1 < text.length then
402 if pos + 2 < text.length then
412 loc = new MDLocation(
413 current_loc.line_start,
414 current_loc.column_start + pos,
415 current_loc.line_start,
416 current_loc.column_start + pos)
421 if c0 != ' ' or c2 != ' ' then
422 return new TokenStrongStar(loc, pos, c)
424 return new TokenEmStar(loc, pos, c)
427 if c0 != ' ' or c1 != ' ' then
428 return new TokenEmStar(loc, pos, c)
430 return new TokenNone(loc, pos, c)
432 else if c == '_' then
434 if c0 != ' ' or c2 != ' ' then
435 return new TokenStrongUnderscore(loc, pos, c)
437 return new TokenEmUnderscore(loc, pos, c)
441 if (c0.is_letter or c0.is_digit) and c0 != '_' and
442 (c1.is_letter or c1.is_digit) then
443 return new TokenNone(loc, pos, c)
445 return new TokenEmUnderscore(loc, pos, c)
448 if c0 != ' ' or c1 != ' ' then
449 return new TokenEmUnderscore(loc, pos, c)
451 return new TokenNone(loc, pos, c)
453 else if c == '!' then
454 if c1 == '[' then return new TokenImage(loc, pos, c)
455 return new TokenNone(loc, pos, c)
456 else if c == '[' then
457 return new TokenLink(loc, pos, c)
458 else if c == ']' then
459 return new TokenNone(loc, pos, c)
460 else if c == '`' then
462 return new TokenCodeDouble(loc, pos, c)
464 return new TokenCodeSingle(loc, pos, c)
466 else if c == '\\' then
467 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
468 return new TokenEscape(loc
, pos
, c
)
470 return new TokenNone(loc
, pos
, c
)
472 else if c
== '<' then
473 return new TokenHTML(loc
, pos
, c
)
474 else if c
== '&' then
475 return new TokenEntity(loc
, pos
, c
)
478 if c
== '~' and c1
== '~' then
479 return new TokenStrike(loc
, pos
, c
)
482 return new TokenNone(loc
, pos
, c
)
486 # Find the position of a `token` in `self`.
487 fun find_token
(text
: Text, start
: Int, token
: Token): Int do
489 while pos
< text
.length
do
490 if token_at
(text
, pos
).is_same_type
(token
) then
498 # Location used for next parsed token.
500 # This location can be changed by the emitter to adjust with `\n` found
502 private fun current_loc
: MDLocation do return emitter
.current_loc
505 # Emit output corresponding to blocks content.
507 # Blocks are created by a previous pass in `MarkdownProcessor`.
508 # The emitter use a `Decorator` to select the output format.
509 class MarkdownEmitter
511 # Kind of processor used for parsing.
512 type PROCESSOR: MarkdownProcessor
514 # Processor containing link refs.
515 var processor
: PROCESSOR
517 # Kind of decorator used for decoration.
518 type DECORATOR: Decorator
520 # Decorator used for output.
521 # Default is `HTMLDecorator`
522 var decorator
: DECORATOR is writable, lazy
do
523 return new HTMLDecorator
526 # Create a new `MarkdownEmitter` using a custom `decorator`.
527 init with_decorator
(processor
: PROCESSOR, decorator
: DECORATOR) do
529 self.decorator
= decorator
532 # Output `block` using `decorator` in the current buffer.
533 fun emit
(block
: Block): Text do
534 var buffer
= push_buffer
540 # Output the content of `block`.
541 fun emit_in
(block
: Block) do block
.emit_in
(self)
543 # Transform and emit mardown text
544 fun emit_text
(text
: Text) do emit_text_until
(text
, 0, null)
546 # Transform and emit mardown text starting at `start` and
547 # until a token with the same type as `token` is found.
548 # Go until the end of `text` if `token` is null.
549 fun emit_text_until
(text
: Text, start
: Int, token
: nullable Token): Int do
550 var old_text
= current_text
551 var old_pos
= current_pos
554 while current_pos
< text
.length
do
555 if text
[current_pos
] == '\n' then
556 current_loc
.line_start
+= 1
557 current_loc
.column_start
= -current_pos
559 var mt
= processor
.token_at
(text
, current_pos
)
560 if (token
!= null and not token
isa TokenNone) and
561 (mt
.is_same_type
(token
) or
562 (token
isa TokenEmStar and mt
isa TokenStrongStar) or
563 (token
isa TokenEmUnderscore and mt
isa TokenStrongUnderscore)) then
569 current_text
= old_text
570 current_pos
= old_pos
574 # Currently processed position in `current_text`.
575 # Used when visiting inline production with `emit_text_until`.
576 private var current_pos
: Int = -1
578 # Currently processed text.
579 # Used when visiting inline production with `emit_text_until`.
580 private var current_text
: nullable Text = null
583 private var buffer_stack
= new List[FlatBuffer]
585 # Push a new buffer on the stack.
586 private fun push_buffer
: FlatBuffer do
587 var buffer
= new FlatBuffer
588 buffer_stack
.add buffer
592 # Pop the last buffer.
593 private fun pop_buffer
do buffer_stack
.pop
595 # Current output buffer.
596 private fun current_buffer
: FlatBuffer do
597 assert not buffer_stack
.is_empty
598 return buffer_stack
.last
602 private var loc_stack
= new List[MDLocation]
604 # Push a new MDLocation on the stack.
605 private fun push_loc
(location
: MDLocation) do loc_stack
.add location
607 # Pop the last buffer.
608 private fun pop_loc
: MDLocation do return loc_stack
.pop
610 # Current output buffer.
611 private fun current_loc
: MDLocation do
612 assert not loc_stack
.is_empty
613 return loc_stack
.last
616 # Append `e` to current buffer.
617 fun add
(e
: Writable) do
619 current_buffer
.append e
621 current_buffer
.append e
.write_to_string
625 # Append `c` to current buffer.
630 # Append a "\n" line break.
631 fun addn
do addc
'\n'
635 # Links that are specified somewhere in the mardown document to be reused as shortcuts.
638 # [1]: http://example.com/ "Optional title"
645 # Optional link title
646 var title
: nullable String = null
648 # Is the link an abreviation?
649 var is_abbrev
= false
651 # Create a link with a title.
652 init with_title
(link
: String, title
: nullable String) do
658 # A `Decorator` is used to emit mardown into a specific format.
659 # Default decorator used is `HTMLDecorator`.
662 # Kind of emitter used for decoration.
663 type EMITTER: MarkdownEmitter
665 # Render a single plain char.
667 # Redefine this method to add special escaping for plain text.
668 fun add_char
(v
: EMITTER, c
: Char) do v
.addc c
670 # Render a ruler block.
671 fun add_ruler
(v
: EMITTER, block
: BlockRuler) is abstract
673 # Render a headline block with corresponding level.
674 fun add_headline
(v
: EMITTER, block
: BlockHeadline) is abstract
676 # Render a paragraph block.
677 fun add_paragraph
(v
: EMITTER, block
: BlockParagraph) is abstract
679 # Render a code or fence block.
680 fun add_code
(v
: EMITTER, block
: BlockCode) is abstract
682 # Render a blockquote.
683 fun add_blockquote
(v
: EMITTER, block
: BlockQuote) is abstract
685 # Render an unordered list.
686 fun add_unorderedlist
(v
: EMITTER, block
: BlockUnorderedList) is abstract
688 # Render an ordered list.
689 fun add_orderedlist
(v
: EMITTER, block
: BlockOrderedList) is abstract
691 # Render a list item.
692 fun add_listitem
(v
: EMITTER, block
: BlockListItem) is abstract
694 # Render an emphasis text.
695 fun add_em
(v
: EMITTER, text
: Text) is abstract
697 # Render a strong text.
698 fun add_strong
(v
: EMITTER, text
: Text) is abstract
700 # Render a strike text.
702 # Extended mode only (see `MarkdownProcessor::ext_mode`)
703 fun add_strike
(v
: EMITTER, text
: Text) is abstract
706 fun add_link
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
709 fun add_image
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
711 # Render an abbreviation.
712 fun add_abbr
(v
: EMITTER, name
: Text, comment
: Text) is abstract
714 # Render a code span reading from a buffer.
715 fun add_span_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
717 # Render a text and escape it.
718 fun append_value
(v
: EMITTER, value
: Text) is abstract
720 # Render code text from buffer and escape it.
721 fun append_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
723 # Render a character escape.
724 fun escape_char
(v
: EMITTER, char
: Char) is abstract
726 # Render a line break
727 fun add_line_break
(v
: EMITTER) is abstract
729 # Generate a new html valid id from a `String`.
730 fun strip_id
(txt
: String): String is abstract
732 # Found headlines during the processing labeled by their ids.
733 fun headlines
: ArrayMap[String, HeadLine] is abstract
736 # Class representing a markdown headline.
738 # Unique identifier of this headline.
741 # Text of the headline.
744 # Level of this headline.
746 # According toe the markdown specification, level must be in `[1..6]`.
750 # `Decorator` that outputs HTML.
754 redef var headlines
= new ArrayMap[String, HeadLine]
756 redef fun add_ruler
(v
, block
) do v
.add
"<hr/>\n"
758 redef fun add_headline
(v
, block
) do
760 var txt
= block
.block
.first_line
.value
761 var id
= strip_id
(txt
)
762 var lvl
= block
.depth
763 headlines
[id
] = new HeadLine(id
, txt
, lvl
)
765 v
.add
"<h{lvl} id=\"{id}\
">"
770 redef fun add_paragraph
(v
, block
) do
776 redef fun add_code
(v
, block
) do
777 var meta
= block
.meta
779 v
.add
"<pre class=\""
780 append_value(v, meta)
786 v
.add
"</code></pre>\n"
789 redef fun add_blockquote
(v
, block
) do
790 v
.add
"<blockquote>\n"
792 v
.add
"</blockquote>\n"
795 redef fun add_unorderedlist
(v
, block
) do
801 redef fun add_orderedlist
(v
, block
) do
807 redef fun add_listitem
(v
, block
) do
813 redef fun add_em
(v
, text
) do
819 redef fun add_strong
(v
, text
) do
825 redef fun add_strike
(v
, text
) do
831 redef fun add_image
(v
, link
, name
, comment
) do
833 append_value(v, link)
835 append_value(v, name)
837 if comment
!= null and not comment
.is_empty
then
839 append_value(v, comment)
845 redef fun add_link
(v
, link
, name
, comment
) do
847 append_value(v, link)
849 if comment
!= null and not comment
.is_empty
then
851 append_value(v, comment)
859 redef fun add_abbr
(v
, name
, comment
) do
860 v
.add
"<abbr title=\""
861 append_value(v, comment)
867 redef fun add_span_code
(v
, text
, from
, to
) do
869 append_code
(v
, text
, from
, to
)
873 redef fun add_line_break
(v
) do
877 redef fun append_value
(v
, text
) do for c
in text
do escape_char
(v
, c
)
879 redef fun escape_char
(v
, c
) do
882 else if c
== '<' then
884 else if c
== '>' then
886 else if c
== '"' then
888 else if c
== '\'' then
895 redef fun append_code(v, buffer, from, to) do
896 for i in [from..to[ do
900 else if c == '<' then
902 else if c == '>' then
910 redef fun strip_id(txt) do
912 var b = new FlatBuffer
917 if not c.is_letter and
919 not allowed_id_chars.has(c) then continue
925 # check for multiple id definitions
926 if headlines.has_key(key) then
929 while headlines.has_key(key) do
937 private var allowed_id_chars: Array[Char] = ['-', '_
', ':', '.']
940 # Location in a Markdown input.
943 # Starting line number (starting from 1).
946 # Starting column number (starting from 1).
947 var column_start: Int
949 # Stopping line number (starting from 1).
952 # Stopping column number (starting from 1).
955 redef fun to_s do return "{line_start},{column_start}--{line_end},{column_end}"
957 # Return a copy of `self`.
958 fun copy: MDLocation do
959 return new MDLocation(line_start, column_start, line_end, column_end)
963 # A block of markdown lines.
964 # A `MDBlock` can contains lines and/or sub-blocks.
967 # Position of `self` in the input.
968 var location: MDLocation
972 var kind: Block = new BlockNone(self) is writable
975 var first_line: nullable MDLine = null is writable
978 var last_line: nullable MDLine = null is writable
980 # First sub-block if any.
981 var first_block: nullable MDBlock = null is writable
983 # Last sub-block if any.
984 var last_block: nullable MDBlock = null is writable
986 # Previous block if any.
987 var prev: nullable MDBlock = null is writable
990 var next: nullable MDBlock = null is writable
992 # Does this block contain subblocks?
993 fun has_blocks: Bool do return first_block != null
996 fun count_blocks: Int do
998 var block = first_block
999 while block != null do
1006 # Does this block contain lines?
1007 fun has_lines: Bool do return first_line != null
1009 # Count block lines.
1010 fun count_lines: Int do
1012 var line = first_line
1013 while line != null do
1020 # Split `self` creating a new sub-block having `line` has `last_line`.
1021 fun split(line: MDLine): MDBlock do
1022 # location for new block
1023 var new_loc = new MDLocation(
1024 first_line.location.line_start,
1025 first_line.location.column_start,
1026 line.location.line_end,
1027 line.location.column_end)
1029 var block = new MDBlock(new_loc)
1030 block.first_line = first_line
1031 block.last_line = line
1032 first_line = line.next
1034 if first_line == null then
1037 first_line.prev = null
1038 # update current block loc
1039 location.line_start = first_line.location.line_start
1040 location.column_start = first_line.location.column_start
1042 if first_block == null then
1046 last_block.next = block
1052 # Add a `line` to this block.
1053 fun add_line(line: MDLine) do
1054 if last_line == null then
1058 last_line.next_empty = line.is_empty
1059 line.prev_empty = last_line.is_empty
1060 line.prev = last_line
1061 last_line.next = line
1066 # Remove `line` from this block.
1067 fun remove_line(line: MDLine) do
1068 if line.prev == null then
1069 first_line = line.next
1071 line.prev.next = line.next
1073 if line.next == null then
1074 last_line = line.prev
1076 line.next.prev = line.prev
1082 # Remove leading empty lines.
1083 fun remove_leading_empty_lines: Bool do
1084 var was_empty = false
1085 var line = first_line
1086 while line != null and line.is_empty do
1094 # Remove trailing empty lines.
1095 fun remove_trailing_empty_lines: Bool do
1096 var was_empty = false
1097 var line = last_line
1098 while line != null and line.is_empty do
1106 # Remove leading and trailing empty lines.
1107 fun remove_surrounding_empty_lines: Bool do
1108 var was_empty = false
1109 if remove_leading_empty_lines then was_empty = true
1110 if remove_trailing_empty_lines then was_empty = true
1114 # Remove list markers and up to 4 leading spaces.
1115 # Used to clean nested lists.
1116 fun remove_list_indent(v: MarkdownProcessor) do
1117 var line = first_line
1118 while line != null do
1119 if not line.is_empty then
1120 var kind = v.line_kind(line)
1121 if kind isa LineList then
1122 line.value = kind.extract_value(line)
1124 line.value = line.value.substring_from(line.leading.min(4))
1126 line.leading = line.process_leading
1132 # Collect block line text.
1134 var text = new FlatBuffer
1135 var line = first_line
1136 while line != null do
1137 if not line.is_empty then
1138 text.append line.text
1143 return text.write_to_string
1147 # Representation of a markdown block in the AST.
1148 # Each `Block` is linked to a `MDBlock` that contains mardown code.
1149 abstract class Block
1151 # The markdown block `self` is related to.
1154 # Output `self` using `v.decorator`.
1155 fun emit(v: MarkdownEmitter) do v.emit_in(self)
1157 # Emit the containts of `self`, lines or blocks.
1158 fun emit_in(v: MarkdownEmitter) do
1159 block.remove_surrounding_empty_lines
1160 if block.has_lines then
1167 # Emit lines contained in `block`.
1168 fun emit_lines(v: MarkdownEmitter) do
1169 var tpl = v.push_buffer
1170 var line = block.first_line
1171 while line != null do
1172 if not line.is_empty then
1173 v.add line.value.substring(line.leading, line.value.length - line.trailing)
1174 if line.trailing >= 2 then v.decorator.add_line_break(v)
1176 if line.next != null then
1185 # Emit sub-blocks contained in `block`.
1186 fun emit_blocks(v: MarkdownEmitter) do
1187 var block = self.block.first_block
1188 while block != null do
1189 v.push_loc(block.location)
1196 # The raw content of the block as a multi-line string.
1197 fun raw_content: String do
1198 var infence = self isa BlockFence
1199 var text = new FlatBuffer
1200 var line = self.block.first_line
1201 while line != null do
1202 if not line.is_empty then
1203 var str = line.value
1204 if not infence and str.has_prefix(" ") then
1205 text.append str.substring(4, str.length - line.trailing)
1213 return text.write_to_string
1217 # A block without any markdown specificities.
1219 # Actually use the same implementation than `BlockCode`,
1220 # this class is only used for typing purposes.
1225 # A markdown blockquote.
1229 redef fun emit(v) do v.decorator.add_blockquote(v, self)
1231 # Remove blockquote markers.
1232 private fun remove_block_quote_prefix(block: MDBlock) do
1233 var line = block.first_line
1234 while line != null do
1235 if not line.is_empty then
1236 if line.value[line.leading] == '>' then
1237 var rem = line.leading + 1
1238 if line.leading + 1 < line.value.length and
1239 line.value[line.leading + 1] == ' ' then
1242 line.value = line.value.substring_from(rem)
1243 line.leading = line.process_leading
1251 # A markdown code block.
1255 # Any string found after fence token.
1256 var meta: nullable Text
1258 # Number of char to skip at the beginning of the line.
1260 # Block code lines start at 4 spaces.
1261 protected var line_start = 4
1263 redef fun emit(v) do v.decorator.add_code(v, self)
1265 redef fun emit_lines(v) do
1266 var line = block.first_line
1267 while line != null do
1268 if not line.is_empty then
1269 v.decorator.append_code(v, line.value, line_start, line.value.length)
1277 # A markdown code-fence block.
1279 # Actually use the same implementation than `BlockCode`,
1280 # this class is only used for typing purposes.
1284 # Fence code lines start at 0 spaces.
1285 redef var line_start = 0
1288 # A markdown headline.
1292 redef fun emit(v) do
1293 var loc = block.location.copy
1294 loc.column_start += start
1296 v.decorator.add_headline(v, self)
1300 private var start = 0
1302 # Depth of the headline used to determine the headline level.
1305 # Remove healine marks from lines contained in `self`.
1306 private fun transform_headline(block: MDBlock) do
1307 if depth > 0 then return
1309 var line = block.first_line
1310 if line.is_empty then return
1311 var start = line.leading
1312 while start < line.value.length and line.value[start] == '#' do
1316 while start
< line
.value
.length
and line
.value
[start
] == ' ' do
1319 if start
>= line
.value
.length
then
1320 line
.is_empty
= true
1322 var nend
= line
.value
.length
- line
.trailing
- 1
1323 while line
.value
[nend
] == '#' do nend
-= 1
1324 while line
.value
[nend
] == ' ' do nend
-= 1
1325 line
.value
= line
.value
.substring
(start
, nend
- start
+ 1)
1330 depth
= level
.min
(6)
1334 # A markdown list item block.
1338 redef fun emit
(v
) do v
.decorator
.add_listitem
(v
, self)
1341 # A markdown list block.
1342 # Can be either an ordered or unordered list, this class is mainly used to factorize code.
1343 abstract class BlockList
1346 # Split list block into list items sub-blocks.
1347 private fun init_block
(v
: MarkdownProcessor) do
1348 var line
= block
.first_line
1350 while line
!= null do
1351 var t
= v
.line_kind
(line
)
1352 if t
isa LineList or
1353 (not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1354 not (t
isa LineList))) then
1355 var sblock
= block
.split
(line
.prev
.as(not null))
1356 sblock
.kind
= new BlockListItem(sblock
)
1360 var sblock
= block
.split
(block
.last_line
.as(not null))
1361 sblock
.kind
= new BlockListItem(sblock
)
1364 # Expand list items as paragraphs if needed.
1365 private fun expand_paragraphs
(block
: MDBlock) do
1366 var outer
= block
.first_block
1367 var inner
: nullable MDBlock
1368 var has_paragraph
= false
1369 while outer
!= null and not has_paragraph
do
1370 if outer
.kind
isa BlockListItem then
1371 inner
= outer
.first_block
1372 while inner
!= null and not has_paragraph
do
1373 if inner
.kind
isa BlockParagraph then
1374 has_paragraph
= true
1381 if has_paragraph
then
1382 outer
= block
.first_block
1383 while outer
!= null do
1384 if outer
.kind
isa BlockListItem then
1385 inner
= outer
.first_block
1386 while inner
!= null do
1387 if inner
.kind
isa BlockNone then
1388 inner
.kind
= new BlockParagraph(inner
)
1399 # A markdown ordered list.
1400 class BlockOrderedList
1403 redef fun emit
(v
) do v
.decorator
.add_orderedlist
(v
, self)
1406 # A markdown unordred list.
1407 class BlockUnorderedList
1410 redef fun emit
(v
) do v
.decorator
.add_unorderedlist
(v
, self)
1413 # A markdown paragraph block.
1414 class BlockParagraph
1417 redef fun emit
(v
) do v
.decorator
.add_paragraph
(v
, self)
1424 redef fun emit
(v
) do v
.decorator
.add_ruler
(v
, self)
1427 # Xml blocks that can be found in markdown markup.
1431 redef fun emit_lines
(v
) do
1432 var line
= block
.first_line
1433 while line
!= null do
1434 if not line
.is_empty
then v
.add line
.value
1444 # Location of `self` in the original input.
1445 var location
: MDLocation
1447 # Text contained in this line.
1448 var value
: String is writable
1450 # Is this line empty?
1451 # Lines containing only spaces are considered empty.
1452 var is_empty
: Bool = true is writable
1454 # Previous line in `MDBlock` or null if first line.
1455 var prev
: nullable MDLine = null is writable
1457 # Next line in `MDBlock` or null if last line.
1458 var next
: nullable MDLine = null is writable
1460 # Is the previous line empty?
1461 var prev_empty
: Bool = false is writable
1463 # Is the next line empty?
1464 var next_empty
: Bool = false is writable
1466 # Initialize a new MDLine from its string value
1468 self.leading
= process_leading
1469 if leading
!= value
.length
then
1470 self.is_empty
= false
1471 self.trailing
= process_trailing
1475 # Set `value` as an empty String and update `leading`, `trailing` and is_`empty`.
1481 if prev
!= null then prev
.next_empty
= true
1482 if next
!= null then next
.prev_empty
= true
1485 # Number or leading spaces on this line.
1486 var leading
: Int = 0 is writable
1488 # Compute `leading` depending on `value`.
1489 fun process_leading
: Int do
1491 var value
= self.value
1492 while count
< value
.length
and value
[count
] == ' ' do count
+= 1
1493 if leading
== value
.length
then clear
1497 # Number of trailing spaces on this line.
1498 var trailing
: Int = 0 is writable
1500 # Compute `trailing` depending on `value`.
1501 fun process_trailing
: Int do
1503 var value
= self.value
1504 while value
[value
.length
- count
- 1] == ' ' do
1510 # Count the amount of `ch` in this line.
1511 # Return A value > 0 if this line only consists of `ch` end spaces.
1512 fun count_chars
(ch
: Char): Int do
1528 # Count the amount of `ch` at the start of this line ignoring spaces.
1529 fun count_chars_start
(ch
: Char): Int do
1544 # Last XML line if any.
1545 private var xml_end_line
: nullable MDLine = null
1547 # Does `value` contains valid XML markup?
1548 private fun check_html
: Bool do
1549 var tags
= new Array[String]
1550 var tmp
= new FlatBuffer
1552 if pos
+ 1 < value
.length
and value
[pos
+ 1] == '!' then
1553 if read_xml_comment
(self, pos
) > 0 then return true
1555 pos
= value
.read_xml
(tmp
, pos
, false)
1559 if not tag
.is_html_block
then
1567 var line
: nullable MDLine = self
1568 while line
!= null do
1569 while pos
< line
.value
.length
and line
.value
[pos
] != '<' do
1572 if pos
>= line
.value
.length
then
1573 if pos
- 2 >= 0 and line
.value
[pos
- 2] == '/' then
1575 if tags
.is_empty
then
1583 tmp
= new FlatBuffer
1584 var new_pos
= line
.value
.read_xml
(tmp
, pos
, false)
1587 if tag
.is_html_block
and not tag
== "hr" then
1588 if tmp
[1] == '/' then
1589 if tags
.last
!= tag
then
1597 if tags
.is_empty
then
1607 return tags
.is_empty
1612 # Read a XML comment.
1613 # Used by `check_html`.
1614 private fun read_xml_comment
(first_line
: MDLine, start
: Int): Int do
1615 var line
: nullable MDLine = first_line
1616 if start
+ 3 < line
.value
.length
then
1617 if line
.value
[2] == '-' and line
.value
[3] == '-' then
1619 while line
!= null do
1620 while pos
< line
.value
.length
and line
.value
[pos
] != '-' do
1623 if pos
== line
.value
.length
then
1627 if pos
+ 2 < line
.value
.length
then
1628 if line
.value
[pos
+ 1] == '-' and line
.value
[pos
+ 2] == '>' then
1629 first_line
.xml_end_line
= line
1641 # Extract the text of `self` without leading and trailing.
1642 fun text
: String do return value
.substring
(leading
, value
.length
- trailing
)
1649 # See `MarkdownProcessor::recurse`.
1650 fun process
(v
: MarkdownProcessor) is abstract
1653 # An empty markdown line.
1657 redef fun process
(v
) do
1658 v
.current_line
= v
.current_line
.next
1662 # A non-specific markdown construction.
1663 # Mainly used as part of another line construct such as paragraphs or lists.
1667 redef fun process
(v
) do
1668 var line
= v
.current_line
1670 var was_empty
= line
.prev_empty
1671 while line
!= null and not line
.is_empty
do
1672 var t
= v
.line_kind
(line
)
1673 if (v
.in_list
or v
.ext_mode
) and t
isa LineList then
1676 if v
.ext_mode
and (t
isa LineCode or t
isa LineFence) then
1679 if t
isa LineHeadline or t
isa LineHeadline1 or t
isa LineHeadline2 or
1680 t
isa LineHR or t
isa LineBlockquote or t
isa LineXML then
1686 if line
!= null and not line
.is_empty
then
1687 var block
= v
.current_block
.split
(line
.prev
.as(not null))
1688 if v
.in_list
and not was_empty
then
1689 block
.kind
= new BlockNone(block
)
1691 block
.kind
= new BlockParagraph(block
)
1693 v
.current_block
.remove_leading_empty_lines
1696 if line
!= null then
1697 block
= v
.current_block
.split
(line
)
1699 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1701 if v
.in_list
and (line
== null or not line
.is_empty
) and not was_empty
then
1702 block
.kind
= new BlockNone(block
)
1704 block
.kind
= new BlockParagraph(block
)
1706 v
.current_block
.remove_leading_empty_lines
1708 v
.current_line
= v
.current_block
.first_line
1712 # A line of markdown code.
1716 redef fun process
(v
) do
1717 var line
= v
.current_line
1719 while line
!= null and (line
.is_empty
or v
.line_kind
(line
) isa LineCode) do
1722 # split at block end line
1724 if line
!= null then
1725 block
= v
.current_block
.split
(line
.prev
.as(not null))
1727 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1729 block
.kind
= new BlockCode(block
)
1730 block
.remove_surrounding_empty_lines
1731 v
.current_line
= v
.current_block
.first_line
1735 # A line of raw XML.
1739 redef fun process
(v
) do
1740 var line
= v
.current_line
1741 var prev
= line
.prev
1742 if prev
!= null then v
.current_block
.split
(prev
)
1743 var block
= v
.current_block
.split
(line
.xml_end_line
.as(not null))
1744 block
.kind
= new BlockXML(block
)
1745 v
.current_block
.remove_leading_empty_lines
1746 v
.current_line
= v
.current_block
.first_line
1750 # A markdown blockquote line.
1751 class LineBlockquote
1754 redef fun process
(v
) do
1755 var line
= v
.current_line
1757 while line
!= null do
1758 if not line
.is_empty
and (line
.prev_empty
and
1759 line
.leading
== 0 and
1760 not v
.line_kind
(line
) isa LineBlockquote) then break
1765 if line
!= null then
1766 block
= v
.current_block
.split
(line
.prev
.as(not null))
1768 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1770 var kind
= new BlockQuote(block
)
1772 block
.remove_surrounding_empty_lines
1773 kind
.remove_block_quote_prefix
(block
)
1774 v
.current_line
= line
1775 v
.recurse
(block
, false)
1776 v
.current_line
= v
.current_block
.first_line
1780 # A markdown ruler line.
1784 redef fun process
(v
) do
1785 var line
= v
.current_line
1786 if line
.prev
!= null then v
.current_block
.split
(line
.prev
.as(not null))
1787 var block
= v
.current_block
.split
(line
.as(not null))
1788 block
.kind
= new BlockRuler(block
)
1789 v
.current_block
.remove_leading_empty_lines
1790 v
.current_line
= v
.current_block
.first_line
1794 # A markdown fence code line.
1798 redef fun process
(v
) do
1800 var line
= v
.current_line
.next
1801 while line
!= null do
1802 if v
.line_kind
(line
) isa LineFence then break
1805 if line
!= null then
1810 if line
!= null then
1811 block
= v
.current_block
.split
(line
.prev
.as(not null))
1813 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1815 block
.remove_surrounding_empty_lines
1816 var meta
= block
.first_line
.value
.meta_from_fence
1817 block
.kind
= new BlockFence(block
, meta
)
1818 block
.first_line
.clear
1819 var last
= block
.last_line
1820 if last
!= null and v
.line_kind
(last
) isa LineFence then
1821 block
.last_line
.clear
1823 block
.remove_surrounding_empty_lines
1824 v
.current_line
= line
1828 # A markdown headline.
1832 redef fun process
(v
) do
1833 var line
= v
.current_line
1834 var lprev
= line
.prev
1835 if lprev
!= null then v
.current_block
.split
(lprev
)
1836 var block
= v
.current_block
.split
(line
.as(not null))
1837 var kind
= new BlockHeadline(block
)
1839 kind
.transform_headline
(block
)
1840 v
.current_block
.remove_leading_empty_lines
1841 v
.current_line
= v
.current_block
.first_line
1845 # A markdown headline of level 1.
1849 redef fun process
(v
) do
1850 var line
= v
.current_line
1851 var lprev
= line
.prev
1852 if lprev
!= null then v
.current_block
.split
(lprev
)
1854 var block
= v
.current_block
.split
(line
.as(not null))
1855 var kind
= new BlockHeadline(block
)
1857 kind
.transform_headline
(block
)
1859 v
.current_block
.remove_leading_empty_lines
1860 v
.current_line
= v
.current_block
.first_line
1864 # A markdown headline of level 2.
1868 redef fun process
(v
) do
1869 var line
= v
.current_line
1870 var lprev
= line
.prev
1871 if lprev
!= null then v
.current_block
.split
(lprev
)
1873 var block
= v
.current_block
.split
(line
.as(not null))
1874 var kind
= new BlockHeadline(block
)
1876 kind
.transform_headline
(block
)
1878 v
.current_block
.remove_leading_empty_lines
1879 v
.current_line
= v
.current_block
.first_line
1883 # A markdown list line.
1884 # Mainly used to factorize code between ordered and unordered lists.
1885 abstract class LineList
1888 redef fun process
(v
) do
1889 var line
= v
.current_line
1891 while line
!= null do
1892 var t
= v
.line_kind
(line
)
1893 if not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1894 not t
isa LineList) then break
1899 if line
!= null then
1900 list
= v
.current_block
.split
(line
.prev
.as(not null))
1902 list
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1904 var kind
= block_kind
(list
)
1906 list
.first_line
.prev_empty
= false
1907 list
.last_line
.next_empty
= false
1908 list
.remove_surrounding_empty_lines
1909 list
.first_line
.prev_empty
= false
1910 list
.last_line
.next_empty
= false
1912 var block
= list
.first_block
1913 while block
!= null do
1914 block
.remove_list_indent
(v
)
1915 v
.recurse
(block
, true)
1918 kind
.expand_paragraphs
(list
)
1919 v
.current_line
= line
1922 # Create a new block kind based on this line.
1923 protected fun block_kind
(block
: MDBlock): BlockList is abstract
1925 # Extract string value from `MDLine`.
1926 protected fun extract_value
(line
: MDLine): String is abstract
1929 # An ordered list line.
1933 redef fun block_kind
(block
) do return new BlockOrderedList(block
)
1935 redef fun extract_value
(line
) do
1936 return line
.value
.substring_from
(line
.value
.index_of
('.') + 2)
1940 # An unordered list line.
1944 redef fun block_kind
(block
) do return new BlockUnorderedList(block
)
1946 redef fun extract_value
(line
) do
1947 return line
.value
.substring_from
(line
.leading
+ 2)
1951 # A token represent a character in the markdown input.
1952 # Some tokens have a specific markup behaviour that is handled here.
1953 abstract class Token
1955 # Location of `self` in the original input.
1956 var location
: nullable MDLocation
1958 # Position of `self` in input independant from lines.
1961 # Character found at `pos` in the markdown input.
1964 # Output that token using `MarkdownEmitter::decorator`.
1965 fun emit
(v
: MarkdownEmitter) do v
.decorator
.add_char
(v
, char
)
1968 # A token without a specific meaning.
1973 # An emphasis token.
1974 abstract class TokenEm
1977 redef fun emit
(v
) do
1978 var tmp
= v
.push_buffer
1979 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 1, self)
1982 v
.decorator
.add_em
(v
, tmp
)
1990 # An emphasis star token.
1995 # An emphasis underscore token.
1996 class TokenEmUnderscore
2001 abstract class TokenStrong
2004 redef fun emit
(v
) do
2005 var tmp
= v
.push_buffer
2006 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2009 v
.decorator
.add_strong
(v
, tmp
)
2010 v
.current_pos
= b
+ 1
2017 # A strong star token.
2018 class TokenStrongStar
2022 # A strong underscore token.
2023 class TokenStrongUnderscore
2028 # This class is mainly used to factorize work between single and double quoted span codes.
2029 abstract class TokenCode
2032 redef fun emit
(v
) do
2033 var a
= pos
+ next_pos
+ 1
2034 var b
= v
.processor
.find_token
(v
.current_text
.as(not null), a
, self)
2036 v
.current_pos
= b
+ next_pos
2037 while a
< b
and v
.current_text
[a
] == ' ' do a
+= 1
2039 while v
.current_text
[b
- 1] == ' ' do b
-= 1
2040 v
.decorator
.add_span_code
(v
, v
.current_text
.as(not null), a
, b
)
2047 private fun next_pos
: Int is abstract
2050 # A span code token.
2051 class TokenCodeSingle
2054 redef fun next_pos
do return 0
2057 # A doubled span code token.
2058 class TokenCodeDouble
2061 redef fun next_pos
do return 1
2064 # A link or image token.
2065 # This class is mainly used to factorize work between images and links.
2066 abstract class TokenLinkOrImage
2070 var link
: nullable Text = null
2073 var name
: nullable Text = null
2076 var comment
: nullable Text = null
2078 # Is the link construct an abbreviation?
2079 var is_abbrev
= false
2081 redef fun emit
(v
) do
2082 var tmp
= new FlatBuffer
2083 var b
= check_link
(v
, tmp
, pos
, self)
2092 # Emit the hyperlink as link or image.
2093 private fun emit_hyper
(v
: MarkdownEmitter) is abstract
2095 # Check if the link is a valid link.
2096 private fun check_link
(v
: MarkdownEmitter, out
: FlatBuffer, start
: Int, token
: Token): Int do
2097 var md
= v
.current_text
2099 if token
isa TokenLink then
2104 var tmp
= new FlatBuffer
2105 pos
= md
.read_md_link_id
(tmp
, pos
)
2106 if pos
< start
then return -1
2110 pos
= md
.skip_spaces
(pos
)
2112 var tid
= name
.write_to_string
.to_lower
2113 if v
.processor
.link_refs
.has_key
(tid
) then
2114 var lr
= v
.processor
.link_refs
[tid
]
2115 is_abbrev
= lr
.is_abbrev
2122 else if md
[pos
] == '(' then
2124 pos
= md
.skip_spaces
(pos
)
2125 if pos
< start
then return -1
2126 tmp
= new FlatBuffer
2127 var use_lt
= md
[pos
] == '<'
2129 pos
= md
.read_until
(tmp
, pos
+ 1, '>')
2131 pos
= md
.read_md_link
(tmp
, pos
)
2133 if pos
< start
then return -1
2134 if use_lt
then pos
+= 1
2135 link
= tmp
.write_to_string
2136 if md
[pos
] == ' ' then
2137 pos
= md
.skip_spaces
(pos
)
2138 if pos
> start
and md
[pos
] == '"' then
2140 tmp
= new FlatBuffer
2141 pos
= md
.read_until
(tmp
, pos
, '"')
2142 if pos
< start
then return -1
2143 comment
= tmp
.write_to_string
2145 pos
= md
.skip_spaces
(pos
)
2146 if pos
== -1 then return -1
2149 if pos
< start
then return -1
2150 if md
[pos
] != ')' then return -1
2151 else if md
[pos
] == '[' then
2153 tmp
= new FlatBuffer
2154 pos
= md
.read_raw_until
(tmp
, pos
, ']')
2155 if pos
< start
then return -1
2157 if tmp
.length
> 0 then
2162 var tid
= id
.write_to_string
.to_lower
2163 if v
.processor
.link_refs
.has_key
(tid
) then
2164 var lr
= v
.processor
.link_refs
[tid
]
2169 var tid
= name
.write_to_string
.replace
("\n", " ").to_lower
2170 if v
.processor
.link_refs
.has_key
(tid
) then
2171 var lr
= v
.processor
.link_refs
[tid
]
2179 if link
== null then return -1
2184 # A markdown link token.
2186 super TokenLinkOrImage
2188 redef fun emit_hyper
(v
) do
2189 if is_abbrev
and comment
!= null then
2190 v
.decorator
.add_abbr
(v
, name
.as(not null), comment
.as(not null))
2192 v
.decorator
.add_link
(v
, link
.as(not null), name
.as(not null), comment
)
2197 # A markdown image token.
2199 super TokenLinkOrImage
2201 redef fun emit_hyper
(v
) do
2202 v
.decorator
.add_image
(v
, link
.as(not null), name
.as(not null), comment
)
2210 redef fun emit
(v
) do
2211 var tmp
= new FlatBuffer
2212 var b
= check_html
(v
, tmp
, v
.current_text
.as(not null), v
.current_pos
)
2217 v
.decorator
.escape_char
(v
, char
)
2221 # Is the HTML valid?
2222 # Also take care of link and mailto shortcuts.
2223 private fun check_html
(v
: MarkdownEmitter, out
: FlatBuffer, md
: Text, start
: Int): Int do
2224 # check for auto links
2225 var tmp
= new FlatBuffer
2226 var pos
= md
.read_until
(tmp
, start
+ 1, ':', ' ', '>', '\n')
2227 if pos
!= -1 and md
[pos
] == ':' and tmp
.is_link_prefix
then
2228 pos
= md
.read_until
(tmp
, pos
, '>')
2230 var link
= tmp
.write_to_string
2231 v
.decorator
.add_link
(v
, link
, link
, null)
2235 # TODO check for mailto
2236 # check for inline html
2237 if start
+ 2 < md
.length
then
2238 return md
.read_xml
(out
, start
, true)
2244 # An HTML entity token.
2248 redef fun emit
(v
) do
2249 var tmp
= new FlatBuffer
2250 var b
= check_entity
(tmp
, v
.current_text
.as(not null), pos
)
2255 v
.decorator
.escape_char
(v
, char
)
2259 # Is the entity valid?
2260 private fun check_entity
(out
: FlatBuffer, md
: Text, start
: Int): Int do
2261 var pos
= md
.read_until
(out
, start
, ';')
2262 if pos
< 0 or out
.length
< 3 then
2265 if out
[1] == '#' then
2266 if out
[2] == 'x' or out
[2] == 'X' then
2267 if out
.length
< 4 then return -1
2268 for i
in [3..out
.length
[ do
2270 if (c
< '0' or c
> '9') and (c
< 'a' and c
> 'f') and (c
< 'A' and c
> 'F') then
2275 for i
in [2..out
.length
[ do
2277 if c
< '0' or c
> '9' then return -1
2282 for i
in [1..out
.length
[ do
2284 if not c
.is_digit
and not c
.is_letter
then return -1
2287 # TODO check entity is valid
2288 # if out.is_entity then
2298 # A markdown escape token.
2302 redef fun emit
(v
) do
2304 v
.addc v
.current_text
[v
.current_pos
]
2308 # A markdown strike token.
2310 # Extended mode only (see `MarkdownProcessor::ext_mode`)
2314 redef fun emit
(v
) do
2315 var tmp
= v
.push_buffer
2316 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2319 v
.decorator
.add_strike
(v
, tmp
)
2320 v
.current_pos
= b
+ 1
2329 # Get the position of the next non-space character.
2330 private fun skip_spaces
(start
: Int): Int do
2332 while pos
> -1 and pos
< length
and (self[pos
] == ' ' or self[pos
] == '\n') do
2335 if pos
< length
then return pos
2339 # Read `self` until `nend` and append it to the `out` buffer.
2340 # Escape markdown special chars.
2341 private fun read_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2343 while pos
< length
do
2345 if c
== '\\' and pos
+ 1 < length
then
2346 pos
= escape
(out
, self[pos
+ 1], pos
)
2348 for n
in nend
do if c
== n
then break label
2353 if pos
== length
then return -1
2357 # Read `self` as raw text until `nend` and append it to the `out` buffer.
2358 # No escape is made.
2359 private fun read_raw_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2361 while pos
< length
do
2363 var end_reached
= false
2370 if end_reached
then break
2374 if pos
== length
then return -1
2378 # Read `self` as XML until `to` and append it to the `out` buffer.
2379 # Escape HTML special chars.
2380 private fun read_xml_until
(out
: FlatBuffer, from
: Int, to
: Char...): Int do
2383 var str_char
: nullable Char = null
2384 while pos
< length
do
2390 if pos
< length
then
2396 if c
== str_char
then
2403 if c
== '"' or c
== '\'' then
2408 var end_reached = false
2409 for n in [0..to.length[ do
2415 if end_reached then break
2420 if pos == length then return -1
2424 # Read `self` as XML and append it to the `out` buffer.
2425 # Safe mode can be activated to limit reading to valid xml.
2426 private fun read_xml(out: FlatBuffer, start: Int, safe_mode: Bool): Int do
2429 var is_close_tag = false
2430 if start + 1 >= length then return -1
2431 if self[start + 1] == '/' then
2434 else if self[start + 1] == '!' then
2438 is_close_tag = false
2442 var tmp = new FlatBuffer
2443 pos = read_xml_until(tmp, pos, ' ', '/', '>')
2444 if pos == -1 then return -1
2445 var tag = tmp.write_to_string.trim.to_lower
2446 if not tag.is_valid_html_tag then
2449 else if tag.is_html_unsafe then
2452 if is_close_tag then out.add '/'
2456 if is_close_tag then out.add '/'
2461 if is_close_tag then out.add '/'
2462 pos = read_xml_until(out, pos, ' ', '/', '>')
2464 if pos == -1 then return -1
2465 pos = read_xml_until(out, pos, '/', '>')
2466 if pos == -1 then return -1
2467 if self[pos] == '/' then
2469 pos = self.read_xml_until(out, pos + 1, '>')
2470 if pos == -1 then return -1
2472 if self[pos] == '>' then
2483 # Read a markdown link address and append it to the `out` buffer.
2484 private fun read_md_link(out: FlatBuffer, start: Int): Int do
2487 while pos < length do
2489 if c == '\\
' and pos + 1 < length then
2490 pos = escape(out, self[pos + 1], pos)
2492 var end_reached = false
2495 else if c == ' ' then
2496 if counter == 1 then end_reached = true
2497 else if c == ')' then
2499 if counter == 0 then end_reached = true
2501 if end_reached then break
2506 if pos == length then return -1
2510 # Read a markdown link text and append it to the `out` buffer.
2511 private fun read_md_link_id(out: FlatBuffer, start: Int): Int do
2514 while pos < length do
2516 var end_reached = false
2520 else if c == ']' then
2522 if counter == 0 then
2530 if end_reached then break
2533 if pos == length then return -1
2537 # Extract the XML tag name from a XML tag.
2538 private fun xml_tag: String do
2539 var tpl = new FlatBuffer
2541 if pos < length and self[1] == '/' then pos += 1
2542 while pos < length - 1 and (self[pos].is_digit or self[pos].is_letter) do
2546 return tpl.write_to_string.to_lower
2549 private fun is_valid_html_tag: Bool do
2550 if is_empty then return false
2552 if not c.is_alpha then return false
2557 # Read and escape the markdown contained in `self`.
2558 private fun escape(out: FlatBuffer, c: Char, pos: Int): Int do
2559 if c == '\\
' or c == '[' or c == ']' or c == '(' or c == ')' or c == '{' or
2560 c == '}' or c == '#' or c == '"' or c == '\'' or c == '.' or c == '<' or
2561 c
== '>' or c
== '*' or c
== '+' or c
== '-' or c
== '_' or c
== '!' or
2562 c
== '`' or c
== '~' or c
== '^' then
2570 # Extract string found at end of fence opening.
2571 private fun meta_from_fence
: nullable Text do
2572 for i
in [0..chars
.length
[ do
2574 if c
!= ' ' and c
!= '`' and c
!= '~' then
2575 return substring_from
(i
).trim
2581 # Is `self` an unsafe HTML element?
2582 private fun is_html_unsafe
: Bool do return html_unsafe_tags
.has
(self.write_to_string
)
2584 # Is `self` a HRML block element?
2585 private fun is_html_block
: Bool do return html_block_tags
.has
(self.write_to_string
)
2587 # Is `self` a link prefix?
2588 private fun is_link_prefix
: Bool do return html_link_prefixes
.has
(self.write_to_string
)
2590 private fun html_unsafe_tags
: Array[String] do return once
["applet", "head", "body", "frame", "frameset", "iframe", "script", "object"]
2592 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"]
2594 private fun html_link_prefixes
: Array[String] do return once
["http", "https", "ftp", "ftps"]
2599 # Parse `self` as markdown and return the HTML representation
2601 # var md = "**Hello World!**"
2602 # var html = md.md_to_html
2603 # assert html == "<p><strong>Hello World!</strong></p>\n"
2604 fun md_to_html
: Writable do
2605 var processor
= new MarkdownProcessor
2606 return processor
.process
(self)