1

I'm using the regular Vim that comes with Ubuntu.

I have the following line of code in my .vimrc:

autocmd filetype py nnoremap <F10> :w <bar> !python3 %<CR>

It's not working, although I have a similar setup with <F10> for cpp files.

  • The name of the FileType is actually python and not py. Can you try that and see if it's all that's needed to solve your issue? – filbranden Apr 25 at 23:37
  • 3
    Should probably be a <buffer> mapping – D. Ben Knoble Apr 26 at 0:35
2

The correct FileType is "python" and not "py". You can check for that by opening a Python file in Vim and checking the detected FileType with the :set ft? command, which I'd expect will return the following:

:set ft?
  filetype=python

If you create a mapping for a specific filetype (such as "python" in your case), make sure you create a local mapping using <buffer>. Otherwise the mapping will be global and will work on every buffer and not only those with Python source files.

If you use an autocmd in your vimrc, make sure you wrap it in an augroup to prevent getting duplicated commands if you reload your vimrc.

Putting it all together:

augroup vimrc_python
  au!
  au FileType python nnoremap <buffer> <F10> :w <bar> !python3 %<CR>
augroup END

Alternatively, you can add filetype mappings for Python in a file ~/.vim/ftplugin/python.vim (or python_*.vim, or python/*.vim, inside that ftplugin directory), which gets automatically loaded by Vim whenever a file of type Python is loaded. (That way you don't need to use explicit autocmds, Vim will take care of those details on your behalf.)

If you use that approach, all you need inside that file to create this mapping is:

nnoremap <buffer> <F10> :w <bar> !python3 %<CR>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.