Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: gf with file extension based on current FileType

Tags:

vim

I'm trying to set up my .vimrc so gf will automatically work on paths that are missing file extensions, by trying to open files with the same extension as the current FileType.

In other words, I want something like:

autocmd FileType <filetype> setl suffixesadd+=<exts>

where <exts> is a list of all file extensions associated with the current <filetype>.

For example, my filetype.vim defines the FileType "javascript" as files with names *.js,*.javascript,*.es,*.jsx, and *.json, so whenever I am editing a javascript buffer, if the cursor is on the path ./index, running gf should try to open ./index.js. If that file doesn't exist then it should try ./index.javascript, and so on. If the filetype is python, it should try ./index.py, ./index.pyw, etc.

I'm pretty sure the autocmd above should produce the intended behavior if I just run it for every FileType, but I'm not sure how to do that.

like image 826
Elliot Hatch Avatar asked Oct 13 '15 03:10

Elliot Hatch


1 Answers

Those default extensions are not stored anywhere in a useful format so you will need to build your own list and loop through it to run your autocommand.

Something like:

augroup suffixes
    autocmd!

    let associations = [
                \["javascript", ".js,.javascript,.es,.esx,.json"],
                \["python", ".py,.pyw"]
                \]

    for ft in associations
        execute "autocmd FileType " . ft[0] . " setlocal suffixesadd=" . ft[1]
    endfor
augroup END
like image 135
romainl Avatar answered Nov 15 '22 09:11

romainl