简体   繁体   English

Vim文件类型,如果语句不起作用

[英]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: 在我的〜/ .vimrc中,我有一个if语句,该语句应确定打开的文件是否为python文件:

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. 目的是将python执行命令绑定到F9(如果该文件是python文件),但是当我在.py文件中按F9时,什么也没有发生。 I took out the if statement, and it worked. 我取出if语句,它起作用了。 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. .vimrc配置文件在启动时仅运行一次。 So if you put an if test at this time, it won't work, because no python file is then currently edited. 因此,如果您此时进行if测试,它将无法正常工作,因为当前未编辑任何python文件。

But you can use .vimrc to setup an automatic behaviour : something that vim will do each time it will encounter a special condition. 但是您可以使用.vimrc来设置自动行为: vim每次遇到特殊情况时都会执行的操作。 The condition can be in your case : "A new file is being editing, and its file type is 'python'". 根据您的情况,条件可能是:“正在编辑一个新文件,其文件类型为'python'”。 See :h :au :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. 在像您这样的情况下,在:map命令中添加<buffer>参数很有用:它将映射范围仅限制为当前缓冲区:因此,当您在非python缓冲区上按F9时,映射不会被激怒了。

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. 在我的第一个答案中,我还删除了命令中的<esc>也许我错了,因为它可能在可视模式下引起问题,因此我再次提出。 You have to test it in visual mode, I didn't do it. 您必须以可视模式对其进行测试,但我没有这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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