(g)Vim - 在运行时禁用history / viminfo

时间:2013-01-27 06:23:46

标签: vim

我有一些命令用于压缩文件保存,post保存解压缩(只是开头的缩进)。我遇到困难的一件事是我不希望将命令添加到历史记录中。既不是命令也不是光标位置等

我认为我要做的是在预写时关闭viminfo,然后在写后重新打开它。但我似乎无法弄明白。这是我正在使用的功能:

function! s:CompressIndent()
    augroup CompressIndent
        autocmd!

        " Befor writing, change 4 spaces (and single tabs) into 2 spaces
        autocmd BufWritePre * set viminfo="NONE"              " Turn off 'history' before making the pre-write substitutions
        autocmd BufWritePre * %substitute/^\( \+\)\1/\1/e " Halve the number of spaces of indentation
        autocmd BufWritePre * set tabstop=2               " Make sure that tabs = 2 spaces before re-tabbing
        autocmd BufWritePre * retab                       " Turn tabs into two spaces

        " When opening a file (and after writing the file) turn 2 spaces into (and 4 tabs) into 4 spaces
        autocmd BufReadPost,BufWritePost * set tabstop=4         " Make sure to display in 4 tabs
        autocmd BufReadPost,BufWritePost * %substitute/^ \+/&&/e " Double the number of spaces of indentation on Reading and writing
        autocmd BufReadPost,BufWritePost * set viminfo='20,\"200 " Turn back on history
    augroup END
endfunction

我已尝试set viminfo="NONE"set viminfo=""。似乎都没有效果。

任何帮助将不胜感激!

谢谢!

修改

这就是我现在使用它的地方,但我仍然没有完全使用它(现在缩进已经破坏,但histdel()也不能正常工作。保存文件后,光标移动到一个全新的位置和撤消历史已经分支或奇怪的事情:

function! s:CompressIndent()
    augroup CompressIndent
        autocmd!

        " Befor writing, change 4 spaces (and single tabs) into 2 spaces
        autocmd BufWritePre * call s:SpaceSubstitution("2") " Halve the number of    spaces of indentation
        autocmd BufWritePre * set tabstop=2                 " Make sure that tabs = 2 spaces before re-tabbing
        autocmd BufWritePre * retab                         " Turn tabs into two spaces

        " When opening a file (and after writing the file) turn 2 spaces into (and 4 tabs) into 4 spaces
        autocmd BufReadPost,BufWritePost * set tabstop=4    " Make sure to display in 4 tabs
        autocmd BufReadPost,BufWritePost * call s:SpaceSubstitution("4") " Double the number of spaces of indentation on Reading and writing
    augroup END
endfunction
command! -n=0 -bar CompressIndent :call s:CompressIndent()

function! s:SpaceSubstitution(toSpaces)
    if a:toSpaces == "2"
        %substitute/^\( \+\)\1/\1/e
    else
        %substitute/^ \+/&&/e
    endif

    call histdel('search', -1)
endfunction

2 个答案:

答案 0 :(得分:2)

Vim有四个用于操作历史记录的函数,:h history-functions为您提供了一个列表和简短描述。在这四个中,您需要的是:

histdel()

您可以在:h histdel()中阅读。

答案 1 :(得分:2)

操纵'viminfo'太棒了,无法在这里挥舞。 :autocmd执行的命令不会添加到命令历史记录中。

我唯一看到的是:substitute污染了搜索历史和当前的搜索模式。通过将命令移动到:function并从autocmd调用该命令,可以避免很多事情。请参阅:help function-search-undo

在函数结束时,您唯一需要做的就是从历史记录中删除搜索模式:

:call histdel('search', -1)

编辑:要保持当前光标位置,请使用以下内容包裹:substitute

let l:save_view = winsaveview()
    %substitute/...
call winrestview(l:save_view)