0

I have a line in my vimrc that enables me to save and run python program in a single click while it's opened:

nnoremap <buffer> <F9> :w <bar> :exec '!python3' shellescape(@%, 1)<cr>

I can also call vim to open a folder in navigation/explorer mode that lets me edit files in that folder. Example:

vim folder

But when I open a python file in that folder in vim by hitting enter and hit F9 to save and run the file, vim does not go back to the shell (zsh) and display results, which it usually does. How can I fix this?

1
  • 2
    Welcome to Vi and Vim! Where is the nnoremap line in your vimrc? In an ftplugin/wrapped in a filetype auto-command? Because you've used <buffer>, it's only available in the buffer where it's executed... Please use the edit button to add additional details
    – D. Ben Knoble
    Commented Mar 16, 2020 at 23:22

1 Answer 1

2

I suspect, but cannot confirm because information is missing, that the line is "bare" in the OP's vimrc.

This means it would execute, no matter what, for the first buffer vim opens. Because of <buffer>, that mapping is only available in that buffer!

Instead, you should put the mapping in ~/.vim/after/ftplugin/python.vim as follows:

nnoremap <buffer> <F9> :write <bar> :exec '!python3' shellescape(@%, 1)<cr>

But note that you can also use <LocalLeader> instead of <F9> to have special "local" maps (I find it hard to remember what function keys do what)—I do this when I have similar mappings for many filetypes. For examples, <LocalLeader>t is my "run tests" mapping, but what it actually does is different depending on the filetype.

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.