Converters

A converter is a Lua script that turns one source file into one output file, usually by calling an external program (pandoc, mmdc, ImageMagick, …). Templates ship their converters in converters/; a profile names one in its engine field.

API

The script returns a convert function, which tern calls once per changed source file:

--- @param input   string  Source file path
--- @param output  string  Output file path; its directory already exists
--- @param options table   The profile's options, one string per entry
--- @return        boolean true when the output was written
local function convert(input, output, options)
    -- ...
    return true
end

return convert

Return value and errors

A failed command must raise an error, not return false: false reads as “nothing to do” and the build summary still says success. Lua’s os.execute returns a non-true value on failure, so returning its result directly hides failures.

Shell quoting

os.execute runs its command through a shell, so every path embedded in it must be quoted. POSIX single-quote escaping handles spaces, $, backticks and quotes:

local function shell_quote(s)
    return "'" .. s:gsub("'", "'\\''") .. "'"
end

Examples

pandoc — Markdown to HTML, with the profile’s flags in options[1]:

local function shell_quote(s)
    return "'" .. s:gsub("'", "'\\''") .. "'"
end

local function convert(input, output, options)
    local command = "pandoc " .. options[1] .. " " .. shell_quote(input)
        .. " -o " .. shell_quote(output)
    if not os.execute(command) then
        error("pandoc failed for " .. input)
    end
    return true
end

return convert

ImageMagick — every option entry becomes an argument:

local function shell_quote(s)
    return "'" .. s:gsub("'", "'\\''") .. "'"
end

local function convert(input, output, options)
    local command = "magick " .. shell_quote(input) .. " "
        .. table.concat(options, " ") .. " " .. shell_quote(output)
    if not os.execute(command) then
        error("magick failed for " .. input)
    end
    return true
end

return convert

Lookup

Tern looks for a converter in two places, in order:

  1. .tern/converters/ in the project, where templates install theirs under <template>/;
  2. converters/ in the user data directory (~/.local/share/tern/ on Linux).

A profile’s origin field (local or global) picks between the two when both hold a script with the same name.