Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I've been using Vim for around 7 months now, I mainly code in javascript but occasionally bash or python. I've picked up lot of tricks for using it and often go off the "if i can;t do it, find out how" or "if i think something can be improved find out how". I find it very difficult to do large restructures of files, moving blocks of code from on place in a file to another. I've tried using :vsplitto make things slightly easier. But it still feels clunky. What is the best way, or a way to move relatively large blocks (10-30 lines) of code, around a file?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

The most basic way would be:

  1. cut the block you want to move, either directly (di{ for example) or after a visual selection (vipd for example).

  2. move to where you want that block to be and paste.

And I don't see anything "clunky" about it.

How do you do it right now and why is it clunky?

Anyway, behold the beauty of Ex commands:

:'<,'>m33    <-- move the currently selected text to after line 33
:50,62m19    <-- move lines 50 to 62 to after line 19
:-23,+15m13  <-- move 13th line above to 15th line below to after line 13
:'{,'}m'a    <-- move the current paragraph to after mark a
:?^foo?,'bm. <-- move 1st line matching ^foo upward to mark b to after the current line

Oh god… See :exusage, :help :move and :help range.

Note that Vim has ways to help you navigate around:

  • marks, ma to place mark a, 'a to jump to mark a, see :help mark-motions
  • the jumplist, <C-o> to jump back, <C-i> to jump forth, see :help jumplist
share|improve this answer
    
i was doing something more like V20jd move where I want and then paste, it just didn't seem right i'm not sure why.. i just tried the vip, what exactly does that do, blocks to the same indent? and what was the meaning of di{. Thanks for this answer it's clear and goes beyond what i asked so I appreciate it. I think i'll learn to use marks before Ex commands!! –  allouis Aug 27 '13 at 13:33
    
ip is the "paragraph" text-object, a "paragraph" is made of every line between two blank lines. i{ is another text-object for {} blocks. Read :help motion.txt, it will blow your mind. Direct action (d20j) is better than action after selection (v20jd) but it needs a bit of practice. –  romainl Aug 27 '13 at 13:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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