I would like to have a default textwidth of 80 characters except for a few file extensions like txt
. The following lines appear to work, except for the first time when I edit (and create) a txt
file.
setlocal textwidth=80
autocmd bufreadpre *.txt set textwidth=0
What is the correct way to do this?
First, you've got the scopes the wrong way; use :set
for the global default and :setlocal
for the buffer-local override in the :autocmd
.
Second, BufReadPre
is only for reading existing files, not new ones; that's why it doesn't work the first time. Instead, you should use BufNew,BufRead
; this captures both cases, and only applies after the file was read, so it will still work when you use modelines or have a setting in an filetype plugin.
Third, the :autocmd
solution tends to become unwieldy once you have many customizations. If you only want to enable a setting for certain filetypes, put the corresponding :setlocal
commands into ~/.vim/after/ftplugin/<filetype>.vim
, where <filetype>
is the actual filetype (e.g. java
). (This requires that you have :filetype plugin on
; use of the after directory allows you to override any default filetype settings done by $VIMRUNTIME/ftplugin/<filetype>.vim
.)
use setlocal
autocmd bufreadpre *.txt setlocal textwidth=0
instead of set
.
With setlocal
you make sure that the value you're setting is set in the current buffer, not for all buffers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With