From 136ab6f7e53813007573375e5fda312739dc67e0 Mon Sep 17 00:00:00 2001 From: Ugric Date: Mon, 3 Aug 2026 22:42:47 +0100 Subject: [PATCH] init markdown system --- .gitattributes | 3 + .gitignore | 6 + argon-package.json | 4 + example.ar | 636 +++++++++++++++++++++++++++++++++++++++++++++ iso-lock.json | 1 + src/init.ar | 509 ++++++++++++++++++++++++++++++++++++ 6 files changed, 1159 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 argon-package.json create mode 100644 example.ar create mode 100644 iso-lock.json create mode 100644 src/init.ar diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..82cbd7a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +sample/bbb_sunflower_1080p_60fps_normal.mp4 filter=lfs diff=lfs merge=lfs -text +*.ar linguist-language=Argon +*.ar linguist-detectable=true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc341af --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +__isotope__ +__arcache__ +argon_modules + + +network/ \ No newline at end of file diff --git a/argon-package.json b/argon-package.json new file mode 100644 index 0000000..cf15beb --- /dev/null +++ b/argon-package.json @@ -0,0 +1,4 @@ +{ + "name": "markdown", + "version": "0.0.1" +} \ No newline at end of file diff --git a/example.ar b/example.ar new file mode 100644 index 0000000..99820ea --- /dev/null +++ b/example.ar @@ -0,0 +1,636 @@ +import "src" expose markdown_to_html + +term.log(markdown_to_html(`# Headers + +$("`")$("`")$("`") +# h1 Heading 8-) +## h2 Heading +### h3 Heading +#### h4 Heading +##### h5 Heading +###### h6 Heading + +Alternatively, for H1 and H2, an underline-ish style: + +Alt-H1 +====== + +Alt-H2 +------ + +$("`")$("`")$("`") + +# h1 Heading 8-) +## h2 Heading +### h3 Heading +#### h4 Heading +##### h5 Heading +###### h6 Heading + +Alternatively, for H1 and H2, an underline-ish style: + +Alt-H1 +====== + +Alt-H2 +------ + +------ + +# Emphasis + +$("`")$("`")$("`") +Emphasis, aka italics, with *asterisks* or _underscores_. + +Strong emphasis, aka bold, with **asterisks** or __underscores__. + +Combined emphasis with **asterisks and _underscores_**. + +Strikethrough uses two tildes. ~~Scratch this.~~ + +**This is bold text** + +__This is bold text__ + +*This is italic text* + +_This is italic text_ + +~~Strikethrough~~ +$("`")$("`")$("`") + +Emphasis, aka italics, with *asterisks* or _underscores_. + +Strong emphasis, aka bold, with **asterisks** or __underscores__. + +Combined emphasis with **asterisks and _underscores_**. + +Strikethrough uses two tildes. ~~Scratch this.~~ + +**This is bold text** + +__This is bold text__ + +*This is italic text* + +_This is italic text_ + +~~Strikethrough~~ + +------ + +# Lists + +$("`")$("`")$("`") +1. First ordered list item +2. Another item +⋅⋅* Unordered sub-list. +1. Actual numbers don't matter, just that it's a number +⋅⋅1. Ordered sub-list +4. And another item. + +⋅⋅⋅You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). + +⋅⋅⋅To have a line break without a paragraph, you will need to use two trailing spaces.⋅⋅ +⋅⋅⋅Note that this line is separate, but within the same paragraph.⋅⋅ +⋅⋅⋅(This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.) + +* Unordered list can use asterisks +- Or minuses ++ Or pluses + +1. Make my changes + 1. Fix bug + 2. Improve formatting + - Make the headings bigger +2. Push my commits to GitHub +3. Open a pull request + * Describe my changes + * Mention all the members of my team + * Ask for feedback + ++ Create a list by starting a line with $("`")+$("`"), $("`")-$("`"), or $("`")*$("`") ++ Sub-lists are made by indenting 2 spaces: + - Marker character change forces new list start: + * Ac tristique libero volutpat at + + Facilisis in pretium nisl aliquet + - Nulla volutpat aliquam velit ++ Very easy! +$("`")$("`")$("`") + +1. First ordered list item +2. Another item +⋅⋅* Unordered sub-list. +1. Actual numbers don't matter, just that it's a number +⋅⋅1. Ordered sub-list +4. And another item. + +⋅⋅⋅You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown). + +⋅⋅⋅To have a line break without a paragraph, you will need to use two trailing spaces.⋅⋅ +⋅⋅⋅Note that this line is separate, but within the same paragraph.⋅⋅ +⋅⋅⋅(This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.) + +* Unordered list can use asterisks +- Or minuses ++ Or pluses + +1. Make my changes + 1. Fix bug + 2. Improve formatting + - Make the headings bigger +2. Push my commits to GitHub +3. Open a pull request + * Describe my changes + * Mention all the members of my team + * Ask for feedback + ++ Create a list by starting a line with $("`")+$("`"), $("`")-$("`"), or $("`")*$("`") ++ Sub-lists are made by indenting 2 spaces: + - Marker character change forces new list start: + * Ac tristique libero volutpat at + + Facilisis in pretium nisl aliquet + - Nulla volutpat aliquam velit ++ Very easy! + +------ + +# Task lists + +$("`")$("`")$("`") +- [x] Finish my changes +- [ ] Push my commits to GitHub +- [ ] Open a pull request +- [x] @mentions, #refs, [links](), **formatting**, and tags supported +- [x] list syntax required (any unordered or ordered list supported) +- [x] this is a complete item +- [ ] this is an incomplete item +$("`")$("`")$("`") + +- [x] Finish my changes +- [ ] Push my commits to GitHub +- [ ] Open a pull request +- [x] @mentions, #refs, [links](), **formatting**, and tags supported +- [x] list syntax required (any unordered or ordered list supported) +- [ ] this is a complete item +- [ ] this is an incomplete item + +------ + +# Ignoring Markdown formatting + +You can tell GitHub to ignore (or escape) Markdown formatting by using \\ before the Markdown character. + +$("`")$("`")$("`") +Let's rename \\*our-new-project\\* to \\*our-old-project\\*. +$("`")$("`")$("`") + +Let's rename \\*our-new-project\\* to \\*our-old-project\\*. + +------ + +# Links + +$("`")$("`")$("`") +[I'm an inline-style link](https://www.google.com) + +[I'm an inline-style link with title](https://www.google.com "Google's Homepage") + +[I'm a reference-style link][Arbitrary case-insensitive reference text] + +[I'm a relative reference to a repository file](../blob/master/LICENSE) + +[You can use numbers for reference-style link definitions][1] + +Or leave it empty and use the [link text itself]. + +URLs and URLs in angle brackets will automatically get turned into links. +http://www.example.com or and sometimes +example.com (but not on Github, for example). + +Some text to show that the reference links can follow later. + +[arbitrary case-insensitive reference text]: https://www.mozilla.org +[1]: http://slashdot.org +[link text itself]: http://www.reddit.com +$("`")$("`")$("`") + +[I'm an inline-style link](https://www.google.com) + +[I'm an inline-style link with title](https://www.google.com "Google's Homepage") + +[I'm a reference-style link][Arbitrary case-insensitive reference text] + +[I'm a relative reference to a repository file](../blob/master/LICENSE) + +[You can use numbers for reference-style link definitions][1] + +Or leave it empty and use the [link text itself]. + +URLs and URLs in angle brackets will automatically get turned into links. +http://www.example.com or and sometimes +example.com (but not on Github, for example). + +Some text to show that the reference links can follow later. + +[arbitrary case-insensitive reference text]: https://www.mozilla.org +[1]: http://slashdot.org +[link text itself]: http://www.reddit.com + +------ + +# Images + +$("`")$("`")$("`") +Here's our logo (hover to see the title text): + +Inline-style: +![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 1") + +Reference-style: +![alt text][logo] + +[logo]: https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 2" + +![Minion](https://octodex.github.com/images/minion.png) +![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg "The Stormtroopocat") + +Like links, Images also have a footnote style syntax + +![Alt text][id] + +With a reference later in the document defining the URL location: + +[id]: https://octodex.github.com/images/dojocat.jpg "The Dojocat" +$("`")$("`")$("`") + +Here's our logo (hover to see the title text): + +Inline-style: +![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 1") + +Reference-style: +![alt text][logo] + +[logo]: https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 2" + +![Minion](https://octodex.github.com/images/minion.png) +![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg "The Stormtroopocat") + +Like links, Images also have a footnote style syntax + +![Alt text][id] + +With a reference later in the document defining the URL location: + +[id]: https://octodex.github.com/images/dojocat.jpg "The Dojocat" + +------ + +# [Footnotes](https://github.com/markdown-it/markdown-it-footnote) + +$("`")$("`")$("`") +Footnote 1 link[^first]. + +Footnote 2 link[^second]. + +Inline footnote^[Text of inline footnote] definition. + +Duplicated footnote reference[^second]. + +[^first]: Footnote **can have markup** + + and multiple paragraphs. + +[^second]: Footnote text. +$("`")$("`")$("`") + +Footnote 1 link[^first]. + +Footnote 2 link[^second]. + +Inline footnote^[Text of inline footnote] definition. + +Duplicated footnote reference[^second]. + +[^first]: Footnote **can have markup** + + and multiple paragraphs. + +[^second]: Footnote text. + +------ + +# Code and Syntax Highlighting + +$("`")$("`")$("`") +Inline $("`")code$("`") has $("`")back-ticks around$("`") it. +$("`")$("`")$("`") + +Inline $("`")code$("`") has $("`")back-ticks around$("`") it. + +$("`")$("`")$("`")c# +using System.IO.Compression; + +#pragma warning disable 414, 3021 + +namespace MyApplication +{ + [Obsolete("...")] + class Program : IInterface + { + public static List JustDoIt(int count) + { + Console.WriteLine($"Hello {Name}!"); + return new List(new int[] { 1, 2, 3 }) + } + } +} +$("`")$("`")$("`") + +$("`")$("`")$("`")css +@font-face { + font-family: Chunkfive; src: url('Chunkfive.otf'); +} + +body, .usertext { + color: #F0F0F0; background: #600; + font-family: Chunkfive, sans; +} + +@import url(print.css); +@media print { + a[href^=http]::after { + content: attr(href) + } +} +$("`")$("`")$("`") + +$("`")$("`")$("`")javascript +function $initHighlight(block, cls) { + try { + if (cls.search(/\\bno\\-highlight\\b/) != -1) + return process(block, true, 0x0F) + + $("`") class="${cls}"$("`"); + } catch (e) { + /* handle exception */ + } + for (var i = 0 / 2; i < classes.length; i++) { + if (checkCondition(classes[i]) === undefined) + console.log('undefined'); + } +} + +export $initHighlight; +$("`")$("`")$("`") + +$("`")$("`")$("`")php +require_once 'Zend/Uri/Http.php'; + +namespace Location\\Web; + +interface Factory +{ + static function _factory(); +} + +abstract class URI extends BaseURI implements Factory +{ + abstract function test(); + + public static $st1 = 1; + const ME = "Yo"; + var $list = NULL; + private $var; + + /** + * Returns a URI + * + * @return URI + */ + static public function _factory($stats = array(), $uri = 'http') + { + echo __METHOD__; + $uri = explode(':', $uri, 0b10); + $schemeSpecific = isset($uri[1]) ? $uri[1] : ''; + $desc = 'Multi +line description'; + + // Security check + if (!ctype_alnum($scheme)) { + throw new Zend_Uri_Exception('Illegal scheme'); + } + + $this->var = 0 - self::$st; + $this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \\Location\\Web\\URI::class)); + + return [ + 'uri' => $uri, + 'value' => null, + ]; + } +} + +echo URI::ME . URI::$st1; + +__halt_compiler () ; datahere +datahere +datahere */ +datahere +$("`")$("`")$("`") + +------ + +# Tables + +$("`")$("`")$("`") +Colons can be used to align columns. + +| Tables | Are | Cool | +| ------------- |:-------------:| -----:| +| col 3 is | right-aligned | $1600 | +| col 2 is | centered | $12 | +| zebra stripes | are neat | $1 | + +There must be at least 3 dashes separating each header cell. +The outer pipes (|) are optional, and you don't need to make the +raw Markdown line up prettily. You can also use inline Markdown. + +Markdown | Less | Pretty +--- | --- | --- +*Still* | $("`")renders$("`") | **nicely** +1 | 2 | 3 + +| First Header | Second Header | +| ------------- | ------------- | +| Content Cell | Content Cell | +| Content Cell | Content Cell | + +| Command | Description | +| --- | --- | +| git status | List all new or modified files | +| git diff | Show file differences that haven't been staged | + +| Command | Description | +| --- | --- | +| $("`")git status$("`") | List all *new or modified* files | +| $("`")git diff$("`") | Show file differences that **haven't been** staged | + +| Left-aligned | Center-aligned | Right-aligned | +| :--- | :---: | ---: | +| git status | git status | git status | +| git diff | git diff | git diff | + +| Name | Character | +| --- | --- | +| Backtick | $("`") | +| Pipe | \\| | +$("`")$("`")$("`") + +Colons can be used to align columns. + +| Tables | Are | Cool | +| ------------- |:-------------:| -----:| +| col 3 is | right-aligned | $1600 | +| col 2 is | centered | $12 | +| zebra stripes | are neat | $1 | + +There must be at least 3 dashes separating each header cell. +The outer pipes (|) are optional, and you don't need to make the +raw Markdown line up prettily. You can also use inline Markdown. + +Markdown | Less | Pretty +--- | --- | --- +*Still* | $("`")renders$("`") | **nicely** +1 | 2 | 3 + +| First Header | Second Header | +| ------------- | ------------- | +| Content Cell | Content Cell | +| Content Cell | Content Cell | + +| Command | Description | +| --- | --- | +| git status | List all new or modified files | +| git diff | Show file differences that haven't been staged | + +| Command | Description | +| --- | --- | +| $("`")git status$("`") | List all *new or modified* files | +| $("`")git diff$("`") | Show file differences that **haven't been** staged | + +| Left-aligned | Center-aligned | Right-aligned | +| :--- | :---: | ---: | +| git status | git status | git status | +| git diff | git diff | git diff | + +| Name | Character | +| --- | --- | +| Backtick | $("`") | +| Pipe | \\| | + +------ + +# Blockquotes + +$("`")$("`")$("`") +> Blockquotes are very handy in email to emulate reply text. +> This line is part of the same quote. + +Quote break. + +> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote. + +> Blockquotes can also be nested... +>> ...by using additional greater-than signs right next to each other... +> > > ...or with spaces between arrows. +$("`")$("`")$("`") + +> Blockquotes are very handy in email to emulate reply text. +> This line is part of the same quote. + +Quote break. + +> This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote. + +> Blockquotes can also be nested... +>> ...by using additional greater-than signs right next to each other... +> > > ...or with spaces between arrows. + +------ + +# Inline HTML + +$("`")$("`")$("`") +
+
Definition list
+
Is something people use sometimes.
+ +
Markdown in HTML
+
Does *not* work **very** well. Use HTML tags.
+
+$("`")$("`")$("`") + +
+
Definition list
+
Is something people use sometimes.
+ +
Markdown in HTML
+
Does *not* work **very** well. Use HTML tags.
+
+ +------ + +# Horizontal Rules + +$("`")$("`")$("`") +Three or more... + +--- + +Hyphens + +*** + +Asterisks + +___ + +Underscores +$("`")$("`")$("`") + +Three or more... + +--- + +Hyphens + +*** + +Asterisks + +___ + +Underscores + +------ + +# YouTube Videos + +$("`")$("`")$("`") + +IMAGE ALT TEXT HERE + +$("`")$("`")$("`") + + +IMAGE ALT TEXT HERE + + +$("`")$("`")$("`") +[![IMAGE ALT TEXT HERE](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE) +$("`")$("`")$("`") + +[![IMAGE ALT TEXT HERE](https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/YouTube_logo_2015.svg/1200px-YouTube_logo_2015.svg.png)](https://www.youtube.com/watch?v=ciawICBvQoE)`)) + +term.log("XSS: ", markdown_to_html("[I'm an inline-style link with title](\"> HTML converter. Handles block-level structure (ATX +# headings, setext headings, paragraphs, blockquotes, fenced code blocks, +# ordered/unordered lists, horizontal rules) and inline formatting (bold, +# italic, strikethrough, inline code, links w/ titles, images, autolinks, +# backslash escapes, hard line breaks). Not full CommonMark: no tables, +# no reference-style links, no footnotes. +# +# Regex API used (per the project's actual regex.ar stdlib module): +# re.match(subject) -> bool, whether the pattern matches anywhere +# re.group(subject, index) -> capture group text for the first match +# (index 0 = whole match), independent of +# any prior .match() call +# re.find_all(subject) -> list of matched substrings (no positions) +# re.replace_all(subj, repl) -> whole-pattern substitution +# +# Since there's no way to get a match's start/end offset, inline scanning +# is done manually (character-by-character) rather than by racing multiple +# patterns against each other; regex is used only for line-level block +# classification and for splitting out capture groups (heading level/text, +# link title, etc.) once we already know a construct starts at a given spot. + +import "maths" as maths +import "regex" as regex + +let escape_html(s) = do + return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) + +let sanitize_url(url) = do + let u = url.strip(" ") + + # Reject dangerous schemes. + let lower = u.lower() + + if (lower.index_of("javascript:") == 0) return "" + if (lower.index_of("vbscript:") == 0) return "" + if (lower.index_of("data:") == 0) return "" + + return escape_html(u) + +let __is_digit__(c) = c >= "0" && c <= "9" + +# --------------------------------------------------------------------------- +# Compiled patterns +# --------------------------------------------------------------------------- + +let __HEADING_RE__ = regex.Regex.intern("^(#{1,6})(?:\\s+(.*))?$") +let __HR_RE__ = regex.Regex.intern("^(?:\\*[ \\t]*){3,}$|^(?:-[ \\t]*){3,}$|^(?:_[ \\t]*){3,}$") +let __FENCE_RE__ = regex.Regex.intern("^(```|~~~)(.*)$") +let __BLOCKQUOTE_RE__ = regex.Regex.intern("^>[ \\t]?(.*)$") +let __UL_RE__ = regex.Regex.intern("^( *)[-*+] (.*)$") +let __OL_RE__ = regex.Regex.intern("^( *)(\\d+)[.)] (.*)$") +let __SETEXT_EQ_RE__ = regex.Regex.intern("^=+[ \\t]*$") +let __SETEXT_DASH_RE__ = regex.Regex.intern("^-+[ \\t]*$") +let __TABLE_DELIM_RE__ = regex.Regex.intern("^\\|?\\s*:?-+:?\\s*(\\|\\s*:?-+:?\\s*)*\\|?$") + +# Used only after we've already located a "url title" chunk between the +# parens of a link/image, to split off an optional quoted title. +let __DEST_TITLE_RE__ = regex.Regex.intern("^(.*?)\\s+[\"']([^\"']*)[\"']$") + +# --------------------------------------------------------------------------- +# Inline scanning helpers (manual, character-by-character) +# --------------------------------------------------------------------------- + +# Finds the index of the next occurrence of `needle` in `s` starting at +# `from_idx`, or -1 if absent. +let __find_from__(s, needle, from_idx) = do + if (from_idx >= s.length) return -1 + let rest = s[from_idx:s.length] + let pos = rest.index_of(needle) + if (pos < 0) return -1 + return pos + from_idx + +# Splits a markdown link/image destination like `url "title"` or +# `url 'title'` into its url and title parts, using the regex group API +# now that we have a concrete substring to test rather than needing +# position info. +let __split_dest_title__(dest) = do + let trimmed = dest.strip(" ") + if (__DEST_TITLE_RE__.match(trimmed)) do + let url = __DEST_TITLE_RE__.group(trimmed, 1) + let title = __DEST_TITLE_RE__.group(trimmed, 2) + return { url: url.strip(" "), title: title } + return { url: trimmed, title: "" } + +# Renders inline markdown within a single logical line (already joined from +# a paragraph or heading text). Processes left-to-right, emitting HTML as +# it goes. +let render_inline(text) = do + let out = "" + let i = 0 + let n = text.length + + while (i < n) do + let c = text[i] + + # Backslash escape: \X emits X literally (HTML-escaped). + if (c == "\\" && i + 1 < n) do + let escaped = text[i + 1] + out = out + escape_html(escaped) + i = i + 2 + + # Strikethrough: ~~...~~ + else if (c == "~" && i + 1 < n && text[i + 1] == "~") do + let close = __find_from__(text, "~~", i + 2) + if (close < 0) do + out = out + escape_html(c) + i = i + 1 + else do + let inner = text[i + 2:close] + out = out + "" + render_inline(inner) + "" + i = close + 2 + + # Inline code span: `...` + else if (c == "`") do + let close = __find_from__(text, "`", i + 1) + if (close < 0) do + out = out + escape_html(c) + i = i + 1 + else do + let code_content = text[i + 1:close] + out = out + "" + escape_html(code_content) + "" + i = close + 1 + + # Image: ![alt](src "title") + else if (c == "!" && i + 1 < n && text[i + 1] == "[") do + let bracket_close = __find_from__(text, "]", i + 2) + if (bracket_close < 0 || bracket_close + 1 >= n || text[bracket_close + 1] != "(") do + out = out + c + i = i + 1 + else do + let paren_close = __find_from__(text, ")", bracket_close + 2) + if (paren_close < 0) do + out = out + c + i = i + 1 + else do + let alt = text[i + 2:bracket_close] + let dest = __split_dest_title__(text[bracket_close + 2:paren_close]) + let title_attr = do + if (dest.title != "") return " title=\"" + escape_html(dest.title) + "\"" + return "" + out = out + "\""" + i = paren_close + 1 + + # Link: [text](href "title") + else if (c == "[") do + let bracket_close = __find_from__(text, "]", i + 1) + if (bracket_close < 0 || bracket_close + 1 >= n || text[bracket_close + 1] != "(") do + out = out + escape_html(c) + i = i + 1 + else do + let paren_close = __find_from__(text, ")", bracket_close + 2) + if (paren_close < 0) do + out = out + escape_html(c) + i = i + 1 + else do + let label = text[i + 1:bracket_close] + let dest = __split_dest_title__(text[bracket_close + 2:paren_close]) + let title_attr = do + if (dest.title != "") return " title=\"" + escape_html(dest.title) + "\"" + return "" + out = out + "" + render_inline(label) + "" + i = paren_close + 1 + + # Autolink: + else if (c == "<") do + let close = __find_from__(text, ">", i + 1) + let looks_like_url = false + if (close > i) do + let inner = text[i + 1:close] + if (inner.index_of("http://") == 0 || inner.index_of("https://") == 0) looks_like_url = true + if (looks_like_url) do + let href = text[i + 1:close] + out = out + "" + escape_html(href) + "" + i = close + 1 + else do + out = out + "<" + i = i + 1 + + # Bold: **...** or __...__ + else if ((c == "*" || c == "_") && i + 1 < n && text[i + 1] == c) do + let marker = c + c + let close = __find_from__(text, marker, i + 2) + if (close < 0) do + out = out + escape_html(c) + i = i + 1 + else do + let inner = text[i + 2:close] + out = out + "" + render_inline(inner) + "" + i = close + 2 + + # Italic: *...* or _..._ + else if (c == "*" || c == "_") do + let close = __find_from__(text, c, i + 1) + if (close < 0 || close == i + 1) do + out = out + escape_html(c) + i = i + 1 + else do + let inner = text[i + 1:close] + out = out + "" + render_inline(inner) + "" + i = close + 1 + + else if (c == "&") do + out = out + "&" + i = i + 1 + else if (c == "<") do + out = out + "<" + i = i + 1 + else if (c == ">") do + out = out + ">" + i = i + 1 + + else do + out = out + c + i = i + 1 + + return out + +# --------------------------------------------------------------------------- +# Block-level line classifiers +# --------------------------------------------------------------------------- + +let __heading_level__(line) = do + if (!__HEADING_RE__.match(line)) return 0 + return __HEADING_RE__.group(line, 1).length + +let __heading_text__(line) = do + if (!__HEADING_RE__.match(line)) return "" + let text = __HEADING_RE__.group(line, 2) + if (text == null) return "" + return text.strip(" ") + +let __is_hr__(line) = __HR_RE__.match(line) + +let __fence_info__(line) = do + if (!__FENCE_RE__.match(line)) return { is_fence: false, marker: "", lang: "" } + let marker = __FENCE_RE__.group(line, 1) + let lang = __FENCE_RE__.group(line, 2) + return { is_fence: true, marker: marker, lang: lang.strip(" ") } + +let __blockquote_content__(line) = do + if (!__BLOCKQUOTE_RE__.match(line)) return null + return __BLOCKQUOTE_RE__.group(line, 1) + +let __ul_item__(line) = do + if (!__UL_RE__.match(line)) return null + let indent = __UL_RE__.group(line, 1) + let content = __UL_RE__.group(line, 2) + return { indent: indent.length, content: content } + +let __ol_item__(line) = do + if (!__OL_RE__.match(line)) return null + let indent = __OL_RE__.group(line, 1) + let content = __OL_RE__.group(line, 3) + return { indent: indent.length, content: content } + +let __setext_level__(line) = do + if (__SETEXT_EQ_RE__.match(line)) return 1 + if (__SETEXT_DASH_RE__.match(line)) return 2 + return 0 + +let __is_table_delim__(line) = __TABLE_DELIM_RE__.match(line.strip(" ")) + +# Splits a pipe-delimited table row into trimmed cell strings, dropping a +# leading/trailing empty cell caused by optional outer pipes. +let __split_table_row__(line) = do + let trimmed = line.strip(" ") + let cells = trimmed.split("|") + let out = [] + let n = cells.length + let i = 0 + while (i < n) do + let is_first = (i == 0) + let is_last = (i == n - 1) + let cell = cells[i] + let is_edge_empty = ((is_first || is_last) && cell.strip(" ") == "" && n > 1) + if (!is_edge_empty) out.append(cell.strip(" ")) + i = i + 1 + return out + +# Parses a delimiter row into a list of alignments: "left", "center", +# "right", or null (no explicit alignment) per column. +let __parse_table_alignments__(delim_line) = do + let cells = __split_table_row__(delim_line) + let out = [] + for (cell in cells) do + let c = cell.strip(" ") + let starts_colon = (c.length > 0 && c[0] == ":") + let ends_colon = (c.length > 0 && c[c.length - 1] == ":") + if (starts_colon && ends_colon) out.append("center") + else if (ends_colon) out.append("right") + else if (starts_colon) out.append("left") + else out.append(null) + return out + +# --------------------------------------------------------------------------- +# Main conversion +# --------------------------------------------------------------------------- + +let markdown_to_html(source) = do + let normalized = source.replace("\r\n", "\n").replace("\r", "\n") + let lines = normalized.split("\n") + let html_parts = [] + + let in_code_block = false + let code_fence_marker = "" + let code_lang = "" + let code_lines = [] + + let paragraph_lines = [] + let flush_paragraph = () = do + if (paragraph_lines.length > 0) do + let joined = paragraph_lines.join(" ") + let rendered = render_inline(joined) + let with_breaks = rendered.replace("\u0001BR\u0001", "
") + html_parts.append("

" + with_breaks + "

") + paragraph_lines = [] + + let list_stack = [] # each entry: {type: "ul"|"ol", indent: } + let close_lists_deeper_than = (indent) = do + while (list_stack.length > 0 && list_stack[list_stack.length - 1].indent > indent) do + let top = list_stack[list_stack.length - 1] + if (top.type == "ul") html_parts.append("") + else html_parts.append("") + let trimmed = [] + let i = 0 + while (i < list_stack.length - 1) do + trimmed.append(list_stack[i]) + i = i + 1 + list_stack = trimmed + let close_all_lists = () = do + while (list_stack.length > 0) do + let top = list_stack[list_stack.length - 1] + if (top.type == "ul") html_parts.append("") + else html_parts.append("") + let trimmed = [] + let i = 0 + while (i < list_stack.length - 1) do + trimmed.append(list_stack[i]) + i = i + 1 + list_stack = trimmed + + let blockquote_lines = [] + let flush_blockquote = () = do + if (blockquote_lines.length > 0) do + let inner_html = markdown_to_html(blockquote_lines.join("\n")) + html_parts.append("
" + inner_html + "
") + blockquote_lines = [] + + let line_idx = 0 + let total_lines = lines.length + while (line_idx < total_lines) do + let line = lines[line_idx] + + if (in_code_block) do + let stripped = line.replace("\t", "").strip(" ") + if (stripped == code_fence_marker) do + let lang_attr = do + if (code_lang != "") return " class=\"language-" + code_lang + "\"" + return "" + html_parts.append("
" + escape_html(code_lines.join("\n")) + "
") + code_lines = [] + in_code_block = false + else code_lines.append(line) + + else do + let fence = __fence_info__(line) + + let next_line = do + if (line_idx + 1 < total_lines) return lines[line_idx + 1] + return null + let setext = do + if (next_line == null) return 0 + if (paragraph_lines.length > 0) return 0 + if (line.strip(" ") == "") return 0 + if (__heading_level__(line) > 0) return 0 + if (fence.is_fence) return 0 + if (__ul_item__(line) != null || __ol_item__(line) != null) return 0 + if (__blockquote_content__(line) != null) return 0 + return __setext_level__(next_line) + + if (setext > 0) do + flush_blockquote() + close_all_lists() + html_parts.append("" + render_inline(line.strip(" ")) + "") + line_idx = line_idx + 1 # also consume the underline line + + else if (fence.is_fence) do + flush_paragraph() + close_all_lists() + flush_blockquote() + in_code_block = true + code_fence_marker = fence.marker + code_lang = fence.lang + code_lines = [] + + else if (line.strip(" ") == "") do + flush_paragraph() + close_all_lists() + flush_blockquote() + + else if (__heading_level__(line) > 0) do + flush_paragraph() + close_all_lists() + flush_blockquote() + let level = __heading_level__(line) + let text = __heading_text__(line) + html_parts.append("" + render_inline(text) + "") + + else if (__is_hr__(line)) do + flush_paragraph() + close_all_lists() + flush_blockquote() + html_parts.append("
") + + else if (__blockquote_content__(line) != null) do + flush_paragraph() + close_all_lists() + blockquote_lines.append(__blockquote_content__(line)) + + else if (next_line != null && paragraph_lines.length == 0 && line.index_of("|") >= 0 && __is_table_delim__(next_line) && line.strip(" ") != "") do + flush_paragraph() + close_all_lists() + flush_blockquote() + + let header_cells = __split_table_row__(line) + let alignments = __parse_table_alignments__(next_line) + + let align_attr = (idx) = do + if (idx >= alignments.length || alignments[idx] == null) return "" + return " style=\"text-align:" + alignments[idx] + "\"" + + let table_html = "\n\n" + let ci = 0 + for (cell in header_cells) do + table_html = table_html + "" + render_inline(cell) + "" + ci = ci + 1 + table_html = table_html + "\n\n\n" + + line_idx = line_idx + 2 # consume header row + delimiter row + + let still_in_table = true + while (still_in_table && line_idx < total_lines) do + let row_line = lines[line_idx] + if (row_line.strip(" ") == "" || row_line.index_of("|") < 0) do + still_in_table = false + else do + let row_cells = __split_table_row__(row_line) + table_html = table_html + "" + let rci = 0 + for (cell in row_cells) do + table_html = table_html + "" + render_inline(cell) + "" + rci = rci + 1 + table_html = table_html + "\n" + line_idx = line_idx + 1 + + table_html = table_html + "\n
" + html_parts.append(table_html) + line_idx = line_idx - 1 # compensate for the trailing line_idx += 1 below + + else if (__ul_item__(line) != null) do + flush_paragraph() + flush_blockquote() + let item = __ul_item__(line) + let indent = item.indent + close_lists_deeper_than(indent) + let top_matches = (list_stack.length > 0 && list_stack[list_stack.length - 1].indent == indent && list_stack[list_stack.length - 1].type == "ul") + if (!top_matches) do + if (list_stack.length > 0 && list_stack[list_stack.length - 1].indent == indent) close_lists_deeper_than(indent - 1) + html_parts.append("
    ") + list_stack.append({ type: "ul", indent: indent }) + html_parts.append("
  • " + render_inline(item.content) + "
  • ") + + else if (__ol_item__(line) != null) do + flush_paragraph() + flush_blockquote() + let item = __ol_item__(line) + let indent = item.indent + close_lists_deeper_than(indent) + let top_matches = (list_stack.length > 0 && list_stack[list_stack.length - 1].indent == indent && list_stack[list_stack.length - 1].type == "ol") + if (!top_matches) do + if (list_stack.length > 0 && list_stack[list_stack.length - 1].indent == indent) close_lists_deeper_than(indent - 1) + html_parts.append("
      ") + list_stack.append({ type: "ol", indent: indent }) + html_parts.append("
    1. " + render_inline(item.content) + "
    2. ") + + else do + flush_blockquote() + close_all_lists() + let trailing_spaces = 0 + let k = line.length - 1 + while (k >= 0 && line[k] == " ") do + trailing_spaces = trailing_spaces + 1 + k = k - 1 + if (trailing_spaces >= 2) paragraph_lines.append(line.strip(" ") + "\u0001BR\u0001") + else paragraph_lines.append(line.strip(" ")) + + line_idx = line_idx + 1 + + flush_paragraph() + close_all_lists() + flush_blockquote() + if (in_code_block && code_lines.length > 0) do + html_parts.append("
      " + escape_html(code_lines.join("\n")) + "
      ") + + return html_parts.join("\n")