5

Sometimes ex commands have the useless side effect of jumping, probably to the last place they affected. Can this be prevented? I would prefer it if ex commands left my screen exactly the same as before their execution.

  • 1
    Would :h :keepjumps be what you are looking for? – statox Apr 4 '16 at 11:38
  • 1
    @statox, no, the screen still changes. keepj. seems to preserve some marks and lists, not the screen. – Toothrot Apr 4 '16 at 11:49
  • Arf I read your question too fast, sorry :-) – statox Apr 4 '16 at 11:59
6
+100

While I don't see in the doc any option/flag you can use for a ex command, I think you can simply use the C-o command afterward.

From the documentation:

CTRL-O          Go to [count] Older cursor position in jump list
                (not a motion command).  {not in Vi}
                {not available without the |+jumplist| feature}

When you do a ex command, you can go back to the previous position with C-o. In my mind it does make sens to go to the last change resulting of the ex command, so that you can see if the change (i.e. in a substitution) had the desired effect.

If you do want to have a transparent call, you can use a custom command that take your ex command as an argument and restore the window automatically:

function! KeepEx(arg)
  let l:winview = winsaveview()
  execute a:arg
  call winrestview(l:winview)
endfunction

command! -nargs=+ -completion=command K :call KeepEx("<args>")

You can use it like so:

:K %s/a/b/g

The winsaveview will fetch every info you need for restoring the view, so you get back to your previous state.

Note: if you delete line above your cursor it might be possible that you cannot restore fully your window, but that's an edge case.

  • 1
    c-o will take you back to the last cursor position, not the last screen state – Toothrot Apr 7 '16 at 9:05
  • you are right, let me update my answer (if I find out how ;) ) – nobe4 Apr 7 '16 at 9:06
  • answer updated. – nobe4 Apr 7 '16 at 9:15
  • 1
    If there are few ex commands that are used frequently, then it might be easier to create aliases for them, e.g.: :%S/a/b/g, :G/a/d, :V/a/d. – mMontu Apr 7 '16 at 19:38
  • 1
    It might be worthwile to add completion to the comand, like command! -nargs=+ -completion=command K :call KeepEx("<args>") – Ingo Apr 12 '16 at 15:19
0

If I understand the question correctly, I think I found a pretty good solution. You could use these to mappings to achieve the desired result:

noremap  <space>: m`:
cnoremap <c-j> <cr>``

Or if you want to simply replace the normal functionality:

noremap  : m`:
cnoremap <cr> <cr>``

These mapping will allow you to do something like :%s/ / / for an entire file without moving the screen or cursor at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.