Rook
Rook

Reputation: 62588

Vim filetype detecting

Can Vim detect filetype of a buffer with contents, but which doesn't have a name yet (not yet saved)? :filetype detect doesn't do much.

Upvotes: 6

Views: 4004

Answers (4)

Nicky McCurdy
Nicky McCurdy

Reputation: 19573

You can do this manually.

:set filetype=EXT

Note that EXT is the extension for the filetype you want, not necessarily the name of the language itself.

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172768

Most filetypes are detected by their file name (and/or location), some (mostly those with a #! shebang line) by their contents.

If you don't want to save the buffer yet, but have detection, you can name the buffer via :file name.ext. Then, the detection via :filetype detect will work.

If you just want syntax highlighting (and corresponding filetype settings) quickly, just manually set the filetype via :setf name.

Upvotes: 5

Ken
Ken

Reputation: 8917

If the file contains a #! on line one it's easy.

For example:

" finish if the filetype was detected
if did_filetype()
    finish
endif

" Ruby & Python ftplugins
if getline(1) =~ '^#!.*ruby'
    setfiletype ruby
elseif getline(1) =~ '^#!.*python'
    setfiletype python
endif

Upvotes: 0

Neil
Neil

Reputation: 55432

As the help for vim says, it works in some cases, for instance if you type

#!/bin/sh

then it will detect as sh script.

Upvotes: 0

Related Questions