Vim Tips Wiki
Advertisement

Obsolete tip

This tip has been merged into another tip.
See VimTip130 for the current tip.

Please do not edit this tip, and do not edit the discussion page.
If anything needs to be improved, please fix VimTip130.


Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created February 16, 2009 · complexity basic · author MizardX · version 7.0

Ever get tired of manually changing the filetype to yourfavouritelanguage when starting to edit a blank buffer?

The simple way is to type:

setf python

into your .vimrc. The problem with this is that normal text-files also get highlighted as code.

If you instead type this:

" default filetype
let g:do_filetype = 0
au GUIEnter,BufAdd * if expand('<afile>') == "" | let g:do_filetype = 1 | endif
au BufEnter * if g:do_filetype | setf python | let g:do_filetype = 0 | endif

you would only highlight new files. GUIEnter is for the buffer that is opened on startup. BufAdd is for new blank buffers.

Why the need to use a global variable, and not set the filetype immediately, is to my understanding, because the buffer hasn't been fully created when the autocmd is triggered.

Comments

It won't work for the very first buffer created when Vim starts up, but you can actually set the filetype automatically when editing a new buffer simply by giving the :new or :edit command an argument with the desired file name. For example, typing :tabnew to get your new buffer will create it without a filetype, but typing :tabnew somefilename.py instead will apply filetype detection rules, setting the filetype in your new buffer to python automatically.

Advertisement