Tue, 09 Mar 2021 12:16:56 +0000
Initial commit
0 | 1 | |
2 | local s_gsub = string.gsub; | |
3 | ||
4 | local html_escape_table = { ["'"] = "'", ["\""] = """, ["<"] = "<", [">"] = ">", ["&"] = "&" }; | |
5 | local function html_escape(str) return (s_gsub(str, "['&<>\"]", html_escape_table)); end | |
6 | ||
7 | local html_unescape_table = {}; for k,v in pairs(html_escape_table) do html_unescape_table[v] = k; end | |
8 | local function html_unescape(str) return (s_gsub(str, "&%a+;", html_unescape_table)); end | |
9 | ||
10 | local tags = { | |
11 | em = "/"; strong = "*"; small = ""; s = ""; cite = ""; | |
12 | q = "\""; dfn = ""; code = "`"; var = "`"; samp = "`"; kbd = "`"; | |
13 | sub = "~"; sup = "^"; i = "/"; b = "*"; u = "_"; mark = ""; | |
14 | }; | |
15 | ||
16 | local function formatted(text) | |
17 | return html_escape(text):gsub(html_escape("<(%a+)([^>]*)>(.-)</%1>"), function (tag, attrs, content) | |
18 | tag = tag:lower(); | |
19 | if tags[tag] then | |
20 | return ("<%s>%s</%s>"):format(tag, content, tag); | |
21 | end | |
22 | end); | |
23 | end | |
24 | ||
25 | local function html2md(text) | |
26 | return text:gsub("<(%a+)([^>]*)>(.-)</%1>", function (tag, attrs, content) | |
27 | tag = tags[tag]; | |
28 | if tag then | |
29 | return tag .. content .. tag; | |
30 | end | |
31 | end); | |
32 | end | |
33 | ||
34 | local par = { ["("] = ")", ["<"] = ">", ["["] = "]", ["{"] = "}", [";"] = "&", }; | |
35 | ||
36 | local function linkify(text) | |
37 | return text:gsub("(%S?)(https?://%S+)", function (p, url) | |
38 | local extra = ""; | |
39 | -- Attempt to get rid of trailing parenthesis from found URLs | |
40 | if par[p] and url:find(par[p], 1, true) then | |
41 | extra = url:sub(url:find(par[p], 1, true), -1); | |
42 | url = url:sub(1, url:find(par[p], 1, true) - 1); | |
43 | end | |
44 | return ("%s<a rel=\"nofollow\" href=\"%s\">%s</a>%s"):format(p, url, url, extra); | |
45 | end); | |
46 | end | |
47 | ||
48 | return { | |
49 | escape = html_escape; | |
50 | html2md = html2md; | |
51 | formatted = formatted; | |
52 | linkify = linkify; | |
53 | unescape = html_unescape; | |
54 | }; |