Skip to content

Instantly share code, notes, and snippets.

@tarleb
Last active December 20, 2020 18:23
Show Gist options
  • Save tarleb/4f72bbda6e4df5f77d1b6067bb859dfa to your computer and use it in GitHub Desktop.
Save tarleb/4f72bbda6e4df5f77d1b6067bb859dfa to your computer and use it in GitHub Desktop.
Add file extension to images
local known_exts = pandoc.List{".png", ".jpg", "jpeg"}
if FORMAT:match 'tex' then
known_exts = pandoc.List {
".pdf", ".png", ".jpg", ".mps", ".jpeg", ".jbig2", ".jb2"
}
elseif FORMAT:match 'html' then
known_exts = pandoc.List {
".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif"
}
end
known_exts:extend(known_exts:map(string.upper))
local function add_extension(basename, ext)
return basename .. (ext:sub(1,1) == '.' and ext or '.' .. ext)
end
local function file_exists(basename)
return function (ext)
local f = io.open(add_extension(basename, ext), 'r')
return f and io.close(f)
end
end
function Image (img)
-- don't do anything if the image already has an extension
if img.src:match '(%..+)$' then return end
-- if the default extension has been given, use that; otherwise
-- try all image extensions and use the first for which an image
-- exists.
img.src = add_extension(
img.src,
PANDOC_READER_OPTIONS.default_image_extension ~= ''
and PANDOC_READER_OPTIONS.default_image_extension
or (known_exts:find_if(file_exists(img.src)) or '')
)
return img
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment