43

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?

2
  • 7
    Why not add a second or last line modeline # vim: ft=javascript since Vim already checks for the modeline rather than reinventing the wheel? Commented Jan 17, 2012 at 7:04
  • 15
    @SwaroopCH Why not parse the information from a line already in the file that has the necessary information, like any real editor has done for years, rather than repeating it redundantly in an editor specific fashion that junks up the file for users of other editors? /me dons flame suit Commented Jan 17, 2012 at 7:29

4 Answers 4

37

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
4
  • 3
    See also the whole :help new-filetype section which is worth reading.
    – ib.
    Commented Jan 17, 2012 at 8:36
  • 1
    why doesn't the forward slashes be escaped? /bin/env Commented Jan 18, 2012 at 9:40
  • 2
    @LaiYu-Hsuan: A forward slash character is not a special symbol according to syntax of Vim regular expressions. It could be escaped as \/, of course, but it is necessary only for patterns that are used in a forward search command (/) or in a substitution command (:s) when pattern delimiters are slashes.
    – ib.
    Commented Jan 19, 2012 at 2:14
  • 1
    You can also put these lines inside .vimrc by using autocmd, probably bufread is the one, to fire the function.
    – Yosh
    Commented Oct 27, 2014 at 2:33
11

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()
2
  • 5
    actually, "ft=javascript" is much more likely to work. Most people DO have "javascript" defined and DON'T have "node" defined. Commented Mar 29, 2012 at 0:42
  • for those that prefer it on a single line: autocmd BufNewFile,BufRead * if getline(1) == '#!/usr/bin/env node' | set ft=javascript | endif Commented Jun 27, 2022 at 15:41
4

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\>
0

A little late to the party, but Node.vim handles detecting such JavaScript files for you. And then some. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.