Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set different textwidths for specific file extensions in .vimrc?

Tags:

vim

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?

like image 499
Paul Baltescu Avatar asked Apr 26 '13 15:04

Paul Baltescu


2 Answers

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.)

like image 184
Ingo Karkat Avatar answered Nov 12 '22 06:11

Ingo Karkat


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.

like image 20
René Nyffenegger Avatar answered Nov 12 '22 08:11

René Nyffenegger