Search code examples
luaneovimkeymapping

Neovim + Lua: how to use different mappings depending on file type?


I have the following lua function for mapping keys in neovim

local M = {}

function M.map(mode, lhs, rhs, opts)
    -- default options
    local options = { noremap = true }

    if opts then
        options = vim.tbl_extend("force", options, opts)
    end

    vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end

return M

And use it for key mapping like so:

map("", "<Leader>f", ":CocCommand prettier.forceFormatDocument<CR>") 
map("", "<Leader>f", ":RustFmt<CR>")

I want to use :RustFmt only for .rs files and :CocCommand prettier.forceFormatDocument for all the other files.

Is this possible to do with vim.api.nvim_set_keymap and if so how could I do it?


Solution

  • Thanks to @DoktorOSwaldo and @UnrealApex I was able to resolve the issue using ftplugin.

    Steps:

    • Create ftplugin directory inside ~/.config/nvim.
    • Inside ftplugin directory create a file rust.lua.
    • Inside rust.lua import map util and define key mapping.
    local map = require("utils").map
    
    -- Format document
    map("", "<Leader>f", ":RustFmt<CR>")
    

    For languages other than Rust use the following command to get the full list of possible file names (.vim can be switched to .lua):

    :exe 'Lexplore ' . expand('$VIMRUNTIME') . '/syntax'