问题
I've got a ½ key on my keyboard and sometimes I want to use it when I'm editing LaTeX in Vim to expand to the right expression i.e. \frac{1}{2}
.
I know I should do something like :
inoremap ½ \frac{1}{2}
Now, how do I make this work only with LaTeX files ?
回答1:
You want Fietype specific autocmds:
autocmd Filetype tex,latex inoremap ½ \frac{1}{2}
Try something like that. This depends on the Filetype
option being on (see here). You can set it with set Filetype on
You can also use an autocmd that checks for the filename when reading or creating a new file:
autocmd BufNewFile,BufRead *.latex inoremap ½ \frac{1}{2}
Also, you should confirm that hitting the 1/2 key on your keyboard actually inputs the 1/2 symbol, otherwise obviously this isn't going to work. Regardless, you can figure out what code the 1/2 key actually inserts by (in insert mode) hitting ctrl-v and then the physical key.
回答2:
You'll get a buffer-local variant of a mapping via the <buffer>
modifier.
To define the mapping for all Tex buffers, you can use an :autocmd
on the FileType
event (:setlocal filetype?
will tell you the actual filetype):
:autocmd Filetype tex inoremap <buffer> ½ \frac{1}{2}
But that get's unwieldy as you add mappings and other settings for various filetypes. Better put the command(s) into ~/.vim/ftplugin/tex_mappings.vim
. (This requires that you have :filetype plugin on
.)
来源:https://stackoverflow.com/questions/19985652/vim-remap-only-if-source-file-is-in-latex