Thursday 10 May 2012

VIM - Folding

I forget what day of vimquest I’m currently on, but I’m going from strength to strength and I wanted to write up a quick post about what I’ve discovered about code folding.

:help fold-methods (fdm in vim shorthand) will bring up all of the help on folding methods in VIM and there are two options that I’ve explored. The first was automatic folding and this was achieved by setting the fold-method to indent …

Indent

 :set fdm=indent 

Because I’ve been folding python I found that this worked a little too well - everything was folded and often in more than fold. Whilst I found it acceptable when I first started using it, I found that I was spending more time unfolding code. It was getting in my way.

None

So I spent a few days working without folds and that’s when I realised that folds are essential in a speedy joy filled workflow. One of the problems that I addressed earlier on in vimquest was that I wanted to be faster at zooming around. Folding plays a part in being faster because when the unwanted code is folded, sometimes you don’t have to dart about in the source to double check what a far away line is doing.

This, is how I’ve came to like manual folding.

Manual

Once you wrap your head around a few commands manually folding code is easy. Notice how all commands start with z and the next letter actually matches the intention of the noun. I’m not the first person to spot the connection with nouns and modifiers in vim, but the more I dive into it the more I start making connections along these lines. I digress, here’s the commands that I’ve been using to work with folds. –

  • zf - fold
  • zc - collapse
  • zo - open
  • zd - delete

So far I’ve found two ways to create a fold. The first is to get into :visual mode and select a block of text and then zf. Once the fold is created you can open, close and delete at will.

The second method carries on from the idea of speaking vim with nouns and modifiers. Imagine that you’re working on some source code, and you’re currently on line 20 and you want to fold all the way through to line 47. You can create a fold by combining commands together –

 zf27j 

That line may look cryptic but it’s not when you see it for what it is. There are two parts to it –

  1. zf - This is the create fold command
  2. 27j - This means 27 lines down. “j” is down in vim movements.

So the above command is saying “fold 27 lines down”.

Onwards

So that’s where I’m at with folding and I’ll continue to work with it more as the days come. A nice side product of all of this is that I’m not just remembering and learning single commands, but I’m also learning to analyse the commands and combine them to “think vim” which is helping me scale Blooms Taxonomy