For context, see How can I automate filetype detection when using sudoedit?

Say filea has filetype foo, which is detected based on varying factors, including the name, the full path or the contents of the file (or combinations thereof). I have a buffer containing filea's contents, and I want to apply filea's filetype, without actually opening filea.

Assume that I already have the path and name of the file, and the contents are in the current buffer.

How do I go about this?

Note that I may not be able to open the actual file. A simple example is Polkit configuration in Ubuntu systems. Files in /etc/polkit-1/localauthority are accessible only to root.

Thanks to Carpetsmoker's tip about :filetype detect, I came up with one way. Something like the following could do the trick:

function SetActualFiletype (actual_path)
    let l:cur_file=expand('%')
    exec 'file' fnameescape(a:actual_path)
    filetype detect
    exec 'file' fnameescape(cur_file)

This way, Vim has access to everything it would normally have when opening that file.

This isn't safe from autocmds which are writing the file (and other such oddities).

  • Comments are not for extended discussion; this conversation has been moved to chat. – muru Mar 14 '16 at 23:34
  • Tim Pope's vim-eunuch advertises filetype detection based on the original filename. Didn't look how it handles it, and I don't know if it was already mentioned in your other thread. – VanLaser Mar 14 '16 at 23:55
  • 1
    @VanLaser no, it hasn't been mentioned yet, and I think it might be the answer to a third question as well: vi.stackexchange.com/q/258/205 – muru Mar 15 '16 at 0:02

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.