Search code examples
vimautocmd

Vimrc autocmd runs command instead of mapping


I want to add a hotkey to my vim to run my python files, so I have added the following line to my vimrc:

autocmd FileType python map <F5> :w|!python3 %

But on opening the file instead of running autocmd, it runs python with my file.

For me this seems no different from what many tutorials suggest on using autocmd and map, so I'd like to know what exactly is happening here instead of the behavior I expect.


Solution

  • Your :map command ends at the command separator |; the remainder is already executed when the :autocmd runs. You need to escape it (\|), or better use the special <Bar> character:

    autocmd FileType python nnoremap <buffer> <F5> :w<Bar>!python3 %<CR>
    

    Cp. :help map_bar. Also, you should use :noremap; it makes the mapping immune to remapping and recursion. And (as @PeterRincker suggested), make the mapping buffer-local, so that it only applies to Python buffers).


    Your :autocmd FileType approach is fine for a few mappings, but it doesn't scale well. If you have :filetype plugin on in your ~/.vimrc, you can factor our your mappings into a separate script ~/.vim/ftplugin/python_mappings.vim.