summaryrefslogtreecommitdiff
path: root/support/make4ht/extensions/make4ht-ext-tidy.lua
blob: b381a05a8fb7af3f5ba9b87700af5e5e1997b994 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
local M = {}

local log = logging.new "tidy"
function M.test(format)
  if format == "odt" then return false end
  return true
end

local empty_elements = {
  area=true,
  base=true,
  br=true,
  col=true,
  embed=true,
  hr=true,
  img=true,
  input=true,
  keygen=true,
  link=true,
  meta=true,
  param=true,
  source=true,
  track=true,
  wbr=true,
}

-- LuaXML cannot read HTML with unclosed tags (like <meta name="hello" content="world">)
-- Tidy removes end slashes in the HTML output, so
-- this function will add them back
local function close_tags(s)
  return s:gsub("<(%w+)([^>]-)>", function(tag, rest)
    local endslash = ""
    if empty_elements[tag] then endslash = " /" end
    return string.format("<%s%s%s>", tag, rest, endslash)
  end)
end
    


function M.modify_build(make)
  make:match("html$", function(filename, par)
    local settings = get_filter_settings "tidy" or {}
    par.options = par.options or settings.options or "-utf8 -w 512 -ashtml -q"
    local command = "tidy ${options}  ${filename}" % par
    log:info("running tidy: ".. command)
    -- os.execute(command)
    local run = io.popen(command, "r")
    local result = run:read("*all")
    run:close()
    result = close_tags(result)
    local f = io.open(filename, "w")
    f:write(result)
    f:close()
  end)
  return make
end

return M