From c473d2b1a0222c321186fffd92daf971a4c43dbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lera=20Elvo=C3=A9?= Date: Tue, 20 May 2025 06:46:36 +0300 Subject: [PATCH] more correct babycode parsing --- lib/babycode.lua | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/lib/babycode.lua b/lib/babycode.lua index afbb9a4..1947151 100644 --- a/lib/babycode.lua +++ b/lib/babycode.lua @@ -1,15 +1,5 @@ local babycode = {} -local _escape_html = function(text) - return text:gsub("[&<>\"']", { - ["&"] = "&", - ["<"] = "<", - [">"] = ">", - ['"'] = """, - ["'"] = "'" - }) -end - ---renders babycode to html ---@param s string input babycode ---@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 text = s:gsub("%[code%](.-)%[/code%]", function(code) 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" end) @@ -48,14 +39,14 @@ function babycode.to_html(s, escape_html) return url end) + -- normalize newlines, replace them with
+ text = text:gsub("\r?\n\r?\n+", "
"):gsub("\r?\n", "
") + -- replace code block placeholders back with their original contents text = text:gsub("\1CODE:(%d+)\1", function(n) return "
"..code_blocks[tonumber(n)].."
" end) - -- finally, normalize newlines replace them with
- text = text:gsub("\r?\n\r?\n+", "
"):gsub("\r?\n", "
") - return text end