2

I would like to change the global mapleader for a specific filetype in neovim, but I am unsucessful...

This is what I have setup:

vim.g.mapleader = " "
vim.keymap.set("n", "<leader>pv", vim.cmd.Ex)

vim.keymap.set("n", "n", "nzz")
vim.keymap.set("n", "N", "Nzz")
vim.keymap.set("v","<Tab>", ">gv")
vim.keymap.set("v","<S-Tab>", "<gv")
vim.keymap.set("n", "za", "zA")
vim.keymap.set("v", "<leader>y", '"+y')
vim.keymap.set("v", "<leader>p", '"+p')
vim.keymap.set("n", "<leader>s", [[:%s/\<<C-r><C-w>\>/<C-r><C-w>/gI<Left><Left><Left>]])
vim.keymap.set("x", "<leader>p", [["_dP]])
vim.api.nvim_create_autocmd('TextYankPost', {
    group = yank_group,
    pattern = '*',
    callback = function()
        vim.highlight.on_yank({
            higroup = 'IncSearch',
            timeout = 100,
        })
    end,
})

vim.api.nvim_create_autocmd({"FileType"}, {
    pattern = "r",
    callback = function()
    vim.g.mapleader = "\\"
    vim.keymap.set("n", "<Space>", "<Plug>RDSendLine")
    vim.keymap.set("v", "<Space>", "<Plug>RDSendSelection")
    end,}
)

If I replace the global mapleader with a buffer one with vim.b.mapleader = " " mapleader is bound to "\" even for files that are not R scripts.

So I am a bit lost on wether it is possible to have a mapleader for a specific filetype

Thanks!

1 Answer 1

2

It happens because vim.g.mapleader is a global variable affecting all buffers once you set it.

You should use intead vim.g.maplocalleader and use <LocalLeader> for all the commands that you expect to run with your given filetype.

See docs with :help localleader

Sign up to request clarification or add additional context in comments.

3 Comments

I am not sure this will help. The problem is that the mapleader clashes with the keymap for the filetype. I am not seeing how a localleader will solve this issue.
The reason <localleader> exists is for your especific use case. You want to have different "leaders" depending on your filetype. That's your use case, right? Althought you set the mapleader inside nvim_create_autocmd, it has no effect in functionality, even if you :echo mapleader it prints `\` which might lead to confusion because it is not actually using it as <leader>.
Thanks for the extra explanation. I guess my problem lies in the fact that I want ALL the mappings using <leader> to change with the filetype. Now, wheter I use <leader> or <localleader> inside the autocmd, checking :nmap I see that mappings will use the default key for the filetype for mappings that are configured in the after/plugin directory, and not the key defined in the filetype So I would like to define the <leader> pretty early in the init.lua and carry that into the plugin configs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.