1

Is it possible to use different documentclass than the one specified in document source code during make4ht / htlatex compilation without changing the source code?

Lets say I have a document source:

\documentclass[varwidth=160mm]{standalone}
\usepackage{lipsum}

\begin{document}
\lipsum[1-2]
\end{document}

and I don't want to change the document source code because it would break my setup elsewhere. Can I configure compiler (htlatex or TeX4ht) to use specific documentclass, for example article, during compilation?

1 Answer 1

3

You can use make4ht build file for this task. It is possible to load the TeX file, modify it using Lua regular expressions, save it to an temporary file and compile the temporary file.

Save the following file as mybuild.mk4:

local tempfile 
Make:add("patchdocumentclass", function(arg)
  -- open the TeX file and load it as string
  local filename = arg.tex_file
  local file = io.open(filename, "r")
  local content = file:read("*all")
  file:close()
  -- replace the standalone class with article
  local newcontent = content:gsub("\\documentclass%[?[^%]]*%]?{standalone}", "\\documentclass{article}")
  -- make temporary file
  local newname =  "temp-" .. filename
  local file = io.open(newname, "w")
  -- save the modified content to the temp file
  file:write(newcontent)
  file:close()
  -- call latex with modified TeX file
  Make:htlatex {tex_file = newname}
  -- we can't remove the temp file right now, because the compilation hasn't started yet
  -- instead, we must save the temp name and remove it later
  tempfile = newname
end)

if mode == "draft" then
  Make:patchdocumentclass {}
else
  Make:patchdocumentclass {}
  Make:patchdocumentclass {}
  Make:patchdocumentclass {}
end

-- remove the temp file
Make:match("tmp$", function(arg)
  print("removing temp file: ".. tempfile)
  os.remove(tempfile)
end)

You can request the build file using -e option:

make4ht -um draft -e mybuild.mk4 filename.tex

A new command patchdocumentclass is defined in this build file. It is Lua function which loads the TeX file and replaces the standalone document class with article using this regex:

local newcontent = content:gsub("\\documentclass%[?[^%]]*%]?{standalone}", "\\documentclass{article}")

The modified TeX code is then saved to temporary file and the compilation is started using

Make:htlatex {tex_file = newname}

I use the following construct:

if mode == "draft" then
  Make:patchdocumentclass {}
else
  Make:patchdocumentclass {}
  Make:patchdocumentclass {}
  Make:patchdocumentclass {}
end

to decide how many times the document should be compiled. If draft mode is used (as in make4ht -m draft), it is compiled only once, otherwise it is compiled three times. So the draft mode is big time saver.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .