Search code examples
luaneovim

Using vim.bo.filetype in an if statement to set filetype specific keybinds in neovim with init.lua


I want to have a simple keymap that is only active when editing a C file using neovim. This is the code in my init.lua file:

if vim.bo.filetype == 'c' then
    vim.api.nvim_set_keymap('i', '(', '(  )<left><left>', {noremap = true})
end

I was aiming for a simple if= statement to see if the file im in has the 'c' file extension, and if it does, 'enable' the keymap. However, this does not seem to work

I am on Arch linux, using gcc as the c compiler (if that matters), and using neovim v0.9.1 [i have also tested the keymap by itself outside of the if statement and it works]

I am aware of this solution;

local function setup_c_mappings()
  vim.api.nvim_set_keymap('i', '(', '(  )<left><left>', {noremap = true})
end

-- Trigger setup_c_mappings when editing a C file
vim.cmd([[
  augroup CFileMappings
    autocmd!
    autocmd FileType c,cpp lua setup_c_mappings()
  augroup END
]])

However i was hoping for a more 'minimalistic'/simpler way of achieving the same result, hence the very basic 'if' statement

All of my research has people saying to use the above solution, but i am still hoping there might still be a way to use if vim.bo.filetype == 'c' solution.


Solution

  • Generally, you want to put your filetype specific settings in ftplugin/c.lua and just put the single line vim.api.nvim_set_keymap('i', '(', '( )<left><left>', {noremap = true}). See :h load-plugins.

    You may also want to look into :h vim.keymap.set

    init.lua only runs when you start Neovim, but not when you open a buffer. You want to set the keymap every time you open a buffer with c file, hence the need for autocommands/ftplugin.

    If you insist on using the if vim.bo.filetype == 'c' solution. You can create a autocommand that runs a function on every filetype with BufEnter, then do your logic in the function.

    Note that you can create autocommand with lua api (see :h api-autocmd)