LaTeX: turn off text wrap and auto indent in maths environments

I use vim with vim-latex for editing latex files. I always have hard wrapping enabled using set tw=80. I also have the default vim-latex auto indent settings enabled.

I wonder if there is a way to disable hard wrapping and any form of automatic indentation when I am in a maths environment? That is, when I am between \begin{IEEEeqnarray*} and \end{IEEEeqnarray*}, for example, or any other maths environment.

There is a partial answer here: Why does vim still auto-indent LaTeX after I set noai noci nosi? It doesn't help with disabling text wrapping though.

Thanks in advance!

• Welcome to Vi and Vim! Aug 10 '21 at 18:13
• Thanks! I looked into this a bit more, and it seems it may be difficult: github.com/preservim/vim-pencil/issues/92. The autoformat blacklist feature in vim-pencil looks promising, although I haven't got it to work yet. Aug 11 '21 at 12:51

1 Answer

The following solution is loosely based on inkarkat's OnSyntaxChange and uses the built-in vimtex function vimtex#syntax#in_mathzone (see here). I have the following code in .vim/after/ftplugin/tex.vim. Every time the cursor moves or a buffer is entered, the function checks whether the current syntax zone is a maths zone, and adjusts indentation and text wrapping accordingly.

function! SwitchTextWidth()
if vimtex#syntax#in_mathzone()
setlocal tw=0 noautoindent nosmartindent nocindent indentexpr&
else
setlocal tw=85 autoindent smartindent cindent indentexpr=VimtexIndentExpr()
endif
endfunction
augroup cursor_moves
autocmd! * <buffer>
autocmd CursorMoved  <buffer> call SwitchTextWidth()
autocmd CursorMovedI <buffer> call SwitchTextWidth()
autocmd BufEnter     <buffer> call SwitchTextWidth()
augroup END


I chose to write my own function, rather than use OnSyntaxChange, so that I could use the built-in vimtex mathzone check.

• The executes at the end are not necessary, and you would do well to wrap that in an augroup (you can then use autocmd! * <buffer> to clear the group, same as you would normally with autocmd! for a global augroup/autocommand pairing. Sep 7 '21 at 15:35
• Thanks for the suggestions! Just edited the code to implement them. Sep 7 '21 at 16:04