Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Vim detect filetype from the shebang line?

Sometimes I write scripts without any filename extension. For example:

#!/usr/bin/env node

console.log('hello world!');

I hope that Vim can detect the filetype from the shebang line (e.g. #!/usr/bin/env node is javascript). What should I put into filetype.vim?

like image 340
Lai Yu-Hsuan Avatar asked Jan 17 '12 06:01

Lai Yu-Hsuan


3 Answers

Following the instructions listed in :help new-filetype-scripts, create the scripts.vim file in the user runtime directory (~/.vim/ on Unix-like systems), and write the following script in it:

if did_filetype()
    finish
endif
if getline(1) =~# '^#!.*/bin/env\s\+node\>'
    setfiletype javascript
endif
like image 170
ib. Avatar answered Nov 17 '22 08:11

ib.


create this file ~/.vim/ftdetect/node.vim with this contents

fun! s:DetectNode()
    if getline(1) == '#!/usr/bin/env node'
        set ft=javascript
    endif
endfun

autocmd BufNewFile,BufRead * call s:DetectNode()
like image 11
aliva Avatar answered Nov 17 '22 10:11

aliva


If you're interested in a plugin, one does exist for this:

https://github.com/vitalk/vim-shebang

This contains a pattern for node -> javascript highlighting.

AddShebangPattern! javascript ^#!.*\s\+node\>
like image 3
dhulihan Avatar answered Nov 17 '22 10:11

dhulihan