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, lhs, rhs, opts)
    -- default options
    local options = { noremap = true }

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

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

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?


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


    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'