有没有更好的方法来映射基于文件类型的命令调用 [英] Is there a better way to map command call based on filetype

查看:31
本文介绍了有没有更好的方法来映射基于文件类型的命令调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Notepad 和 Notepad++ 切换后,我是 vim 的新手,但过去四个月我一直在专门使用它.在我的 .vimrc 中,我有一个命令可以根据文件扩展名自动更改命令调用.例如,如果我正在编辑一个 R 文件,我可以按 并且 vim 执行 !Rscript %:p,但是如果我切换到一个python文件并按下,vim执行!python %:p.我通过将以下内容放入我的 .vimrc 中来完成此操作:

I'm new to vim after switching from Notepad and Notepad++, but I've been using it exclusively for the past four months. In my .vimrc I have a command that automatically changes the command call based on file extensions. For example, if I'm editing an R file, I can press <F5> and vim executes !Rscript %:p<cr>, but if I switch to a python file and press <F5>, vim executes !python %:p<cr>. I accomplish this by putting the following in my .vimrc:

    autocmd BufRead *.R noremap <F5> :!Rscript %:p<cr>
    autocmd BufRead *.pl noremap <F5> :!perl %:p<cr>
    autocmd BufRead *.py noremap <F5> :!python %:p<cr>

我想知道这是否是基于命令调用执行它的正确"vim 方式.我知道我使用的一些 python 文件没有 *.py 扩展名,因此在这种情况下设置是无用的.

I'm wondering if this is the "proper" vim way to execute it based on the command call. I know some of python files I work with do not have a *.py extension, and so the setting is useless in this case.

推荐答案

你需要做两件事:

  • 使用 noremap 选项创建特定缓冲区的本地映射.
  • 仅加载特定文件类型的映射.
  • Create a mapping local to a specific buffer by using the <buffer> option for noremap.
  • Load the mappings for just a specific filetype.

这可以通过 .vimrc 中的 autocmdFileType 事件来完成,如下所示:

This can be done via an autocmd and FileType event in your .vimrc like so:

autocmd FileType perl noremap <buffer> <F5> :!perl %:p<cr>

另一种方式是创建一个文件类型插件.(查看:h ftplugin 了解更多详情)

The other way option is by creating a filetype plugin. (see :h ftplugin for more details)

一个简单的例子是创建一个名为 ~/.vim/ftplugin/perl.vim 的文件并将你的映射放入其中:

A simple example is do create a file named, ~/.vim/ftplugin/perl.vim and place your mappings inside like so:

nnoremap <buffer> <F5> :!perl %:p<cr>

我个人更倾向于 ftplugin 方法,但在 .vimrc 文件中包含所有内容可能会很好.

I personally lean more towards the ftplugin approach but having a everything in your .vimrc file can be nice.

有关更多帮助,请参阅:

For more help see:

:h :au
:h FileType
:h map-local
:h ftplugin

这篇关于有没有更好的方法来映射基于文件类型的命令调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆