Vim autocmd runs erroneously on readonly

Tag: vim Author: zhao__2008 Date: 2014-01-18

Among other things, I have in my .vimrc file the following:

function! BashHeader()
    source ~/.vim/bash_header.txt

autocmd BufNewFile *.bash,*.sh :call BashHeader()

The file bash_header.txt just has a boilerplate header I want at the top of my bash script files.

At first glance, this works great – vim somefile gives me no header, while vim somescript.bash automatically inserts the header. The trouble comes when I use the startup mode shortcut view. view, as this Vim documentation describes, is a shortcut for starting Vim in readonly mode, like vim -R somefile. But when I start Vim in this manner, opening a file that already exists, I get the following message:

$> view somefile
"somefile" "somefile" [readonly] 6L, 359C
Error detected while processing ~/.vim/bash_header.txt:
line    2:W10: Warning: Changing a readonly file
Press ENTER or type command to continue

Note that I've replaced the real path to my .vim directory with ~; I don't think this is an important omission.

Clearly, Vim is trying to add a header to this file, despite the facts that

  1. somefile already exists (and should not trigger the BufNewFile event required for my autocmd), and

  2. somefile doesn't even end in .bash or .sh, so it should not trigger the pattern required by my autocmd.

And indeed, once I press enter, my bash header has been inserted into this readonly buffer.

To further complicate matters, invoking Vim in readonly mode explicitly, as in vim -R somefile does not display the same erroneous behavior. That works just as expected.

What am I missing?

EDIT: Here are the contents of bash_header.txt:

#! /bin/bash
# $Author$
# $Date$
# $HeadURL$
# $Revision$

Further, running view -u NONE somefile does not exhibit the error. I had a thought – perhaps my .vimrc was not being evaluated when using the view alias, but only when using vim. As a simply test, I added

echo ".vimrc was run."

to my .vimrc file. A-ha! When I run vim somefile, I see the message printed, but not when I run view somefile. So now my question becomes, what would cause vim to use my .vimrc, but view not to? And how, then, is view getting hold of my bash_header.txt even though it does not appear to be evaluating my .vimrc?

Other Answer1

Please share ~/.vim/bash_header.txt.

If that file really only contains boilerplate, you shouldn't use :source because Vim will execute its content as if it was Vimscript. For quick and dirty templating, you are supposed to us :0r ~/.vim/bash_header.txt.

Also, I can't replicate your problem here: the autocmd is not run when I do view. You should reduce your config to its base components to refine your question:

  1. What is the content of ~/.vim/bash_header.txt?
  2. What happens without plugins? With an empty ~/.vimrc?
  3. Use the exact path of your files.