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

Viewed 633

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?

2 Answers

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>")

You can create a format function in your utils.lua configuration file :

function M.format()
  if vim.bo.filetype == 'rust' then
    vim.cmd('RustFmt')
  else
    vim.cmd('CocCommand prettier.forceFormatDocument')
  end

and define your key mapping like this :

map("", "<Leader>f", "<cmd>:lua require('utils').format<CR>")
Related