OMetaJS: Simple Markdown
var text = | |
"hi\ | |
=== \ | |
### hi hi\ | |
another\ | |
--------\ | |
\ | |
hello\ | |
\ | |
\ | |
\ | |
\ | |
```\ | |
<code>\ | |
hi\ | |
</code>\ | |
```\ | |
"; | |
// I would like to know how to do these: | |
// | |
// \# Backslash escaping | |
// | |
ometa MarkDown { | |
// formatting | |
BOF = spaces, | |
EOF = spaces end, | |
line = '\n' -> ("") | |
| (~'\n' string)+:l '\n'? -> (l.join("")), | |
lineSpaces = ' '*, | |
// headers | |
h1 = "#" lineSpaces line:h -> (tag("h1", h)) | |
| (~'\n' string)+:h '\n' '='+ lineSpaces ('\n' | end) -> (tag("h1", h.join(""))), | |
h2 = "##" lineSpaces line:h -> (tag("h2", h)) | |
| (~'\n' string)+:h '\n' '-'+ lineSpaces ('\n' | end) -> (tag("h2", h.join(""))), | |
h3 = "###" lineSpaces line:h -> (tag("h3", h)), | |
// flourishes | |
strong = "**" lineSpaces (~"**" char)*:t lineSpaces "**" -> (tag("strong", t.join(""))), | |
em = "*" lineSpaces (~"*" char)*:t lineSpaces "*" -> (tag("em", t.join(""))), | |
// text | |
para = (strong | em | (~seq("\n") char))+:t '\n'? -> (tag("p", t.join(""))), | |
break = '\n' -> (singleTag("br")), | |
// code | |
codeBlock = fromTo("```\n", "\n```"):t -> tag("pre",tag("code",esc(t))), | |
// markdown | |
markdownLine = (h3|h2|h1|codeBlock|para|break):t -> (t), | |
markdown = BOF markdownLine*:m EOF -> (m.join("")), | |
END | |
} | |
function singleTag (tag) { | |
return "<"+tag+" />" | |
} | |
function tag (tag, str) { | |
return "<"+tag+">"+str+"</"+tag+">"; | |
}; | |
function esc (s) { | |
return s.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br/>"); | |
}; | |
var result = MarkDown.matchAll( | |
text, | |
'markdown' | |
); | |
console.log(result); |
<h1>hi</h1><h3>hi hi</h3><h2>another</h2><br /><p>hello</p><br /><br /><p> </p><br /><pre><code>```<br/><code><br/> hi<br/></code><br/>```</code></pre><br /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment