Brandon
Brandon

Reputation: 1855

How do I use the same keymap for different commands depending on the file type?

I have the following config, but when I enter an eruby file and then go back to a different file, F3 still executes :Autoformat.

noremap <F3> :Neoformat<CR>
autocmd FileType eruby bufdo map <F3> :Autoformat<CR>

I want it to only apply that command while in eruby buffers.

Upvotes: 0

Views: 109

Answers (1)

D. Ben Knoble
D. Ben Knoble

Reputation: 4673

First, don’t use bufdo here; it executes a command for all buffers. Second, prefer <buffer> mappings.

With autocommands:

augroup vimrc_eruby
  au!
  au FileType eruby noremap <buffer> <F3> :Autoformat<CR>
augroup END

But I highly encourage reading about ftplugins, and using ~/.vim/after/ftplugin/eruby.vim. Read about setlocal, map-<buffer>, and b:undo_ftplugin in vim’s help.

I’ve written answers about using these tools on Vi & Vim StackExchange a few times: https://vi.stackexchange.com/a/22256/10604, https://vi.stackexchange.com/a/15329/10604, https://vi.stackexchange.com/a/15019/10604

Upvotes: 5

Related Questions