VIM文件类型(filetype)是VIM用来识别和区分不同文件格式的机制,它决定了VIM如何对文件进行语法高亮、缩进规则和其他特定于文件类型的处理。
在文件的开头或结尾添加特殊注释:
# vim: set filetype=python:
/* vim: set filetype=javascript: */
-- vim: set filetype=lua:
在vimrc或init.vim中添加:
autocmd BufNewFile,BufRead *.myext set filetype=python
创建~/.vim/ftdetect/myfiletype.vim
:
autocmd BufNewFile,BufRead *.foo set filetype=bar
:set filetype=html
或者在Vim脚本中:
set ft=javascript
更复杂的检测可以使用自定义函数:
function! s:DetectFiletype()
if getline(1) =~ '^#!.*python'
set filetype=python
endif
endfunction
autocmd BufNewFile,BufRead * call s:DetectFiletype()
set nomodeline
禁用" 为特定扩展名设置文件类型
autocmd BufNewFile,BufRead *.tpl set filetype=html
" 为无扩展名但包含特定内容的文件设置类型
function! SetFileType()
if search('<?php', 'nw')
set filetype=php
endif
endfunction
autocmd BufRead * call SetFileType()
" 临时覆盖文件类型检测
command! -nargs=1 SetFileType set filetype=<args>
通过以上方法,你可以灵活地以编程方式控制VIM的文件类型设置。
没有搜到相关的文章