I'm trying to learn a bit of vimscript and currently reading the 12th chapter of Learn Vimscript the Hard Way.
In this page, the author says :
A common idiom in Vim scripting is to pair the BufRead and BufNewFile events together to run a command whenever you open a certain kind of file, regardless of whether it happens to exist already or not.
So I thought I would try this for a problem I have. I've got a folder in which I would like to be sure all files have the filetype markdown. The folder contains existing files, which have the filetype text and don't have any extension.
I added the following line to my vimrc :
autocmd BufNewFile,BufRead /path/to/my/folder/* set filetype=markdown
Now, when I create a new file inside my folder, the filetype is automatically set to markdown. So the BufNewFile event is triggered as expected. However, when I open an existing file, the filetype remains text, as if the BufRead event was not triggered.
I found two solutions :
- delete the content of
~/.vim/view
- change the event to watch from
BufNewFile
,BufRead
toBufEnter
.
But out of curiosity I would like to understand a few things:
- Why is the
BufRead
event not working ? - What's the difference between
BufRead
andBufEnter
? - For each file previously edited in vim, the
~/.vim/view
folder seems to have a corresponding file which stores its settings (filetype, indentation...). The settings stored in that file seem to have priority over an autocmd triggered by theBufRead
event. So, what's the purpose of this event if it's unable to bypass what's inside theview/
folder ? - If I want to be sure to automatically change any setting for a file with an autocommand, is the
BufEnter
event the right one to choose ?
:mkview
manually? If possible I would like to reproduce what you're experiencing in order to look for an answer.au BufWinLeave ?* mkview
andau BufWinEnter ?* silent loadview
I suppose it was to automatically save and restore folds.