简体   繁体   中英

Vim filetype if statement not working

In my ~/.vimrc, I have an if statement that is supposed to determine if the open file is a python file or not:

if (&ft=='python')
    map <F9> <esc>:w<enter>:!python3 '%'<enter>
endif

The goal is to bind the python execution command to F9 if the file is a python file, but when I press F9 in a .py file nothing happens. I took out the if statement, and it worked. What is going wrong?

Try something like that instead:

au FileType python map <buffer> <F9> <esc>:w<bar>!python3 '%'<cr>

Your .vimrc config file runs only once on startup. So if you put an if test at this time, it won't work, because no python file is then currently edited.

But you can use .vimrc to setup an automatic behaviour : something that vim will do each time it will encounter a special condition. The condition can be in your case : "A new file is being editing, and its file type is 'python'". See :h :au

In cases like yours, it's useful to add the <buffer> parameter in the :map command : it limits the scope of your mapping to the current buffer only : so when you will press F9 on a non-python buffer, the mapping will not be trigerred.

EDIT:
In my first answer, I also deleted the <esc> in your command, but maybe I'm wrong about this, because it can cause problems in visual mode, so I put it again. You have to test it in visual mode, I didn't do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM