Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

How could I set file with #!/usr/bin/env node filetype to javascript?

like image 921
guilin 桂林 Avatar asked Apr 25 '11 03:04

guilin 桂林


People also ask

How do I change the filetype in Vim?

As other answers have mentioned, you can use the vim set command to set syntax. :set syntax=<type> where <type> is something like perl , html , php , etc. There is another mechanism that can be used to control syntax highlighting called filetype , or ft for short.

How does Vim determine filetype?

vim is read from directories in the runtime path. The first match which executes :setf will set the filetype for the file Vim is creating or reading. If no rules execute :setf then additional filetype. vim files will be read.

What are .VIM files?

Settings file used by Vim, a text editing program often used by source code developers; commonly used to save settings, such as syntax highlighting rules, for the text editor when it is opened; can be referenced within the . VIMRC settings file.


3 Answers

Make use of modeline.

Put the following line:

// vim: set ft=javascript: 

more info about vim's modeline.

like image 62
Drake Guan Avatar answered Oct 04 '22 12:10

Drake Guan


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.

like image 41
Laurence Gonsalves Avatar answered Oct 04 '22 12:10

Laurence Gonsalves


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
like image 39
Andy Avatar answered Oct 04 '22 11:10

Andy