Using autocommand to set local formatprg

Skip to first unread message

Spencer Collyer

Jun 13, 2022, 6:42:44 PMJun 13
i'm running Vim on an Arch Linux build.

When editing *.txt files I want to set the formatprg to use the 'fmt'
program, as well as modifying my 'diffopt' value for those files.

I have the following lines in my .vim/filetype.vim:

if exists("did_load_filetypes")
augroup filetypedetect
" ... stuff for other filetypes
au! BufRead,BufNewFile *.txt setlocal formatprg="fmt -w70 -u"
au! BufRead,BufNewFile *.txt set diffopt-=iwhite diffopt+=iwhiteeol
au! BufEnter *.txt set diffopt-=iwhite diffopt+=iwhiteeol
au! BufLeave *.txt set diffopt-=iwhiteeol diffopt+=iwhite
augroup END

When I edit a *.txt file, I can see that the 'diffopt' is being set
correctly, but the 'formatprg' is not set. I've tried it with 'set' as
well as 'setlocal' and it still doesn't change.

I tried running 'verbose set formatprg' but that tells me nothing.
Doing the same for 'diffopt' tells me it is set in the filetype.vim

Any clues as to why the 'formatprg' option isn't being set? Is it not
allowed to be set by an autocmd? Should I create a text.vim plugin just
to set it?

Thanks in advance for any help.


Gary Johnson

Jun 13, 2022, 7:44:26 PMJun 13
The problem is that you're starting each autocommand with


As ":help autocmd-remove" says, an autocommand of that form first
removes all autocommands associated with the event and pattern
specified, then adds the command. So, your

au! BufRead,BufNewFile *.txt set diffopt-=iwhite diffopt+=iwhiteeol

removes the preceding

au! BufRead,BufNewFile *.txt setlocal formatprg="fmt -w70 -u"

I see that you appear to have followed the example under ":help
new-filetype". A better example for your purposes is found under
":help 43.2", but in neither place is the significance of the '!'
explained. Also, you're not doing filetype detection, you're simply
setting options depending on the filename suffix.

In any case, just removing the '!' from at least your second
autocommand should fix the problem, i.e.,

au BufRead,BufNewFile *.txt set diffopt-=iwhite diffopt+=iwhiteeol

Whether or not you keep the other '!'s depends on what you're trying
to achieve, so I'll leave that to you to figure out.


Reply all
Reply to author
0 new messages