How to make Vim understand that *.md files contain Markdown code, and not Modula-2 code?

Cause of the issue

To understand which script was setting this filetype, I executed the following command after editing foo.md.

:verbose set filetype?

I found the following output.

  filetype=modula2
        Last set from /usr/share/vim/vim74/filetype.vim

In /usr/share/vim/vim74/filetype.vim, I found the following lines.

au BufNewFile,BufRead *.markdown,*.mdown,*.mkd,*.mkdn,*.mdwn,README.md  setf markdown
au BufNewFile,BufRead *.m2,*.DEF,*.MOD,*.md,*.mi setf modula2

These lines show that when README.md is edited, the filetype is set to markdown but on editing any other file with extension name as .md, the filetype is set to modula2. In other words, *.md files are recognized as Modula-2 source code but an exception is made for README.md for it to be recognized as Markdown code, perhaps due to the growing popularity of README.md files on GitHub.

Solution

Add the following statement to ~/.vimrc to set filetype=markdown for all .md files.

autocmd BufNewFile,BufRead *.md set filetype=markdown

This statement says that when starting to edit a new file that doesn't exist or when starting to edit a new buffer, after reading the file into the buffer, if the file matches the pattern *.md then set filetype=markdown.

Update

In the updated version of Vim that I have now, I find that this issue no longer exists.

$ vim --version | head -n 2
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Mar 31 2015 23:36:07)
Included patches: 1-488, 576
$ grep -E "markdown|modula2" /usr/share/vim/vim74/filetype.vim 
au BufNewFile,BufRead *.markdown,*.mdown,*.mkd,*.mkdn,*.mdwn,*.md  setf markdown
au BufNewFile,BufRead *.m2,*.DEF,*.MOD,*.mi     setf modula2

The patch at ftp://ftp.vim.org/pub/vim/patches/7.4/7.4.860 seems to have made this change. However, I am a little confused about how these changes that seem to be available in patch 860 is available in my version of Vim which includes patches 1-448, 576 only.


More complete answer with Markdown flavour

The other answer is correct, but incomplete. For this to equally work with the Save As… :sav command, one needs to extend the autocommand with BufFilePre:

autocmd BufNewFile,BufFilePre,BufRead *.md set filetype=markdown

It might also be interesting to specify a Markdown flavour, like Pandoc:

autocmd BufNewFile,BufFilePre,BufRead *.md set filetype=markdown.pandoc

Note that Vim currently allows specifying only one flavour though.

Tags:

Vim