我正在使用:set textwidth=80
命令来让Vim编辑器自动进行硬换行。但是,有时对于文件中的某些行(例如LaTeX中的表格),我不想让Vim自动进行硬换行。是否有一种方法可以标记特定的行以禁用Vim中的硬换行?或者自动为指定行执行:set textwidth=0
命令?
我正在使用:set textwidth=80
命令来让Vim编辑器自动进行硬换行。但是,有时对于文件中的某些行(例如LaTeX中的表格),我不想让Vim自动进行硬换行。是否有一种方法可以标记特定的行以禁用Vim中的硬换行?或者自动为指定行执行:set textwidth=0
命令?
textwidth
和wrap
更改为整个文件,因此对于每次光标移动运行autocmd
可能是昂贵的)。ftplugin/tex.vim
文件中:" By default the text is
let s:textwidth = 90
let &l:textwidth=s:textwidth
" Toggle between "textwidth and wrap" and "textwidth=0 and nowrap".
" When editing a table, can be useful to have all the '&' aligned (using e.g.
" ':Tabularize /&') but without line brakes and wraps. Besides it's very
" annoying when line brakes "happen" while editing.
" As hopefully tables must be edited only from time to time, one can toggle
" wrap and textwidth by hand.
function! ToggleTwWrap() "{{{
" if textwidth and wrap is used, then disable them
if &textwidth > 0
let &l:textwidth=0
setlocal nowrap
else " otherwise re-enable them
let &l:textwidth=s:textwidth
setlocal wrap
endif
endfunction
:call ToggleTwWrap()
虽然没有现成的解决方案,但是你可以在:autocmd <buffer>
命令下监听CursorMoved,CursorMovedI
事件,并在每次光标移动时检查当前是否在所谓的“特定行”上,然后相应地修改本地的'textwidth'
选项。
autocmd CursorMoved,CursorMovedI <buffer> if IsSpecialLine() | setlocal textwidth=0 | else | setlocal textwidth=80 | endif
~/.vim/after/ftplugin/tex.vim
中(前提是你已经使用了:filetype plugin on
,使用after目录可以覆盖$VIMRUNTIME/ftplugin/tex.vim
所做的任何默认文件类型设置)。或者,您可以直接在~/.vimrc
中定义一个:autocmd FileType tex autocmd ...
,但是一旦您有许多自定义设置,这种方法可能变得难以处理。IsSpecialLine()
函数,您可能需要在当前行上匹配正则表达式(getline('.') =~# "..."
)。如果您可以通过语法高亮来识别“特定行”,那么我的OnSyntaxChange插件可以为您完成所有工作。IsSpecialLine()
函数吗?例如,该行是否包含未带有前导\
的&
(即包含&
但不包含\&
)。非常感谢! - Liwreturn getline('.') =~# '\\\@<!&'
。 - Ingo Karkat你可以为特定的文件类型设置它,但我认为你不能为单独的行更改这些设置(或任何其他设置)。
textwidth
设置。我非常喜欢对LaTeX源代码进行硬换行以便于阅读。然而,这会真正搞乱我的表格源代码。我只想禁用LaTeX表格代码的硬换行。 - Liwsetlocal textwidth=
。这样可以大大加快速度:autocmd CursorMoved,CursorMovedI <buffer> if IsSpecialLine() | if &textwidth != 0 | setlocal textwidth=0 | endif | else | if &textwidth != 80 | setlocal textwidth=80 | endif | endif