add inline code block support

This commit is contained in:
2025-05-24 16:15:25 +03:00
parent 11dbec0793
commit ed34f394ce
4 changed files with 47 additions and 5 deletions

View File

@ -8,12 +8,19 @@ function babycode.to_html(s, escape_html)
-- extract code blocks first and store them as placeholders
-- don't want to process bbcode embedded into a code block
local code_blocks = {}
local inline_codes = {}
s = escape_html(s)
local text = s:gsub("%[code%](.-)%[/code%]", function(code)
-- strip leading and trailing newlines, preserve others
local m, _ = code:gsub("^%s*(.-)%s*$", "%1")
table.insert(code_blocks, m)
return "\1CODE:"..#code_blocks.."\1"
local is_inline = code:match("\n") == nil
if is_inline then
table.insert(inline_codes, code)
return "\1ICODE:"..#inline_codes.."\1"
else
-- strip leading and trailing newlines, preserve others
local m, _ = code:gsub("^%s*(.-)%s*$", "%1")
table.insert(code_blocks, m)
return "\1CODE:"..#code_blocks.."\1"
end
end)
-- replace `[url=https://example.com]Example[/url] tags
@ -51,6 +58,11 @@ function babycode.to_html(s, escape_html)
local button = ("<button type=button class=\"copy-code\" value=\"%s\">Copy</button>"):format(code)
return "<pre><span class=\"copy-code-container\">" .. button .. "</span><code>"..code.."</code></pre>"
end)
text = text:gsub("\1ICODE:(%d+)\1", function (n)
local code = inline_codes[tonumber(n)]
return "<code class=\"inline-code\">" .. code .. "</code>"
end)
return text
end