more correct babycode parsing
This commit is contained in:
parent
00c56f1417
commit
c473d2b1a0
@ -1,15 +1,5 @@
|
|||||||
local babycode = {}
|
local babycode = {}
|
||||||
|
|
||||||
local _escape_html = function(text)
|
|
||||||
return text:gsub("[&<>\"']", {
|
|
||||||
["&"] = "&",
|
|
||||||
["<"] = "<",
|
|
||||||
[">"] = ">",
|
|
||||||
['"'] = """,
|
|
||||||
["'"] = "'"
|
|
||||||
})
|
|
||||||
end
|
|
||||||
|
|
||||||
---renders babycode to html
|
---renders babycode to html
|
||||||
---@param s string input babycode
|
---@param s string input babycode
|
||||||
---@param escape_html fun(s: string): string function that escapes html
|
---@param escape_html fun(s: string): string function that escapes html
|
||||||
@ -21,7 +11,8 @@ function babycode.to_html(s, escape_html)
|
|||||||
local code_count = 0
|
local code_count = 0
|
||||||
local text = s:gsub("%[code%](.-)%[/code%]", function(code)
|
local text = s:gsub("%[code%](.-)%[/code%]", function(code)
|
||||||
code_count = code_count + 1
|
code_count = code_count + 1
|
||||||
code_blocks[code_count] = code
|
-- strip leading and trailing newlines, preserve others
|
||||||
|
code_blocks[code_count] = code:gsub("^%s*(.-)%s*$", "%1")
|
||||||
return "\1CODE:"..code_count.."\1"
|
return "\1CODE:"..code_count.."\1"
|
||||||
end)
|
end)
|
||||||
|
|
||||||
@ -48,14 +39,14 @@ function babycode.to_html(s, escape_html)
|
|||||||
return url
|
return url
|
||||||
end)
|
end)
|
||||||
|
|
||||||
|
-- normalize newlines, replace them with <br>
|
||||||
|
text = text:gsub("\r?\n\r?\n+", "<br>"):gsub("\r?\n", "<br>")
|
||||||
|
|
||||||
-- replace code block placeholders back with their original contents
|
-- replace code block placeholders back with their original contents
|
||||||
text = text:gsub("\1CODE:(%d+)\1", function(n)
|
text = text:gsub("\1CODE:(%d+)\1", function(n)
|
||||||
return "<pre><code>"..code_blocks[tonumber(n)].."</code></pre>"
|
return "<pre><code>"..code_blocks[tonumber(n)].."</code></pre>"
|
||||||
end)
|
end)
|
||||||
|
|
||||||
-- finally, normalize newlines replace them with <br>
|
|
||||||
text = text:gsub("\r?\n\r?\n+", "<br>"):gsub("\r?\n", "<br>")
|
|
||||||
|
|
||||||
return text
|
return text
|
||||||
end
|
end
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user