Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing filetype based on file extention in vim

I want to change the filetype based on file extension in vim.

I have the following code in the my .vimrc

autocmd BufNew,BufNewFile,BufRead *.txt,*.text,*.md,*.markdown setlocal ft=markdown

But when I open a file with the extention .md file, the filetype is not changed. I run :set ft command and it shows the output as filetype=modula2.

Am I doing anything wrong?

Edit:

I started to debug by renaming my old .vimrc file and created a new one with just this line. It was working properly. Then I replaced my old .vimrc file and everything seems to be working fine. Guess it was because of some issues in some addon which I am using.

But accepting ZyX's answer, since it thought me an alternate way to do this.

like image 327
Sudar Avatar asked Dec 12 '22 21:12

Sudar


2 Answers

I created a ~/vim/ftdetect/markdown.vim file with this line

autocmd BufNewFile,BufRead *.md,*.mkdn,*.markdown :set filetype=markdown

Reading the docs for filetype, setfiletype only sets if filetype is unset. So you need to use set for an unconditional change to a filetype.

like image 172
xdg Avatar answered Jan 05 '23 00:01

xdg


Wondering whether this line goes before or after filetype … on. In the former case you should try putting it (your autocommand) after this line. Better if you put it into ~/.vim/ftdetect/markdown.vim and use setfiletype markdown instead of setlocal ft=markdown:

augroup filetypedetect
    autocmd BufNew,BufNewFile,BufRead *.txt,*.text,*.md,*.markdown :setfiletype markdown
augroup END

: it is the default way of doing such things. ~/.vim must go before /usr/share/vim/* paths in 'runtimepath' option in this case (it does by default).

like image 29
ZyX Avatar answered Jan 04 '23 23:01

ZyX