5

:set textwidth=80用来让 Vim 编辑器自动进行硬包装。然而,有时对于文件中的某些行(例如 LaTeX 中的表格),我不希望 Vim 自动进行任何硬包装。有没有办法标记某些行以禁用 Vim 中的硬包装?还是自动:set textwidth=0只针对指定的行?

4

4 回答 4

2

没有什么是开箱即用的,但您可以使用事件构建解决: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。)或者,您可以:autocmd FileType tex autocmd ...直接在您的~/.vimrc.

对于该IsSpecialLine()函数,您可能需要匹配当前行 ( getline('.') =~# "...") 上的正则表达式。如果您可以通过语法高亮识别“某些行”,我的OnSyntaxChange 插件可以为您完成所有工作。

于 2013-10-06T12:07:32.060 回答
2

我试过Ingo Karkat answer。尽管它确实工作得很好并且可以满足 OP 的要求,但我发现它会分散注意力(如果我有长表,其中有数百个字符长的行,那么在通过表时会有很多上下移动)并且会减慢很多vim 处理大文件(整个textwidth文件的andwrap被更改,因此为每个光标移动运行可能代价高昂)。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()

禁用换行和文本宽度,然后在我完成表格时再次禁用。

当然,您可以创建命令或地图

于 2014-01-03T21:14:24.763 回答
0

您当然可以为特定的文件类型设置它,但我认为您不能为各个行更改这些设置(或任何设置)。

于 2013-10-06T00:50:57.420 回答
0

Ingo Karat 的回答有效,但在每个光标移动时设置 textwidth太慢了。setlocal textwidth=此改编版本仅在文本宽度实际发生变化时才会调用。这大大加快了速度:

autocmd CursorMoved,CursorMovedI <buffer> if IsSpecialLine() | if &textwidth != 0 | setlocal textwidth=0 | endif | else | if &textwidth != 80 | setlocal textwidth=80 | endif | endif
于 2016-09-07T16:39:20.617 回答