Vim scripting: Preserve cursor position and screen view in function call

前端 未结 5 897
庸人自扰
庸人自扰 2021-02-02 11:11

I have some Vim functions that make changes to the document format. When I call this function, I currently use something like the following to save and restore my cursor positio

5条回答
  •  清酒与你
    2021-02-02 11:36

    There is a plugin but I use a single function like this:

    if !exists('*Preserve')
        function! Preserve(command)
            try
                " Preparation: save last search, and cursor position.
                let l:win_view = winsaveview()
                let l:old_query = getreg('/')
                silent! execute 'keepjumps ' . a:command
             finally
                " Clean up: restore previous search history, and cursor position
                call winrestview(l:win_view)
                call setreg('/', l:old_query)
             endtry
        endfunction
    endif
    

    then I call it to clean trailing spaces

    fun! CleanExtraSpaces()
        call Preserve(':%s/\s\+$//ge')
    endfun
    com! Cls :call CleanExtraSpaces()
    au! BufwritePre * :call CleanExtraSpaces()
    

    del blank lines

    fun! DelBlankLines()
        call Preserve(':%s/^\n\{2,}/\r/ge')
    endfun
    command! -nargs=0 DelBlank :call DelBlankLines()
    

    and change Header (Last Modified) information

    fun! ChangeHeader()
        call Preserve(':1,5s/Last Change: \zs.*/\=strftime("%c")/e')
    endfun
    command! -nargs=0 CH :call ChangeHeader()
    au BufWritePost * :call ChangeHeader()
    

提交回复
热议问题