8

Say you have code on lines 4, 5, 6. Then you want to move this block of code to starting point line 9 while also deleting lines 4, 5, 6.

What's the fastest way, i.e. least amount of key strokes, to achieve this? Would a custom function be better suited?

c-o-d
  • 910
  • 9
  • 19

4 Answers4

8

If the distance not big you can use move-text:

enter image description here

In terms of key strokes, for me it is:

  1. Select region:

    C-SPCC-nC-nC-n

  2. Move region:

    H-S-nH-S-nH-S-n

(move-text-down is binded to H-S-n)

welldan97
  • 516
  • 5
  • 9
  • You can also provide a numeric argument `n` to `move-text-down` and `move-text-up`. This shortens step (2) to `M-3` `H-S-n`. – itsjeyd Oct 19 '14 at 17:56
6

Starting at the beginning of line 4 (ESC 4 ESC g g or M-4 M-g M-g to go there), C-3 C-k C-2 C-n C-y (or ESC 3 C-k down down C-y if you don't like holding modifiers down) will do this.

If you don't want to do the arithmetic in your head, but instead select lines visually, then

  • Move to the beginning of the zone to move
  • C-SPC to set the mark
  • Move down to the beginning of the first line to keep
  • C-w to cut
  • Move down to the place where you want to insert the cut text
  • C-y to paste

I don't think there's any way to make this shorter unless you're willing to lose some flexibility (for example, if you often want to move a block of exactly three lines). You need to provide three locations: the beginning of the block to move, the end of the block to move, and the destination. In the sequences above, there is a single keystroke at each location, which is as low as it gets.

3

You could use expand-region to mark the block, if it is a semantic unit, like a function (The package's website explains this in more detail). Then moving it around as the other response explains. Depending on where you are in the block, a single keystroke can mark the whole thing.

rlazo
  • 983
  • 8
  • 13
  • Can you expand on this? What do you mean a real block? Like a function block? – c-o-d Sep 23 '14 at 21:13
  • Yes, the term used in the package is "semantic units" which can be word, line, code block, function, class, whole file. I've edited the answer to include a link to the package that explains this better. – rlazo Sep 23 '14 at 21:16
2

If you're using evil-mode, you can alternatively use an ex command: :4,6m9 (which moves lines 4 to 6 to line 9).

shosti
  • 5,048
  • 26
  • 33
  • I don't get the point of mentioning an exotic feature like vi emulation when it has nothing to do with the question. – Gilles 'SO- stop being evil' Sep 23 '14 at 22:03
  • 2
    Gilles: `evil-mode` isn't exactly obscure--it has almost 18,000 downloads on melpa. Another answer used `expand-region`, which is also an external package. For a Q&A site, it's probably good to include multiple ways to accomplish the same thing with different packages (although it might be good to come up with some guidelines). – shosti Sep 23 '14 at 22:11