0

Consider a scenario, when you are editing a C file in vim. & you have used a mix of spaces & tabss. & you need to convert all of them to spaces.

There is a utility, called expand, which performs this task intelligently & it's a preferred way than s/\t/<4 spaces>/g. We can use this command in vim using :%!expand -t4. Typically, I map a function key, say F11 for this.

Similarly, we can use any other command in vim.

The problem is when you run any such operation on entire buffer, the cursor position changes & can be irritating at times.

Hence, the question is, how to perform an operation on entire buffer, without changing cursor position?

4

3 回答 3

2

The cursor position can be restored by using the latest jump mark:

``

If you also want to maintain the exact window view, use winsaveview() / winrestview().

The anwolib - Yet another vim library has a handy :KeepView command for that:

:KeepView %!expand -t4
于 2013-11-13T11:24:20.307 回答
1

For such a case, we can use marks (e.g. mA). The mapping would be:

:nmap <F11> mZ:%!expand -t4<CR>`Z

However, there is still a catch. The screen scroll position may change, when operating on entire buffer.
This can be handled by using 2 marks as below:

:nmap <F11> mZHmY:%!expand -t4<CR>'Yzt`Z

Explanation:

  1. Mark current position. (mZ)
  2. Go to top of screen. (H)
  3. Mark this line. (mY)
  4. Run your filter. (:%!expand -t4)
  5. Go to line Y. ('Y)
  6. Make it top of screen. (zt)
  7. Go to your mark. (`Z)

Now, when you press the mapped key, F11, the filter runs on the buffer & the cursor remains at its proper location.

于 2013-11-13T11:11:34.727 回答
0

you can just:

:your expand cmd|norm! ``

you can map it to <F11> if you like. but better use nnoremap

I just saw you mentioned in your question:

Similarly, we can use any other command in vim

If you want to do that, the reliable solution would be wrap the "any other command" in a function, and before/after the main logic, save/restore the cursor position. Because "any other command" could change the (back tick) mark, even the marks you defined.

于 2013-11-13T11:17:32.583 回答