puk
puk

Reputation: 16752

How to use vim's mark functionality but keep the cursor where it is

Vim's mark functionality allows one to apply functions to every line between the current line and the marked line. For example if I mark the below line 3 with k

1 var a = 0;
2 while (a < 10){
3 a++;
4 console.log('Hello');
5 console.log('world');
6 █
7 }

and from the cursor position () issue the command >'k, I will get the following

1 var a = 0;
2 while (a < 10){
3 █  a++;
4    console.log('Hello');
5    console.log('world');
6
7 }

(Note: the cursos might be over the a, but that's not important)

This is the desired effect, but now the cursor has moved all the way back up. For most cases this is desirable, as I usually want to edit from the top. But in this case, I might want to indent again, so I have to navigate once again to the bottom. In cases where I am indenting 20+ lines this becomes a real chore.

How can I temporarily disable this seek back function?

Upvotes: 4

Views: 380

Answers (4)

sehe
sehe

Reputation: 392893

The most exact answer I can think of is simply:

:'k,.>

I.e., use a command-mode command with a range (:he :range, and other sections)

In fact, you'd be able to to do 'remote action stuff' that would resemble levitation illusions to non-vim-initiated programmers. Just try

:'k>

Indenting a marked line, from a distance!1

You'll find that most interesting edit commands have a command-mode version. E.g.

:'ky|put

Yanking the marked line, put it after current cursor line.

If the command-mode command isn't there, there is always :normal. E.g. you can

:'k,.norm ,cc

using NerdCommenter to comment the block instead of indenting


Now, for fun:

:'k,.>|'k,.retab|'k,.y+|u

To take that same block, indent it, retabulate it, put it on the Windows/X clipboard and undo the edit (this is about perfect for pasting on StackOverflow). Note that in practice, I'd prefer to use a visual selection for that:

V'k:>|*retab|*y+|u

1 Fair warning: some 'destructive' commands (such as :delete, or some mappings from scripts, like :norm ,cc to comment a selection) actually do move the cursor

Upvotes: 1

Birei
Birei

Reputation: 36252

It depends of how many times you want to repeat that action.

  • If it was 2 or 3 times I would use:

    '' to come back to line 6.
    . to repeat your last command (indent those lines).

  • If it would be more times, I would use a macro qa to begin record, q to end record and <number>@a to repeat it.

Upvotes: 1

ams
ams

Reputation: 25559

After you do >'k just hit '' (single quote, single quote) - not back tick, I think - and you'll go back to where you were.

If you do this often then you can map a key to do it in one:

:map >> >'k''

Then whenever you hit >> it'll do that sequence.

Upvotes: 3

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20610

The simplest solution is to press `` (i.e. back-tick twice) after your command to jump back to the previous location.

Upvotes: 5

Related Questions