When reading from stdin with something like fancy-command | vim -R -, vim does not detect the filetype (i.e. set filetype prints filetype=). When I know the right vim filetype, I can provide it from the command line (or from within vim) with fancy-command | vim -R +'set ft=cpp' -.

Now, that pipe might be in a shell script e.g. in conjunction with git show <commit hash>:<path>, such that I don't want to hardcode cpp as filetype. I have thought about just taking the end of <path> and provide it to ft=, but I expect this to fail (CMakeLists.txt are not identified by their suffix).

So what I'd like to do is run vim's filetype detect but with a pretended filename when vim is actually reading from stdin.

1 Answer 1


You could try something like the following:



cat $file | vim -c "doautocmd BufRead $file" -

This will run the autocommands that would normally run, when you would open a file with the given name. This includes filetype detection.

To my surprise, this also works when the file name contains a space.

The name is only used to run the autocommands, the name of the loaded buffer is not changed (it still is [No Name]).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.