Tuesday, February 15, 2011

Vim Usage: Copy and paste multiple lines across different files

If you use vim, it is better to avoid using mouse. (I think that's good and convenience if you can control your vim without leaving your hand out of keyboard. In fact, I think it is the most important reason to use vim.) However, you may need to copy multiple lines in one document and paste them into same document or other files. Probably, you can use mouse and highlight multiple lines,  then edit->copy. I think this is ok for vim newbie and definitely this will take some times for hand switching from keyboard and mouse. Here is a better way, at least I use this one. (If you have better command, please feel free to give a comment :-) )


I will use "m" to help me. "m" is used for making a marker. You can use it in your text file. Then, you can jump to any line. In command mode, you press "m + [any letter (a-z)]". It will make a marker with the letter you choose. For example, you can move to line 10 and type "ma" (I usually use a as my marker). Then you make a marker on line 10. Once, you move to other place within the file. You can type "'a" to go back your marker a (line 10 in our example). Thus, it helps you to have better navigation experience in vim.


But, how can I make use of marker to copy and paste multiple lines? Remember, when you need to copy something in vim, you have to use yank "y". You can go to any lines other than line 10, then press "y'a", which means you copy from current location to marker a (line 10). You then can you paste command "p" to paste the thing you just copied.


Then, our next step is to pasting the copied content to other files rather than current file. To edit other file, you can use ":ex [filename]". Then you should be editing other file right now, you can press "p" to paste. Nice!


Summary:
  • "m + [a - z]" - create a marker with the letter [a - z]
  • "'m +[a - z]" - go to marker [a - z]
  • "y'[a - z]" - yank from current line to marker [a - z]
  • ":ex [filename]" - edit other file

No comments:

Post a Comment