I'm looking for a way to set filetype on load, a loading phase via ftdetect.

Right now I can open the files inside a given directory via some utility function that I wrote, and during the opening phase, I'm setting a filetype and it works.

Now what I want to achieve is that no matter where or how I open something of that kind, I would like to have a ftdetect rule, that matches the correct filetype.

Let's say I have a variable as let g:special_dir = '/path/to/dir', and that directory has an arbitrarily deep file tree.

I would like that whenever I open /path/to/dir/deep/route/file, I set one filetype, but If I open /path/to/dir/deep/route/directory I set another.

I have being reading, it's not clear to me If I can set a variable to be the matching criteria for the autocommand that does the setting, but at least if I can parametrize the glob expression that it's used there, I can instead of setting the file type plain and simple, I could call a function that does that.

In other words, I would like to find a way to do something like

function SpecialFileTypeResolver(filename)
 " Logic"

let g:special_dir = '/path/to/dir'

au BufNewFile,BufRead g:special_dir :call SpecialFileTypeResolver(<filename>)

Now I know that you can set file type to directories, netrw and nerdtree do something similar, but honestly I haven't had a deep jump in to the code, I've only tried and grep out the file where that condition is coded, but no luck there.

Any ideas?

  • 1
    Use :execute to interpolate expressions into the command.
    – D. Ben Knoble
    Jul 3 at 12:59
  • Here is an example: github.com/benknoble/wiki-md/blob/master/ftdetect/wiki.vim If that helps, let me know and I can write up an answer.
    – D. Ben Knoble
    Jul 3 at 18:33
  • Ok, that worked, but I'm still missing the case on opening directories, I thought of adding a rule on ftplugin/netrw.vim to check change the ft, but it doesn't seem to work.
    – ekiim
    Jul 4 at 20:25
  • Ah, opening directories is its own beast; other than using netrw im not familiar with doing anything special for those
    – D. Ben Knoble
    Jul 4 at 20:45
  • If you check the way nerdtree does that, it has a way to hijack netrw, I managed to solve this.
    – ekiim
    Jul 5 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.