more correct babycode parsing

This commit is contained in:
Lera Elvoé 2025-05-20 06:46:36 +03:00
parent 00c56f1417
commit c473d2b1a0
Signed by: yagich
SSH Key Fingerprint: SHA256:6xjGb6uA7lAVcULa7byPEN//rQ0wPoG+UzYVMfZnbvc

View File

@ -1,15 +1,5 @@
local babycode = {} local babycode = {}
local _escape_html = function(text)
return text:gsub("[&<>\"']", {
["&"] = "&amp;",
["<"] = "&lt;",
[">"] = "&gt;",
['"'] = "&quot;",
["'"] = "&#39;"
})
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