-- hyperlinks.lua

-- End URLs in hyperlinks with {blank}, {parent}, {top}, or {self} to have the appropriate target added to the link.

local suffixes = { 'blank', 'parent', 'top', 'self', 'frame-content' }

function targetAdjust(elem, suffix, targetDest)
    local url = elem.target:sub(1, -string.len(suffix) - 1)
    local targetNameParts = {}
    for i = 1, #elem.content do
        table.insert(targetNameParts, elem.content[i].text)
    end
    local targetName = table.concat(targetNameParts, ' ')
    return pandoc.RawInline('html', string.format("%s", url, targetDest, targetName))
end

return {
    {
        Link = function(elem)
            for i = 1, #suffixes do
                local suffix = suffixes[i]
                local suffixFull = '%7B' .. suffix .. '%7D'
                if elem.target:sub(-string.len(suffixFull)) == suffixFull then
                    return targetAdjust(elem, suffixFull, '_' .. suffix)
                end
            end
            return elem
        end,
    }
}