Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically set multiple file types in `filetype` if a file has multiple extensions

Tags:

vim

I frequently develop on Ruby on Rails. With the recent inclusion of Tilt in RoR 3, we have file extensions like .scss.erb. How can I make the filetype = scss.erb in this case automatically, and the same for every file that has multiple extensions?

Edit: It should be scss.eruby in this case, as erb extension defaults to eruby filetype.

Edit: If it wasn't clear, I'm looking for a way to make this work dynamically for all files with multiple extensions. For example, file foo.js.html should have a filetype of js.html.

Edit again: Prince Goulash's answer doesn't take the default filetype for a particular extension.

like image 233
Dogbert Avatar asked Dec 07 '11 10:12

Dogbert


1 Answers

In your vimrc:

autocmd BufRead,BufNewFile *.scss.erb setlocal filetype=scss.eruby

(see :help ftdetect, section 2).

EDIT

To set the filetype dyanamically for multiple extensions, this seems to work for me:

autocmd BufRead,BufNewFile *.*.*
    \ sil exe "setlocal filetype=" . substitute(expand("%"),"^[^.]*\.","",1)

The substitute command constructs the filtype by simply stripping all text from the filename before the first .. There may be a more sophisticated way...

EDIT AGAIN

Here's another attempt. MultiExtensionFiletype() is function that uses the default filetype of the last part of the extension and prefixes it with the first part of the extension (i.e. the part sandwiched between the dots).

function MultiExtensionFiletype()
    let ft_default=&filetype
    let ft_prefix=substitute(matchstr(expand('%'),'\..\+\.'),'\.','','g')
    sil exe "set filetype=" . ft_prefix  . "." . ft_default
endfunction

The function must be called on a BufReadPost event so the initial filetype is set by ignoring the multiple extensions.

autocmd BufReadPost *.*.* call MultiExtensionFiletype()

Hopefully this answer is converging on something useful!

like image 95
Prince Goulash Avatar answered Nov 08 '22 18:11

Prince Goulash