如何在保存文件open和space2tab上调用vim函数space2tab

时间:2013-11-14 07:58:27

标签: vim

我是VIM的新手,我找到了两个函数Tab2SpaceSpace2Tab。它们是真实的命令并且在给定此函数的情况下调用另一个函数。我可以执行:Tab2Space:Space2Tab。但我希望当我打开文件进行编辑时,会自动在tab2space之前传递Space2Tab:w

" Return indent (all whitespace at start of a line), converted from
" tabs to spaces if what = 1, or from spaces to tabs otherwise.
" When converting to tabs, result has no redundant spaces.
function! Indenting(indent, what, cols)
  let spccol = repeat(' ', a:cols)
  let result = substitute(a:indent, spccol, '\t', 'g')
  let result = substitute(result, ' \+\ze\t', '', 'g')
  if a:what == 1
    let result = substitute(result, '\t', spccol, 'g')
  endif
  return result
endfunction

" Convert whitespace used for indenting (before first non-whitespace).
" what = 0 (convert spaces to tabs), or 1 (convert tabs to spaces).
" cols = string with number of columns per tab, or empty to use 'tabstop'.
" The cursor position is restored, but the cursor will be in a different
" column when the number of characters in the indent of the line is changed.
function! IndentConvert(line1, line2, what, cols)
  let savepos = getpos('.')
  let cols = empty(a:cols) ? &tabstop : a:cols
  execute a:line1 . ',' . a:line2 . 's/^\s\+/\=Indenting(submatch(0), a:what, cols)/e'
  call histdel('search', -1)
  call setpos('.', savepos)
endfunction
command! -nargs=? -range=% Space2Tab call IndentConvert(<line1>,<line2>,0,<q-args>)
command! -nargs=? -range=% Tab2Space call IndentConvert(<line1>,<line2>,1,<q-args>)
command! -nargs=? -range=% RetabIndent call IndentConvert(<line1>,<line2>,&et,<q-args>)

基本上我想要缩进进行编辑,但在保存之前它会转换为空格。

1 个答案:

答案 0 :(得分:2)

要在打开时转换文件,请将BufRead事件与:autocmd一起使用。在这里,我使用*作为模式,以便它适用于所有打开的文件;你可以根据自己的需要进行调整。

:autocmd BufRead * Space2Tab

在写入时,您要撤消转换,然后在写入后立即重做(以便您可以继续编辑)。这组:autocmd将执行此操作:

:autocmd BufWritePre * Tab2Space
:autocmd BufWritePost * Space2Tab