In almost any text-editing use-case it can be necessary to extract portions of your current file into a separate file. The easiest way to do this in Vim is with w
. Here’s a workflow I recently used when extracting portions of a class to a new library:
shift-v
to visually select some lines:w path/to/new/file.rb<Enter>
to save those lines to a new filegv
to reselect the last visual selection
(Read that post if you haven’t already. It’s one of our most popular!)d
to delete that selection
Another variation on this is to use >> before your filename to append rather than overwrite.
:w >>path/to/new/file.rb<Enter>
appends the lines to the existing file
There’s a Gif where I demonstrate these in action below, check it out!
Ruby Developer?
If you’re a Ruby developer, or more specifically a Rails developer, then you should already be using tpope’s rails.vim. Built into to this essential plugin is an :Extract
command that will extract the highlighted lines to their own file. From a model, it will extract to a Concern. From a View, it will extract to a Partial. This extra command adds some niceties that the vanilla-Vim version above can’t offer, like removing the extracted code and leaving behind a reference to it.
As professional Ruby developers ourselves, we’ve developed years of experience honing Vim for Ruby work. So we’ve opened preorders for our Vim for Rubyists email course. 💸 Use promo code “preorder” for 25% off!
Git User?
Every Git user should check out Git Better with Vim, our 12 week email course. The course teaches tips, tricks, and expert workflows for using Git inside of Vim with emails that release every Tuesday and Friday. If you like our free Vim tips on Mondays and Thursdays, why not add 2 more Vim tips every week?
Preorders are now also open for our other most-requested course: Master Vim Note-Taking. 💸 Use promo code “preorder” for 25% off!
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote:
There's another common use case: extract a portion of a file to a buffer which is mapped back to that file. This is useful when one needs to diff two portion of a file, possibly during a merge conflict resolution. I use a small (unpublished) plugin for that, I wonder how other people are doing this?