vimvim-plugin

Vim: Jump to last non-whitespace character of a file


I have an ora file that is 200,000 lines long but the last 60,000 some lines are all blank carriage returns/whitespace.

I know G jumps to the end of a file, but I do I configure vim to jump to the last line or character that is non-whitespace and non-carriage return?


Solution

  • G?\SEnter

    Go to end of document, search backwards, find a non-whitespace, go. If you need a mapping for that,

    nnoremap <Leader>G G?\S<CR>:noh<CR>
    

    EDIT: This will not work if the last line is not blank. Here's a modification that will work if the last character is not blank:

    nnoremap <Leader>G G$?\S<CR>:noh<CR>
    

    To fix that, it gets a bit complicated. We'll go to the last character of the file, and test whether it's a whitespace or not. If it is not a whitespace, we're done; but if it is, we can use the previous solution. (This also saves the state of things we mess up, so it will interfere minimally with your work.)

    function! LastChar()
      let oldsearch = @/
      let oldhls = &hls
      let oldz = @z
    
      norm G$"zyl
      if match(@z, '\S')
        exe "norm ?\\S\<CR>"
      endif
    
      let @/ = oldsearch
      let &hls = oldhls
      let @z = oldz
    endfunction
    
    nnoremap <Leader>G :call LastChar()<CR>