Change `commentstring` for the `foldmarker` only

I am currently using the following snippet to add space before the foldmarker:

vim.api.nvim_create_autocmd('FileType', {
    pattern = '*',
    desc = 'Add space before foldmarker',
    callback = function()
        if vim.bo.commentstring ~= nil and vim.bo.commentstring ~= '' then
            vim.bo.commentstring = ' ' .. vim.bo.commentstring
        end
    end
})

Unfortunately, sometimes (!) it affects comments as well.

Has anyone tried amending commentstring selectively, for the foldmarker only?

You can set a custom foldtext function and handle things inside that. For example, I have:

function neat_foldtext() -- Simplified, cleaner foldtext.
    local patterns = {
        "%s?{{{%d?",     -- Remove default fold markers, see :h foldmarker.
        '"""',           -- Remove triple-quotes (Python docstring syntax).
    }
    -- Make 'commentstring' into a more robust pattern and remove comment characters.
    local commentstring = string.gsub(opt.commentstring:get(), "%s", "%s?%%s")
    for _, v in pairs(fn.split(commentstring, "%s")) do
        table.insert(patterns, v)
    end
    local headerline = fn.getline(vim.v.foldstart)
    for _, pattern in pairs(patterns) do
        headerline = headerline:gsub(pattern, "")
    end
    -- Add a space at the end before optional fill chars.
    local foldtext = { string.rep("+ ", fn.foldlevel(vim.v.foldstart)), headerline, " " }
    return table.concat(foldtext)
end

vim.opt.foldtext = "v:lua.neat_foldtext()"
1 Like