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:
45 # * and this is not a list
49 # <p>This is a paragraph
50 # * and this is not a list</p>
52 # When using extended mode this changes to:
54 # <p>This is a paragraph</p>
56 # <li>and this is not a list</li>
59 # * Fences code blocks
61 # If you don't want to indent your all your code with 4 spaces,
62 # you can wrap your code in ``` ``` ``` or `~~~`.
68 # print "Hello World!"
74 # If you want to use syntax highlighting tools, most of them need to know what kind
75 # of language they are highlighting.
76 # You can add an optional language identifier after the fence declaration to output
77 # it in the HTML render.
82 # print "# Hello World!".md_to_html
87 # <pre class="nit"><code>import markdown
89 # print "Hello World!".md_to_html
92 # * Underscores (Emphasis)
94 # Underscores in the middle of a word like:
98 # normally produces this:
100 # <p>Con<em>cat</em>this</p>
102 # With extended mode they don't result in emphasis.
104 # <p>Con_cat_this</p>
108 # Like in [GFM](https://help.github.com/articles/github-flavored-markdown),
109 # strikethrought span is marked with `~~`.
115 # <del>Mistaken text.</del>
118 init do self.emitter
= new MarkdownEmitter(self)
120 # Process the mardown `input` string and return the processed output.
121 fun process
(input
: String): Writable do
128 var parent
= read_lines
(input
)
129 parent
.remove_surrounding_empty_lines
130 recurse
(parent
, false)
131 # output processed text
132 return emitter
.emit
(parent
.kind
)
135 # Split `input` string into `MDLines` and create a parent `MDBlock` with it.
136 private fun read_lines
(input
: String): MDBlock do
137 var block
= new MDBlock(new MDLocation(1, 1, 1, 1))
138 var value
= new FlatBuffer
144 while i
< input
.length
do
148 while not eol
and i
< input
.length
do
153 else if c
== '\t' then
154 var np
= pos
+ (4 - (pos
.bin_and
(3)))
167 var loc
= new MDLocation(line_pos
, 1, line_pos
, col_pos
)
168 var line
= new MDLine(loc
, value
.write_to_string
)
169 var is_link_ref
= check_link_ref
(line
)
171 if not is_link_ref
then block
.add_line line
177 # Check if line is a block link definition.
178 # Return `true` if line contains a valid link ref and save it into `link_refs`.
179 private fun check_link_ref
(line
: MDLine): Bool do
181 var is_link_ref
= false
182 var id
= new FlatBuffer
183 var link
= new FlatBuffer
184 var comment
= new FlatBuffer
186 if not line
.is_empty
and line
.leading
< 4 and line
.value
[line
.leading
] == '[' then
187 pos
= line
.leading
+ 1
188 pos
= md
.read_until
(id
, pos
, ']')
189 if not id
.is_empty
and pos
+ 2 < line
.value
.length
then
190 if line
.value
[pos
+ 1] == ':' then
192 pos
= md
.skip_spaces
(pos
)
193 if line
.value
[pos
] == '<' then
195 pos
= md
.read_until
(link
, pos
, '>')
198 pos
= md
.read_until
(link
, pos
, ' ', '\n')
200 if not link
.is_empty
then
201 pos
= md
.skip_spaces
(pos
)
202 if pos
> 0 and pos
< line
.value
.length
then
203 var c
= line
.value
[pos
]
204 if c
== '\"' or c
== '\'' or c == '(' then
207 pos = md.read_until(comment, pos, ')')
209 pos = md.read_until(comment, pos, c)
211 if pos > 0 then is_link_ref = true
220 if is_link_ref and not id.is_empty and not link.is_empty then
221 var lr = new LinkRef.with_title(link.write_to_string, comment.write_to_string)
222 add_link_ref(id.write_to_string, lr)
223 if comment.is_empty then last_link_ref = lr
226 comment = new FlatBuffer
227 if not line.is_empty and last_link_ref != null then
229 var c = line.value[pos]
230 if c == '\
"' or c == '\'' or c == '(' then
233 pos = md.read_until(comment, pos, ')')
235 pos = md.read_until(comment, pos, c)
238 if not comment.is_empty then last_link_ref.title = comment.write_to_string
240 if comment.is_empty then return false
246 # This list will be needed during output to expand links.
247 var link_refs: Map[String, LinkRef] = new HashMap[String, LinkRef]
249 # Last encountered link ref (for multiline definitions)
251 # Markdown allows link refs to be defined over two lines:
253 # [id]: http://example.com/longish/path/to/resource/here
254 # "Optional Title Here"
256 private var last_link_ref: nullable LinkRef = null
258 # Add a link ref to the list
259 fun add_link_ref(key: String, ref: LinkRef) do link_refs[key.to_lower] = ref
261 # Recursively split a `block`.
263 # The block is splitted according to the type of lines it contains.
264 # Some blocks can be splited again recursively like lists.
265 # The `in_list` mode is used to recurse on list and build
266 # nested paragraphs or code blocks.
267 fun recurse(root: MDBlock, in_list: Bool) do
268 var old_mode = self.in_list
269 var old_root = self.current_block
270 self.in_list = in_list
272 var line = root.first_line
273 while line != null and line.is_empty do
275 if line == null then return
280 while current_line != null do
281 line_kind(current_line.as(not null)).process(self)
283 self.in_list = old_mode
284 self.current_block = old_root
287 # Currently processed line.
288 # Used when visiting blocks with `recurse`.
289 var current_line: nullable MDLine = null is writable
291 # Currently processed block.
292 # Used when visiting blocks with `recurse`.
293 var current_block: nullable MDBlock = null is writable
295 # Is the current recursion in list mode?
296 # Used when visiting blocks with `recurse`
297 private var in_list = false
301 fun line_kind(md: MDLine): Line do
303 var leading = md.leading
304 var trailing = md.trailing
305 if md.is_empty then return new LineEmpty
306 if md.leading > 3 then return new LineCode
307 if value[leading] == '#' then return new LineHeadline
308 if value[leading] == '>' then return new LineBlockquote
311 if value.length - leading - trailing > 2 then
312 if value[leading] == '`' and md.count_chars_start('`') >= 3 then
315 if value[leading] == '~' and md.count_chars_start('~') >= 3 then
321 if value.length - leading - trailing > 2 and
322 (value[leading] == '*' or value[leading] == '-' or value[leading] == '_') then
323 if md.count_chars(value[leading]) >= 3 then
328 if value.length - leading >= 2 and value[leading + 1] == ' ' then
329 var c = value[leading]
330 if c == '*' or c == '-' or c == '+' then return new LineUList
333 if value.length - leading >= 3 and value[leading].is_digit then
335 while i < value.length and value[i].is_digit do i += 1
336 if i + 1 < value.length and value[i] == '.' and value[i + 1] == ' ' then
341 if value[leading] == '<' and md.check_html then return new LineXML
344 if next != null and not next.is_empty then
345 if next.count_chars('=') > 0 then
346 return new LineHeadline1
348 if next.count_chars('-') > 0 then
349 return new LineHeadline2
355 # Get the token kind at `pos`.
356 fun token_at(text: Text, pos: Int): Token do
368 if pos + 1 < text.length then
373 if pos + 2 < text.length then
379 var loc = text.pos_to_loc(pos)
383 if c0 != ' ' or c2 != ' ' then
384 return new TokenStrongStar(loc, pos, c)
386 return new TokenEmStar(loc, pos, c)
389 if c0 != ' ' or c1 != ' ' then
390 return new TokenEmStar(loc, pos, c)
392 return new TokenNone(loc, pos, c)
394 else if c == '_' then
396 if c0 != ' ' or c2 != ' 'then
397 return new TokenStrongUnderscore(loc, pos, c)
399 return new TokenEmUnderscore(loc, pos, c)
403 if (c0.is_letter or c0.is_digit) and c0 != '_' and
404 (c1.is_letter or c1.is_digit) then
405 return new TokenNone(loc, pos, c)
407 return new TokenEmUnderscore(loc, pos, c)
410 if c0 != ' ' or c1 != ' ' then
411 return new TokenEmUnderscore(loc, pos, c)
413 return new TokenNone(loc, pos, c)
415 else if c == '!' then
416 if c1 == '[' then return new TokenImage(loc, pos, c)
417 return new TokenNone(loc, pos, c)
418 else if c == '[' then
419 return new TokenLink(loc, pos, c)
420 else if c == ']' then
421 return new TokenNone(loc, pos, c)
422 else if c == '`' then
424 return new TokenCodeDouble(loc, pos, c)
426 return new TokenCodeSingle(loc, pos, c)
428 else if c == '\\' then
429 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
430 return new TokenEscape(loc
, pos
, c
)
432 return new TokenNone(loc
, pos
, c
)
434 else if c
== '<' then
435 return new TokenHTML(loc
, pos
, c
)
436 else if c
== '&' then
437 return new TokenEntity(loc
, pos
, c
)
440 if c
== '~' and c1
== '~' then
441 return new TokenStrike(loc
, pos
, c
)
444 return new TokenNone(loc
, pos
, c
)
448 # Find the position of a `token` in `self`.
449 fun find_token
(text
: Text, start
: Int, token
: Token): Int do
451 while pos
< text
.length
do
452 if token_at
(text
, pos
).is_same_type
(token
) then
461 # Emit output corresponding to blocks content.
463 # Blocks are created by a previous pass in `MarkdownProcessor`.
464 # The emitter use a `Decorator` to select the output format.
465 class MarkdownEmitter
467 # Kind of processor used for parsing.
468 type PROCESSOR: MarkdownProcessor
470 # Processor containing link refs.
471 var processor
: PROCESSOR
473 # Kind of decorator used for decoration.
474 type DECORATOR: Decorator
476 # Decorator used for output.
477 # Default is `HTMLDecorator`
478 var decorator
: DECORATOR is writable, lazy
do
479 return new HTMLDecorator
482 # Create a new `MarkdownEmitter` using a custom `decorator`.
483 init with_decorator
(processor
: PROCESSOR, decorator
: DECORATOR) do
485 self.decorator
= decorator
488 # Output `block` using `decorator` in the current buffer.
489 fun emit
(block
: Block): Text do
490 var buffer
= push_buffer
496 # Output the content of `block`.
497 fun emit_in
(block
: Block) do block
.emit_in
(self)
499 # Transform and emit mardown text
500 fun emit_text
(text
: Text) do emit_text_until
(text
, 0, null)
502 # Transform and emit mardown text starting at `from` and
503 # until a token with the same type as `token` is found.
504 # Go until the end of text if `token` is null.
505 fun emit_text_until
(text
: Text, start
: Int, token
: nullable Token): Int do
506 var old_text
= current_text
507 var old_pos
= current_pos
510 while current_pos
< text
.length
do
511 var mt
= processor
.token_at
(text
, current_pos
)
512 if (token
!= null and not token
isa TokenNone) and
513 (mt
.is_same_type
(token
) or
514 (token
isa TokenEmStar and mt
isa TokenStrongStar) or
515 (token
isa TokenEmUnderscore and mt
isa TokenStrongUnderscore)) then
521 current_text
= old_text
522 current_pos
= old_pos
526 # Currently processed position in `current_text`.
527 # Used when visiting inline production with `emit_text_until`.
528 private var current_pos
: Int = -1
530 # Currently processed text.
531 # Used when visiting inline production with `emit_text_until`.
532 private var current_text
: nullable Text = null
535 private var buffer_stack
= new List[FlatBuffer]
537 # Push a new buffer on the stack.
538 private fun push_buffer
: FlatBuffer do
539 var buffer
= new FlatBuffer
540 buffer_stack
.add buffer
544 # Pop the last buffer.
545 private fun pop_buffer
do buffer_stack
.pop
547 # Current output buffer.
548 private fun current_buffer
: FlatBuffer do
549 assert not buffer_stack
.is_empty
550 return buffer_stack
.last
553 # Append `e` to current buffer.
554 fun add
(e
: Writable) do
556 current_buffer
.append e
558 current_buffer
.append e
.write_to_string
562 # Append `c` to current buffer.
563 fun addc
(c
: Char) do add c
.to_s
565 # Append a "\n" line break.
570 # Links that are specified somewhere in the mardown document to be reused as shortcuts.
573 # [1]: http://example.com/ "Optional title"
580 # Optional link title
581 var title
: nullable String = null
583 # Is the link an abreviation?
584 var is_abbrev
= false
586 # Create a link with a title.
587 init with_title
(link
: String, title
: nullable String) do
593 # A `Decorator` is used to emit mardown into a specific format.
594 # Default decorator used is `HTMLDecorator`.
597 # Kind of emitter used for decoration.
598 type EMITTER: MarkdownEmitter
600 # Render a ruler block.
601 fun add_ruler
(v
: EMITTER, block
: BlockRuler) is abstract
603 # Render a headline block with corresponding level.
604 fun add_headline
(v
: EMITTER, block
: BlockHeadline) is abstract
606 # Render a paragraph block.
607 fun add_paragraph
(v
: EMITTER, block
: BlockParagraph) is abstract
609 # Render a code or fence block.
610 fun add_code
(v
: EMITTER, block
: BlockCode) is abstract
612 # Render a blockquote.
613 fun add_blockquote
(v
: EMITTER, block
: BlockQuote) is abstract
615 # Render an unordered list.
616 fun add_unorderedlist
(v
: EMITTER, block
: BlockUnorderedList) is abstract
618 # Render an ordered list.
619 fun add_orderedlist
(v
: EMITTER, block
: BlockOrderedList) is abstract
621 # Render a list item.
622 fun add_listitem
(v
: EMITTER, block
: BlockListItem) is abstract
624 # Render an emphasis text.
625 fun add_em
(v
: EMITTER, text
: Text) is abstract
627 # Render a strong text.
628 fun add_strong
(v
: EMITTER, text
: Text) is abstract
630 # Render a strike text.
632 # Extended mode only (see `MarkdownProcessor::ext_mode`)
633 fun add_strike
(v
: EMITTER, text
: Text) is abstract
636 fun add_link
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
639 fun add_image
(v
: EMITTER, link
: Text, name
: Text, comment
: nullable Text) is abstract
641 # Render an abbreviation.
642 fun add_abbr
(v
: EMITTER, name
: Text, comment
: Text) is abstract
644 # Render a code span reading from a buffer.
645 fun add_span_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
647 # Render a text and escape it.
648 fun append_value
(v
: EMITTER, value
: Text) is abstract
650 # Render code text from buffer and escape it.
651 fun append_code
(v
: EMITTER, buffer
: Text, from
, to
: Int) is abstract
653 # Render a character escape.
654 fun escape_char
(v
: EMITTER, char
: Char) is abstract
656 # Render a line break
657 fun add_line_break
(v
: EMITTER) is abstract
659 # Generate a new html valid id from a `String`.
660 fun strip_id
(txt
: String): String is abstract
662 # Found headlines during the processing labeled by their ids.
663 fun headlines
: ArrayMap[String, HeadLine] is abstract
666 # Class representing a markdown headline.
668 # Unique identifier of this headline.
671 # Text of the headline.
674 # Level of this headline.
676 # According toe the markdown specification, level must be in `[1..6]`.
680 # `Decorator` that outputs HTML.
684 redef var headlines
= new ArrayMap[String, HeadLine]
686 redef fun add_ruler
(v
, block
) do v
.add
"<hr/>\n"
688 redef fun add_headline
(v
, block
) do
690 var txt
= block
.block
.first_line
.value
691 var id
= strip_id
(txt
)
692 var lvl
= block
.depth
693 headlines
[id
] = new HeadLine(id
, txt
, lvl
)
695 v
.add
"<h{lvl} id=\"{id}\
">"
700 redef fun add_paragraph
(v
, block
) do
706 redef fun add_code
(v
, block
) do
707 if block
isa BlockFence and block
.meta
!= null then
708 v
.add
"<pre class=\"{block.meta.to_s}\
"><code>"
713 v
.add
"</code></pre>\n"
716 redef fun add_blockquote
(v
, block
) do
717 v
.add
"<blockquote>\n"
719 v
.add
"</blockquote>\n"
722 redef fun add_unorderedlist
(v
, block
) do
728 redef fun add_orderedlist
(v
, block
) do
734 redef fun add_listitem
(v
, block
) do
740 redef fun add_em
(v
, text
) do
746 redef fun add_strong
(v
, text
) do
752 redef fun add_strike
(v
, text
) do
758 redef fun add_image
(v
, link
, name
, comment
) do
760 append_value(v, link)
762 append_value(v, name)
764 if comment
!= null and not comment
.is_empty
then
766 append_value(v, comment)
772 redef fun add_link
(v
, link
, name
, comment
) do
774 append_value(v, link)
776 if comment
!= null and not comment
.is_empty
then
778 append_value(v, comment)
786 redef fun add_abbr
(v
, name
, comment
) do
787 v
.add
"<abbr title=\""
788 append_value(v, comment)
794 redef fun add_span_code
(v
, text
, from
, to
) do
796 append_code
(v
, text
, from
, to
)
800 redef fun add_line_break
(v
) do
804 redef fun append_value
(v
, text
) do for c
in text
do escape_char
(v
, c
)
806 redef fun escape_char
(v
, c
) do
809 else if c
== '<' then
811 else if c
== '>' then
813 else if c
== '"' then
815 else if c
== '\'' then
822 redef fun append_code(v, buffer, from, to) do
823 for i in [from..to[ do
827 else if c == '<' then
829 else if c == '>' then
837 redef fun strip_id(txt) do
839 var b = new FlatBuffer
844 if not c.is_letter and
846 not allowed_id_chars.has(c) then continue
852 # check for multiple id definitions
853 if headlines.has_key(key) then
856 while headlines.has_key(key) do
864 private var allowed_id_chars: Array[Char] = ['-', '_
', ':', '.']
867 # Location in a Markdown input.
870 # Starting line number (starting from 1).
873 # Starting column number (starting from 1).
874 var column_start: Int
876 # Stopping line number (starting from 1).
879 # Stopping column number (starting from 1).
882 redef fun to_s do return "{line_start},{column_start}--{line_end},{column_end}"
885 # A block of markdown lines.
886 # A `MDBlock` can contains lines and/or sub-blocks.
889 # Position of `self` in the input.
890 var location: MDLocation
894 var kind: Block = new BlockNone(self) is writable
897 var first_line: nullable MDLine = null is writable
900 var last_line: nullable MDLine = null is writable
902 # First sub-block if any.
903 var first_block: nullable MDBlock = null is writable
905 # Last sub-block if any.
906 var last_block: nullable MDBlock = null is writable
908 # Previous block if any.
909 var prev: nullable MDBlock = null is writable
912 var next: nullable MDBlock = null is writable
914 # Does this block contain subblocks?
915 fun has_blocks: Bool do return first_block != null
918 fun count_blocks: Int do
920 var block = first_block
921 while block != null do
928 # Does this block contain lines?
929 fun has_lines: Bool do return first_line != null
932 fun count_lines: Int do
934 var line = first_line
935 while line != null do
942 # Split `self` creating a new sub-block having `line` has `last_line`.
943 fun split(line: MDLine): MDBlock do
944 # location for new block
945 var new_loc = new MDLocation(
946 first_line.location.line_start,
947 first_line.location.column_start,
948 line.location.line_end,
949 line.location.column_end)
951 var block = new MDBlock(new_loc)
952 block.first_line = first_line
953 block.last_line = line
954 first_line = line.next
956 if first_line == null then
959 first_line.prev = null
960 # update current block loc
961 location.line_start = first_line.location.line_start
962 location.column_start = first_line.location.column_start
964 if first_block == null then
968 last_block.next = block
974 # Add a `line` to this block.
975 fun add_line(line: MDLine) do
976 if last_line == null then
980 last_line.next_empty = line.is_empty
981 line.prev_empty = last_line.is_empty
982 line.prev = last_line
983 last_line.next = line
988 # Remove `line` from this block.
989 fun remove_line(line: MDLine) do
990 if line.prev == null then
991 first_line = line.next
993 line.prev.next = line.next
995 if line.next == null then
996 last_line = line.prev
998 line.next.prev = line.prev
1004 # Remove leading empty lines.
1005 fun remove_leading_empty_lines: Bool do
1006 var was_empty = false
1007 var line = first_line
1008 while line != null and line.is_empty do
1016 # Remove trailing empty lines.
1017 fun remove_trailing_empty_lines: Bool do
1018 var was_empty = false
1019 var line = last_line
1020 while line != null and line.is_empty do
1028 # Remove leading and trailing empty lines.
1029 fun remove_surrounding_empty_lines: Bool do
1030 var was_empty = false
1031 if remove_leading_empty_lines then was_empty = true
1032 if remove_trailing_empty_lines then was_empty = true
1036 # Remove list markers and up to 4 leading spaces.
1037 # Used to clean nested lists.
1038 fun remove_list_indent(v: MarkdownProcessor) do
1039 var line = first_line
1040 while line != null do
1041 if not line.is_empty then
1042 var kind = v.line_kind(line)
1043 if kind isa LineList then
1044 line.value = kind.extract_value(line)
1046 line.value = line.value.substring_from(line.leading.min(4))
1048 line.leading = line.process_leading
1054 # Collect block line text.
1056 var text = new FlatBuffer
1057 var line = first_line
1058 while line != null do
1059 if not line.is_empty then
1060 text.append line.text
1065 return text.write_to_string
1069 # Representation of a markdown block in the AST.
1070 # Each `Block` is linked to a `MDBlock` that contains mardown code.
1071 abstract class Block
1073 # The markdown block `self` is related to.
1076 # Output `self` using `v.decorator`.
1077 fun emit(v: MarkdownEmitter) do v.emit_in(self)
1079 # Emit the containts of `self`, lines or blocks.
1080 fun emit_in(v: MarkdownEmitter) do
1081 block.remove_surrounding_empty_lines
1082 if block.has_lines then
1089 # Emit lines contained in `block`.
1090 fun emit_lines(v: MarkdownEmitter) do
1091 var tpl = v.push_buffer
1092 var line = block.first_line
1093 while line != null do
1094 if not line.is_empty then
1095 v.add line.value.substring(line.leading, line.value.length - line.trailing)
1096 if line.trailing >= 2 then v.decorator.add_line_break(v)
1098 if line.next != null then
1107 # Emit sub-blocks contained in `block`.
1108 fun emit_blocks(v: MarkdownEmitter) do
1109 var block = self.block.first_block
1110 while block != null do
1117 # A block without any markdown specificities.
1119 # Actually use the same implementation than `BlockCode`,
1120 # this class is only used for typing purposes.
1125 # A markdown blockquote.
1129 redef fun emit(v) do v.decorator.add_blockquote(v, self)
1131 # Remove blockquote markers.
1132 private fun remove_block_quote_prefix(block: MDBlock) do
1133 var line = block.first_line
1134 while line != null do
1135 if not line.is_empty then
1136 if line.value[line.leading] == '>' then
1137 var rem = line.leading + 1
1138 if line.leading + 1 < line.value.length and
1139 line.value[line.leading + 1] == ' ' then
1142 line.value = line.value.substring_from(rem)
1143 line.leading = line.process_leading
1151 # A markdown code block.
1155 # Number of char to skip at the beginning of the line.
1157 # Block code lines start at 4 spaces.
1158 protected var line_start = 4
1160 redef fun emit(v) do v.decorator.add_code(v, self)
1162 redef fun emit_lines(v) do
1163 var line = block.first_line
1164 while line != null do
1165 if not line.is_empty then
1166 v.decorator.append_code(v, line.value, line_start, line.value.length)
1174 # A markdown code-fence block.
1176 # Actually use the same implementation than `BlockCode`,
1177 # this class is only used for typing purposes.
1181 # Any string found after fence token.
1182 var meta: nullable Text
1184 # Fence code lines start at 0 spaces.
1185 redef var line_start = 0
1188 # A markdown headline.
1192 redef fun emit(v) do v.decorator.add_headline(v, self)
1194 # Depth of the headline used to determine the headline level.
1197 # Remove healine marks from lines contained in `self`.
1198 private fun transform_headline(block: MDBlock) do
1199 if depth > 0 then return
1201 var line = block.first_line
1202 if line.is_empty then return
1203 var start = line.leading
1204 while start < line.value.length and line.value[start] == '#' do
1208 while start
< line
.value
.length
and line
.value
[start
] == ' ' do
1211 if start
>= line
.value
.length
then
1212 line
.is_empty
= true
1214 var nend
= line
.value
.length
- line
.trailing
- 1
1215 while line
.value
[nend
] == '#' do nend
-= 1
1216 while line
.value
[nend
] == ' ' do nend
-= 1
1217 line
.value
= line
.value
.substring
(start
, nend
- start
+ 1)
1221 depth
= level
.min
(6)
1225 # A markdown list item block.
1229 redef fun emit
(v
) do v
.decorator
.add_listitem
(v
, self)
1232 # A markdown list block.
1233 # Can be either an ordered or unordered list, this class is mainly used to factorize code.
1234 abstract class BlockList
1237 # Split list block into list items sub-blocks.
1238 private fun init_block
(v
: MarkdownProcessor) do
1239 var line
= block
.first_line
1241 while line
!= null do
1242 var t
= v
.line_kind
(line
)
1243 if t
isa LineList or
1244 (not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1245 not (t
isa LineList))) then
1246 var sblock
= block
.split
(line
.prev
.as(not null))
1247 sblock
.kind
= new BlockListItem(sblock
)
1251 var sblock
= block
.split
(block
.last_line
.as(not null))
1252 sblock
.kind
= new BlockListItem(sblock
)
1255 # Expand list items as paragraphs if needed.
1256 private fun expand_paragraphs
(block
: MDBlock) do
1257 var outer
= block
.first_block
1258 var inner
: nullable MDBlock
1259 var has_paragraph
= false
1260 while outer
!= null and not has_paragraph
do
1261 if outer
.kind
isa BlockListItem then
1262 inner
= outer
.first_block
1263 while inner
!= null and not has_paragraph
do
1264 if inner
.kind
isa BlockParagraph then
1265 has_paragraph
= true
1272 if has_paragraph
then
1273 outer
= block
.first_block
1274 while outer
!= null do
1275 if outer
.kind
isa BlockListItem then
1276 inner
= outer
.first_block
1277 while inner
!= null do
1278 if inner
.kind
isa BlockNone then
1279 inner
.kind
= new BlockParagraph(inner
)
1290 # A markdown ordered list.
1291 class BlockOrderedList
1294 redef fun emit
(v
) do v
.decorator
.add_orderedlist
(v
, self)
1297 # A markdown unordred list.
1298 class BlockUnorderedList
1301 redef fun emit
(v
) do v
.decorator
.add_unorderedlist
(v
, self)
1304 # A markdown paragraph block.
1305 class BlockParagraph
1308 redef fun emit
(v
) do v
.decorator
.add_paragraph
(v
, self)
1315 redef fun emit
(v
) do v
.decorator
.add_ruler
(v
, self)
1318 # Xml blocks that can be found in markdown markup.
1322 redef fun emit_lines
(v
) do
1323 var line
= block
.first_line
1324 while line
!= null do
1325 if not line
.is_empty
then v
.add line
.value
1335 # Location of `self` in the original input.
1336 var location
: MDLocation
1338 # Text contained in this line.
1339 var value
: String is writable
1341 # Is this line empty?
1342 # Lines containing only spaces are considered empty.
1343 var is_empty
: Bool = true is writable
1345 # Previous line in `MDBlock` or null if first line.
1346 var prev
: nullable MDLine = null is writable
1348 # Next line in `MDBlock` or null if last line.
1349 var next
: nullable MDLine = null is writable
1351 # Is the previous line empty?
1352 var prev_empty
: Bool = false is writable
1354 # Is the next line empty?
1355 var next_empty
: Bool = false is writable
1357 # Initialize a new MDLine from its string value
1359 self.leading
= process_leading
1360 if leading
!= value
.length
then
1361 self.is_empty
= false
1362 self.trailing
= process_trailing
1366 # Set `value` as an empty String and update `leading`, `trailing` and is_`empty`.
1372 if prev
!= null then prev
.next_empty
= true
1373 if next
!= null then next
.prev_empty
= true
1376 # Number or leading spaces on this line.
1377 var leading
: Int = 0 is writable
1379 # Compute `leading` depending on `value`.
1380 fun process_leading
: Int do
1382 var value
= self.value
1383 while count
< value
.length
and value
[count
] == ' ' do count
+= 1
1384 if leading
== value
.length
then clear
1388 # Number of trailing spaces on this line.
1389 var trailing
: Int = 0 is writable
1391 # Compute `trailing` depending on `value`.
1392 fun process_trailing
: Int do
1394 var value
= self.value
1395 while value
[value
.length
- count
- 1] == ' ' do
1401 # Count the amount of `ch` in this line.
1402 # Return A value > 0 if this line only consists of `ch` end spaces.
1403 fun count_chars
(ch
: Char): Int do
1419 # Count the amount of `ch` at the start of this line ignoring spaces.
1420 fun count_chars_start
(ch
: Char): Int do
1435 # Last XML line if any.
1436 private var xml_end_line
: nullable MDLine = null
1438 # Does `value` contains valid XML markup?
1439 private fun check_html
: Bool do
1440 var tags
= new Array[String]
1441 var tmp
= new FlatBuffer
1443 if pos
+ 1 < value
.length
and value
[pos
+ 1] == '!' then
1444 if read_xml_comment
(self, pos
) > 0 then return true
1446 pos
= value
.read_xml
(tmp
, pos
, false)
1450 if not tag
.is_html_block
then
1458 var line
: nullable MDLine = self
1459 while line
!= null do
1460 while pos
< line
.value
.length
and line
.value
[pos
] != '<' do
1463 if pos
>= line
.value
.length
then
1464 if pos
- 2 >= 0 and line
.value
[pos
- 2] == '/' then
1466 if tags
.is_empty
then
1474 tmp
= new FlatBuffer
1475 var new_pos
= line
.value
.read_xml
(tmp
, pos
, false)
1478 if tag
.is_html_block
and not tag
== "hr" then
1479 if tmp
[1] == '/' then
1480 if tags
.last
!= tag
then
1488 if tags
.is_empty
then
1498 return tags
.is_empty
1503 # Read a XML comment.
1504 # Used by `check_html`.
1505 private fun read_xml_comment
(first_line
: MDLine, start
: Int): Int do
1506 var line
: nullable MDLine = first_line
1507 if start
+ 3 < line
.value
.length
then
1508 if line
.value
[2] == '-' and line
.value
[3] == '-' then
1510 while line
!= null do
1511 while pos
< line
.value
.length
and line
.value
[pos
] != '-' do
1514 if pos
== line
.value
.length
then
1518 if pos
+ 2 < line
.value
.length
then
1519 if line
.value
[pos
+ 1] == '-' and line
.value
[pos
+ 2] == '>' then
1520 first_line
.xml_end_line
= line
1532 # Extract the text of `self` without leading and trailing.
1533 fun text
: String do return value
.substring
(leading
, value
.length
- trailing
)
1540 # See `MarkdownProcessor::recurse`.
1541 fun process
(v
: MarkdownProcessor) is abstract
1544 # An empty markdown line.
1548 redef fun process
(v
) do
1549 v
.current_line
= v
.current_line
.next
1553 # A non-specific markdown construction.
1554 # Mainly used as part of another line construct such as paragraphs or lists.
1558 redef fun process
(v
) do
1559 var line
= v
.current_line
1561 var was_empty
= line
.prev_empty
1562 while line
!= null and not line
.is_empty
do
1563 var t
= v
.line_kind
(line
)
1564 if (v
.in_list
or v
.ext_mode
) and t
isa LineList then
1567 if v
.ext_mode
and (t
isa LineCode or t
isa LineFence) then
1570 if t
isa LineHeadline or t
isa LineHeadline1 or t
isa LineHeadline2 or
1571 t
isa LineHR or t
isa LineBlockquote or t
isa LineXML then
1577 if line
!= null and not line
.is_empty
then
1578 var block
= v
.current_block
.split
(line
.prev
.as(not null))
1579 if v
.in_list
and not was_empty
then
1580 block
.kind
= new BlockNone(block
)
1582 block
.kind
= new BlockParagraph(block
)
1584 v
.current_block
.remove_leading_empty_lines
1587 if line
!= null then
1588 block
= v
.current_block
.split
(line
)
1590 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1592 if v
.in_list
and (line
== null or not line
.is_empty
) and not was_empty
then
1593 block
.kind
= new BlockNone(block
)
1595 block
.kind
= new BlockParagraph(block
)
1597 v
.current_block
.remove_leading_empty_lines
1599 v
.current_line
= v
.current_block
.first_line
1603 # A line of markdown code.
1607 redef fun process
(v
) do
1608 var line
= v
.current_line
1610 while line
!= null and (line
.is_empty
or v
.line_kind
(line
) isa LineCode) do
1613 # split at block end line
1615 if line
!= null then
1616 block
= v
.current_block
.split
(line
.prev
.as(not null))
1618 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1620 block
.kind
= new BlockCode(block
)
1621 block
.remove_surrounding_empty_lines
1622 v
.current_line
= v
.current_block
.first_line
1626 # A line of raw XML.
1630 redef fun process
(v
) do
1631 var line
= v
.current_line
1632 var prev
= line
.prev
1633 if prev
!= null then v
.current_block
.split
(prev
)
1634 var block
= v
.current_block
.split
(line
.xml_end_line
.as(not null))
1635 block
.kind
= new BlockXML(block
)
1636 v
.current_block
.remove_leading_empty_lines
1637 v
.current_line
= v
.current_block
.first_line
1641 # A markdown blockquote line.
1642 class LineBlockquote
1645 redef fun process
(v
) do
1646 var line
= v
.current_line
1648 while line
!= null do
1649 if not line
.is_empty
and (line
.prev_empty
and
1650 line
.leading
== 0 and
1651 not v
.line_kind
(line
) isa LineBlockquote) then break
1656 if line
!= null then
1657 block
= v
.current_block
.split
(line
.prev
.as(not null))
1659 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1661 var kind
= new BlockQuote(block
)
1663 block
.remove_surrounding_empty_lines
1664 kind
.remove_block_quote_prefix
(block
)
1665 v
.current_line
= line
1666 v
.recurse
(block
, false)
1667 v
.current_line
= v
.current_block
.first_line
1671 # A markdown ruler line.
1675 redef fun process
(v
) do
1676 var line
= v
.current_line
1677 if line
.prev
!= null then v
.current_block
.split
(line
.prev
.as(not null))
1678 var block
= v
.current_block
.split
(line
.as(not null))
1679 block
.kind
= new BlockRuler(block
)
1680 v
.current_block
.remove_leading_empty_lines
1681 v
.current_line
= v
.current_block
.first_line
1685 # A markdown fence code line.
1689 redef fun process
(v
) do
1691 var line
= v
.current_line
.next
1692 while line
!= null do
1693 if v
.line_kind
(line
) isa LineFence then break
1696 if line
!= null then
1701 if line
!= null then
1702 block
= v
.current_block
.split
(line
.prev
.as(not null))
1704 block
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1706 var meta
= block
.first_line
.value
.meta_from_fence
1707 block
.kind
= new BlockFence(block
, meta
)
1708 block
.first_line
.clear
1709 var last
= block
.last_line
1710 if last
!= null and v
.line_kind
(last
) isa LineFence then
1711 block
.last_line
.clear
1713 block
.remove_surrounding_empty_lines
1714 v
.current_line
= line
1718 # A markdown headline.
1722 redef fun process
(v
) do
1723 var line
= v
.current_line
1724 var lprev
= line
.prev
1725 if lprev
!= null then v
.current_block
.split
(lprev
)
1726 var block
= v
.current_block
.split
(line
.as(not null))
1727 var kind
= new BlockHeadline(block
)
1729 kind
.transform_headline
(block
)
1730 v
.current_block
.remove_leading_empty_lines
1731 v
.current_line
= v
.current_block
.first_line
1735 # A markdown headline of level 1.
1739 redef fun process
(v
) do
1740 var line
= v
.current_line
1741 var lprev
= line
.prev
1742 if lprev
!= null then v
.current_block
.split
(lprev
)
1744 var block
= v
.current_block
.split
(line
.as(not null))
1745 var kind
= new BlockHeadline(block
)
1747 kind
.transform_headline
(block
)
1749 v
.current_block
.remove_leading_empty_lines
1750 v
.current_line
= v
.current_block
.first_line
1754 # A markdown headline of level 2.
1758 redef fun process
(v
) do
1759 var line
= v
.current_line
1760 var lprev
= line
.prev
1761 if lprev
!= null then v
.current_block
.split
(lprev
)
1763 var block
= v
.current_block
.split
(line
.as(not null))
1764 var kind
= new BlockHeadline(block
)
1766 kind
.transform_headline
(block
)
1768 v
.current_block
.remove_leading_empty_lines
1769 v
.current_line
= v
.current_block
.first_line
1773 # A markdown list line.
1774 # Mainly used to factorize code between ordered and unordered lists.
1778 redef fun process
(v
) do
1779 var line
= v
.current_line
1781 while line
!= null do
1782 var t
= v
.line_kind
(line
)
1783 if not line
.is_empty
and (line
.prev_empty
and line
.leading
== 0 and
1784 not t
isa LineList) then break
1789 if line
!= null then
1790 list
= v
.current_block
.split
(line
.prev
.as(not null))
1792 list
= v
.current_block
.split
(v
.current_block
.last_line
.as(not null))
1794 var kind
= block_kind
(list
)
1796 list
.first_line
.prev_empty
= false
1797 list
.last_line
.next_empty
= false
1798 list
.remove_surrounding_empty_lines
1799 list
.first_line
.prev_empty
= false
1800 list
.last_line
.next_empty
= false
1802 var block
= list
.first_block
1803 while block
!= null do
1804 block
.remove_list_indent
(v
)
1805 v
.recurse
(block
, true)
1808 kind
.expand_paragraphs
(list
)
1809 v
.current_line
= line
1812 # Create a new block kind based on this line.
1813 protected fun block_kind
(block
: MDBlock): BlockList is abstract
1815 # Extract string value from `MDLine`.
1816 protected fun extract_value
(line
: MDLine): String is abstract
1819 # An ordered list line.
1823 redef fun block_kind
(block
) do return new BlockOrderedList(block
)
1825 redef fun extract_value
(line
) do
1826 return line
.value
.substring_from
(line
.value
.index_of
('.') + 2)
1830 # An unordered list line.
1834 redef fun block_kind
(block
) do return new BlockUnorderedList(block
)
1836 redef fun extract_value
(line
) do
1837 return line
.value
.substring_from
(line
.leading
+ 2)
1841 # A token represent a character in the markdown input.
1842 # Some tokens have a specific markup behaviour that is handled here.
1843 abstract class Token
1845 # Location of `self` in the original input.
1846 var location
: MDLocation
1848 # Position of `self` in input independant from lines.
1851 # Character found at `pos` in the markdown input.
1854 # Output that token using `MarkdownEmitter::decorator`.
1855 fun emit
(v
: MarkdownEmitter) do v
.addc char
1858 # A token without a specific meaning.
1863 # An emphasis token.
1864 abstract class TokenEm
1867 redef fun emit
(v
) do
1868 var tmp
= v
.push_buffer
1869 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 1, self)
1872 v
.decorator
.add_em
(v
, tmp
)
1880 # An emphasis star token.
1885 # An emphasis underscore token.
1886 class TokenEmUnderscore
1891 abstract class TokenStrong
1894 redef fun emit
(v
) do
1895 var tmp
= v
.push_buffer
1896 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
1899 v
.decorator
.add_strong
(v
, tmp
)
1900 v
.current_pos
= b
+ 1
1907 # A strong star token.
1908 class TokenStrongStar
1912 # A strong underscore token.
1913 class TokenStrongUnderscore
1918 # This class is mainly used to factorize work between single and double quoted span codes.
1919 abstract class TokenCode
1922 redef fun emit
(v
) do
1923 var a
= pos
+ next_pos
+ 1
1924 var b
= v
.processor
.find_token
(v
.current_text
.as(not null), a
, self)
1926 v
.current_pos
= b
+ next_pos
1927 while a
< b
and v
.current_text
[a
] == ' ' do a
+= 1
1929 while v
.current_text
[b
- 1] == ' ' do b
-= 1
1930 v
.decorator
.add_span_code
(v
, v
.current_text
.as(not null), a
, b
)
1937 private fun next_pos
: Int is abstract
1940 # A span code token.
1941 class TokenCodeSingle
1944 redef fun next_pos
do return 0
1947 # A doubled span code token.
1948 class TokenCodeDouble
1951 redef fun next_pos
do return 1
1954 # A link or image token.
1955 # This class is mainly used to factorize work between images and links.
1956 abstract class TokenLinkOrImage
1960 var link
: nullable Text = null
1963 var name
: nullable Text = null
1966 var comment
: nullable Text = null
1968 # Is the link construct an abbreviation?
1969 var is_abbrev
= false
1971 redef fun emit
(v
) do
1972 var tmp
= new FlatBuffer
1973 var b
= check_link
(v
, tmp
, pos
, self)
1982 # Emit the hyperlink as link or image.
1983 private fun emit_hyper
(v
: MarkdownEmitter) is abstract
1985 # Check if the link is a valid link.
1986 private fun check_link
(v
: MarkdownEmitter, out
: FlatBuffer, start
: Int, token
: Token): Int do
1987 var md
= v
.current_text
1989 if token
isa TokenLink then
1994 var tmp
= new FlatBuffer
1995 pos
= md
.read_md_link_id
(tmp
, pos
)
1996 if pos
< start
then return -1
2000 pos
= md
.skip_spaces
(pos
)
2002 var tid
= name
.write_to_string
.to_lower
2003 if v
.processor
.link_refs
.has_key
(tid
) then
2004 var lr
= v
.processor
.link_refs
[tid
]
2005 is_abbrev
= lr
.is_abbrev
2012 else if md
[pos
] == '(' then
2014 pos
= md
.skip_spaces
(pos
)
2015 if pos
< start
then return -1
2016 tmp
= new FlatBuffer
2017 var use_lt
= md
[pos
] == '<'
2019 pos
= md
.read_until
(tmp
, pos
+ 1, '>')
2021 pos
= md
.read_md_link
(tmp
, pos
)
2023 if pos
< start
then return -1
2024 if use_lt
then pos
+= 1
2025 link
= tmp
.write_to_string
2026 if md
[pos
] == ' ' then
2027 pos
= md
.skip_spaces
(pos
)
2028 if pos
> start
and md
[pos
] == '"' then
2030 tmp
= new FlatBuffer
2031 pos
= md
.read_until
(tmp
, pos
, '"')
2032 if pos
< start
then return -1
2033 comment
= tmp
.write_to_string
2035 pos
= md
.skip_spaces
(pos
)
2036 if pos
== -1 then return -1
2039 if md
[pos
] != ')' then return -1
2040 else if md
[pos
] == '[' then
2042 tmp
= new FlatBuffer
2043 pos
= md
.read_raw_until
(tmp
, pos
, ']')
2044 if pos
< start
then return -1
2046 if tmp
.length
> 0 then
2051 var tid
= id
.write_to_string
.to_lower
2052 if v
.processor
.link_refs
.has_key
(tid
) then
2053 var lr
= v
.processor
.link_refs
[tid
]
2058 var tid
= name
.write_to_string
.replace
("\n", " ").to_lower
2059 if v
.processor
.link_refs
.has_key
(tid
) then
2060 var lr
= v
.processor
.link_refs
[tid
]
2068 if link
== null then return -1
2073 # A markdown link token.
2075 super TokenLinkOrImage
2077 redef fun emit_hyper
(v
) do
2078 if is_abbrev
and comment
!= null then
2079 v
.decorator
.add_abbr
(v
, name
.as(not null), comment
.as(not null))
2081 v
.decorator
.add_link
(v
, link
.as(not null), name
.as(not null), comment
)
2086 # A markdown image token.
2088 super TokenLinkOrImage
2090 redef fun emit_hyper
(v
) do
2091 v
.decorator
.add_image
(v
, link
.as(not null), name
.as(not null), comment
)
2099 redef fun emit
(v
) do
2100 var tmp
= new FlatBuffer
2101 var b
= check_html
(v
, tmp
, v
.current_text
.as(not null), v
.current_pos
)
2106 v
.decorator
.escape_char
(v
, char
)
2110 # Is the HTML valid?
2111 # Also take care of link and mailto shortcuts.
2112 private fun check_html
(v
: MarkdownEmitter, out
: FlatBuffer, md
: Text, start
: Int): Int do
2113 # check for auto links
2114 var tmp
= new FlatBuffer
2115 var pos
= md
.read_until
(tmp
, start
+ 1, ':', ' ', '>', '\n')
2116 if pos
!= -1 and md
[pos
] == ':' and tmp
.is_link_prefix
then
2117 pos
= md
.read_until
(tmp
, pos
, '>')
2119 var link
= tmp
.write_to_string
2120 v
.decorator
.add_link
(v
, link
, link
, null)
2124 # TODO check for mailto
2125 # check for inline html
2126 if start
+ 2 < md
.length
then
2127 return md
.read_xml
(out
, start
, true)
2133 # An HTML entity token.
2137 redef fun emit
(v
) do
2138 var tmp
= new FlatBuffer
2139 var b
= check_entity
(tmp
, v
.current_text
.as(not null), pos
)
2144 v
.decorator
.escape_char
(v
, char
)
2148 # Is the entity valid?
2149 private fun check_entity
(out
: FlatBuffer, md
: Text, start
: Int): Int do
2150 var pos
= md
.read_until
(out
, start
, ';')
2151 if pos
< 0 or out
.length
< 3 then
2154 if out
[1] == '#' then
2155 if out
[2] == 'x' or out
[2] == 'X' then
2156 if out
.length
< 4 then return -1
2157 for i
in [3..out
.length
[ do
2159 if (c
< '0' or c
> '9') and (c
< 'a' and c
> 'f') and (c
< 'A' and c
> 'F') then
2164 for i
in [2..out
.length
[ do
2166 if c
< '0' or c
> '9' then return -1
2171 for i
in [1..out
.length
[ do
2173 if not c
.is_digit
and not c
.is_letter
then return -1
2176 # TODO check entity is valid
2177 # if out.is_entity then
2187 # A markdown escape token.
2191 redef fun emit
(v
) do
2193 v
.addc v
.current_text
[v
.current_pos
]
2197 # A markdown strike token.
2199 # Extended mode only (see `MarkdownProcessor::ext_mode`)
2203 redef fun emit
(v
) do
2204 var tmp
= v
.push_buffer
2205 var b
= v
.emit_text_until
(v
.current_text
.as(not null), pos
+ 2, self)
2208 v
.decorator
.add_strike
(v
, tmp
)
2209 v
.current_pos
= b
+ 1
2218 # Get the position of the next non-space character.
2219 private fun skip_spaces
(start
: Int): Int do
2221 while pos
> -1 and pos
< length
and (self[pos
] == ' ' or self[pos
] == '\n') do
2224 if pos
< length
then return pos
2228 # Read `self` until `nend` and append it to the `out` buffer.
2229 # Escape markdown special chars.
2230 private fun read_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2232 while pos
< length
do
2234 if c
== '\\' and pos
+ 1 < length
then
2235 pos
= escape
(out
, self[pos
+ 1], pos
)
2237 var end_reached
= false
2244 if end_reached
then break
2249 if pos
== length
then return -1
2253 # Read `self` as raw text until `nend` and append it to the `out` buffer.
2254 # No escape is made.
2255 private fun read_raw_until
(out
: FlatBuffer, start
: Int, nend
: Char...): Int do
2257 while pos
< length
do
2259 var end_reached
= false
2266 if end_reached
then break
2270 if pos
== length
then return -1
2274 # Read `self` as XML until `to` and append it to the `out` buffer.
2275 # Escape HTML special chars.
2276 private fun read_xml_until
(out
: FlatBuffer, from
: Int, to
: Char...): Int do
2279 var str_char
: nullable Char = null
2280 while pos
< length
do
2286 if pos
< length
then
2292 if c
== str_char
then
2299 if c
== '"' or c
== '\'' then
2304 var end_reached = false
2305 for n in [0..to.length[ do
2311 if end_reached then break
2316 if pos == length then return -1
2320 # Read `self` as XML and append it to the `out` buffer.
2321 # Safe mode can be activated to limit reading to valid xml.
2322 private fun read_xml(out: FlatBuffer, start: Int, safe_mode: Bool): Int do
2325 var is_close_tag = false
2326 if start + 1 >= length then return -1
2327 if self[start + 1] == '/' then
2330 else if self[start + 1] == '!' then
2334 is_close_tag = false
2338 var tmp = new FlatBuffer
2339 pos = read_xml_until(tmp, pos, ' ', '/', '>')
2340 if pos == -1 then return -1
2341 var tag = tmp.write_to_string.trim.to_lower
2342 if not tag.is_valid_html_tag then
2345 else if tag.is_html_unsafe then
2348 if is_close_tag then out.add '/'
2352 if is_close_tag then out.add '/'
2357 if is_close_tag then out.add '/'
2358 pos = read_xml_until(out, pos, ' ', '/', '>')
2360 if pos == -1 then return -1
2361 pos = read_xml_until(out, pos, '/', '>')
2362 if pos == -1 then return -1
2363 if self[pos] == '/' then
2365 pos = self.read_xml_until(out, pos + 1, '>')
2366 if pos == -1 then return -1
2368 if self[pos] == '>' then
2379 # Read a markdown link address and append it to the `out` buffer.
2380 private fun read_md_link(out: FlatBuffer, start: Int): Int do
2383 while pos < length do
2385 if c == '\\
' and pos + 1 < length then
2386 pos = escape(out, self[pos + 1], pos)
2388 var end_reached = false
2391 else if c == ' ' then
2392 if counter == 1 then end_reached = true
2393 else if c == ')' then
2395 if counter == 0 then end_reached = true
2397 if end_reached then break
2402 if pos == length then return -1
2406 # Read a markdown link text and append it to the `out` buffer.
2407 private fun read_md_link_id(out: FlatBuffer, start: Int): Int do
2410 while pos < length do
2412 var end_reached = false
2416 else if c == ']' then
2418 if counter == 0 then
2426 if end_reached then break
2429 if pos == length then return -1
2433 # Extract the XML tag name from a XML tag.
2434 private fun xml_tag: String do
2435 var tpl = new FlatBuffer
2437 if pos < length and self[1] == '/' then pos += 1
2438 while pos < length - 1 and (self[pos].is_digit or self[pos].is_letter) do
2442 return tpl.write_to_string.to_lower
2445 private fun is_valid_html_tag: Bool do
2446 if is_empty then return false
2448 if not c.is_alpha then return false
2453 # Read and escape the markdown contained in `self`.
2454 private fun escape(out: FlatBuffer, c: Char, pos: Int): Int do
2455 if c == '\\
' or c == '[' or c == ']' or c == '(' or c == ')' or c == '{' or
2456 c == '}' or c == '#' or c == '"' or c == '\'' or c == '.' or c == '<' or
2457 c
== '>' or c
== '*' or c
== '+' or c
== '-' or c
== '_' or c
== '!' or
2458 c
== '`' or c
== '~' or c
== '^' then
2466 # Extract string found at end of fence opening.
2467 private fun meta_from_fence
: nullable Text do
2468 for i
in [0..chars
.length
[ do
2470 if c
!= ' ' and c
!= '`' and c
!= '~' then
2471 return substring_from
(i
).trim
2477 # Init a `MDLocation` instance at `pos` in `self`.
2478 private fun pos_to_loc
(pos
: Int): MDLocation do
2479 assert pos
<= length
2492 return new MDLocation(line
, col
, line
, col
)
2495 # Is `self` an unsafe HTML element?
2496 private fun is_html_unsafe
: Bool do return html_unsafe_tags
.has
(self.write_to_string
)
2498 # Is `self` a HRML block element?
2499 private fun is_html_block
: Bool do return html_block_tags
.has
(self.write_to_string
)
2501 # Is `self` a link prefix?
2502 private fun is_link_prefix
: Bool do return html_link_prefixes
.has
(self.write_to_string
)
2504 private fun html_unsafe_tags
: Array[String] do return once
["applet", "head", "body", "frame", "frameset", "iframe", "script", "object"]
2506 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"]
2508 private fun html_link_prefixes
: Array[String] do return once
["http", "https", "ftp", "ftps"]
2513 # Parse `self` as markdown and return the HTML representation
2515 # var md = "**Hello World!**"
2516 # var html = md.md_to_html
2517 # assert html == "<p><strong>Hello World!</strong></p>\n"
2518 fun md_to_html
: Writable do
2519 var processor
= new MarkdownProcessor
2520 return processor
.process
(self)