Ashwin Nanjappa
Ashwin Nanjappa

Reputation: 78478

How to enable line wrap only for certain filetypes in Vim?

I have turned off line wrap in Vim by adding this in my vimrc:

set nowrap

But, I would like to have line wrap turned on automatically when I am editing *.tex files. So, I added this to my vimrc:

augroup WrapLineInTeXFile
    autocmd!
    autocmd FileType tex set wrap
augroup END

This should enable line wrap when the filetype is detected to be TeX. This works as expected for tex files, but if I open a non-tex file in the same Vim session, it has line wrap turned on!

Enabling and disabling word wrap automatically on different file extensions on Vim suggests using BufRead instead. But, even that has the same effect: if I first open a TeX file, followed by a non-TeX file, the non-TeX file has line wrap turned on.

How do I correctly enable line wrapping only for a certain filetype?

Upvotes: 11

Views: 4034

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172510

The 'wrap' option is local to window. When you use :set, it will also apply to any newly opened windows. You want to use :setlocal.

Also, though your :augroup WrapLineInTeXFile works, it is cumbersome and doesn't scale to many settings. If you have :filetype plugin on in your ~/.vimrc, you can place filetype-specific settings (like :setlocal wrap) in ~/.vim/after/ftplugin/tex.vim (use of the after directory allows you to override any default filetype settings done by $VIMRUNTIME/ftplugin/tex.vim).

Upvotes: 5

Jim Stewart
Jim Stewart

Reputation: 17323

You can use setlocal for this. It'll only affect the current buffer.

augroup WrapLineInTeXFile
    autocmd!
    autocmd FileType tex setlocal wrap
augroup END

That'll be applied to every new TeX buffer.

Upvotes: 10

Related Questions