Monday, June 13, 2022

Re: Using autocommand to set local formatprg

On 2022-06-10, Spencer Collyer wrote:
> 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")
> finish
> endif
> 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
> file.
>
> 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?

The problem is that you're starting each autocommand with

au!

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.

Regards,
Gary

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20220613234416.GC20513%40phoenix.

No comments: