开发者

Vim: how to set filetype for none extension file by `#!`?

开发者 https://www.devze.com 2023-02-28 17:15 出处:网络
How could I set开发者_如何学编程 file with #!/usr/bin/env node filetype to javascript?Make use of modeline.

How could I set开发者_如何学编程 file with #!/usr/bin/env node filetype to javascript?


Make use of modeline.

Put the following line:

// vim: set ft=javascript:

more info about vim's modeline.


In vim, :e $VIMRUNTIME/scripts.vim. This is the file that does filetype detection of "scripts" when there isn't something in the filename (like an extension) that tells vim the type. If you search for "#!" in this file you'll see the logic that does this. The problem is, it's a bunch of special cases and there isn't a fine-grained hook for what you want to do. One possibility would be to modify this scripts.vim file and also submit your modification back to be included in Vim.

If you don't want to modify files that came with vim then an alternative is to create your own scripts.vim in your personal runtimepath (use :set rtp? to see what it's set to on your system). This will be run in addition to the one in $VIMRUNTIME. You can include your logic for looking at the first line and detecting "node". You'll probably want to model your code after the logic in $VIMRUNTIME/scripts.vim.


autocommand can be used to check file types (this is how $VIMRUNTIME/scripts.vim is loaded).

You can specify commands to be executed automatically when reading or writing a file, when entering or leaving a buffer or window, and when exiting Vim.

...

WARNING: Using autocommands is very powerful, and may lead to unexpected side effects. Be careful not to destroy your text.

Add this to your .vimrc - it will be invoked when a new file is opened:

autocmd BufNewFile,BufRead * if match(getline(1),"node") >= 0 | set filetype=javascript | endif
0

精彩评论

暂无评论...
验证码 换一张
取 消