René Nyffenegger
René Nyffenegger

Reputation: 40563

How do i correctly set the filetype txt for *.txt files in vim

I am trying to figure out how I am supposed to set the filetext to txt for *.txt files in vim

I was tempted to add a file into the ftdetect directory with the content

autocmd BufNewFile,BufRead    *.txt     set ft=txt

The problem with this approach, however, is that the autocmd is also triggered when I edit robots.txt. The default of vim ($VIMRUNTIME/filetype.vim) is to detect the robots.txt file and (correctly) set the filetype to robots in that case. I don't want to change that.

Additionally, I am not sure why I have to include this autocmd line into the ftdected directory. What is the difference to just add the line into my vimrc file?

Upvotes: 0

Views: 774

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172698

Use :setf txt instead of :set ft=txt. This way, a previously set filetype (e.g. for robots.txt) is kept. From :help new-filetype:

The files in the "ftdetect" directory are used after all the default checks, thus they can overrule a previously detected file type. But you can also use |:setfiletype| to keep a previously detected filetype.

The benefit of the ftdetect directory is that it provides a well-known abstraction, and allows to separate the rules (this is important when you want to publish your filetype plugin for others). You could also put this (enclosed with :augroup filetypedetect) into your ~/.vimrc, but that's not so maintainable and the precedence rules are different.

Upvotes: 4

Related Questions