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.

2
  • 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, 2020 at 23:37
  • 3
    Should probably be a <buffer> mapping
    – D. Ben Knoble
    Apr 26, 2020 at 0:35

1 Answer 1

3

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>
3
  • 1
    What's the question mark in :set ft? for, isn't the same as :set ft?
    – Jon
    Jul 28, 2021 at 16:58
  • 1
    @Jon For boolean options (such as et, short for expandtab, or ai for autoindent) if you don't use the ? at the end you will set the option instead of query whether it's set. Yes, for something like ft it doesn't matter, but in general using the ? to query is never really incorrect and in many cases it's required, so I find it better to always include it.
    – filbranden
    Jul 28, 2021 at 17:47
  • 1
    Thanks for the explanation!
    – Jon
    Jul 28, 2021 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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