autocommand for filetypes working for setting options but not for mappings

回眸只為那壹抹淺笑 提交于 2020-01-05 19:29:08

问题


I have the following lines in my vimrc:

set shiftwidth=4
autocmd FileType tex setlocal shiftwidth=2
autocmd FileType tex map xyz doSomething

If I open a, say, text file (filetype is set correctly), and do set sw, I get 4. If I open a tex file (filetype is set correctly), I get 2 for set sw. That part works!

Now for the mapping I type map xyz, and I see that the mapping is done for both filetypes. What am I doing wrong?

At first I thought something with the mapping is wrong, so I tried:

set history=100
autocmd FileType tex setlocal history=123

But history is set to 123 for all filetypes... How can shiftwidth work, but history not?


回答1:


What :setlocal is to :set, :map <buffer> is to :map (see :h :map-local):

autocmd FileType tex map <buffer> xyz doSomething

Also, you should use :noremap; it makes the mapping immune to remapping and recursion.

And I would recommend putting the settings and mappings into ~/.vim/after/ftplugin/tex.vim instead of defining lots of :autocmd FileType; this requires that you have :filetype plugin on.

Option scopes

The :help offers hints which options are global only (like 'history'), and which support (either buffer or window)-local values; compare the second line:

'history' 'hi'      number  (Vim default: 20, Vi default: 0)
                    global
'shiftwidth' 'sw'   number  (default 8)
                    local to buffer


来源:https://stackoverflow.com/questions/21407083/autocommand-for-filetypes-working-for-setting-options-but-not-for-mappings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!