more correct babycode parsing
This commit is contained in:
		@@ -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 <br>
 | 
			
		||||
  text = text:gsub("\r?\n\r?\n+", "<br>"):gsub("\r?\n", "<br>")
 | 
			
		||||
 | 
			
		||||
  -- replace code block placeholders back with their original contents
 | 
			
		||||
  text = text:gsub("\1CODE:(%d+)\1", function(n)
 | 
			
		||||
    return "<pre><code>"..code_blocks[tonumber(n)].."</code></pre>"
 | 
			
		||||
  end)
 | 
			
		||||
 | 
			
		||||
  -- finally, normalize newlines replace them with <br>
 | 
			
		||||
  text = text:gsub("\r?\n\r?\n+", "<br>"):gsub("\r?\n", "<br>")
 | 
			
		||||
 | 
			
		||||
  return text
 | 
			
		||||
end
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user