Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark block based on indentation level in Vim

Is it possible to mark a block in Vim based on the indentation already in place? Similarly to v{ .

It would be extremely useful for programming languages with whitespace-sensitive syntax (like Haskell and Python).

For example mark everything between the first let and return in this function:

checkArg (com:arg) s d ns 
  | com == "add-source " = do
      let s' = v ++ s
      lift $ saveLinks s'
      return (s', d)
  | com == "remove-source" = do
      let s' = filter (not . hasWord str) s
      lift $ saveLinks s'
      return (s', d)

http://en.wikipedia.org/wiki/Off-side_rule

like image 386
Daniel O Avatar asked Sep 11 '11 11:09

Daniel O


2 Answers

I use the indent object plugin:

This plugin defines a new text object, based on indentation levels. This is very useful in languages such as Python, in which the syntax defines scope in terms of indentation. Using the objects defined in this plugin, an entire if structure can be quickly selected, for example.

With this, you can select, delete, change, etc. blocks using the standard Vim text object commands, using "i" and "a" to refer to the block that you are in: "vii", "dii", etc. It it language-agnostic, though is especially useful/relevant in whitespace-structured languages such as Python.

like image 157
Jeet Avatar answered Nov 11 '22 16:11

Jeet


The plugin Jeet linked to looks neat, but here's a simple alternative.

If you've set foldmethod=indent...

you can use a visual block selection.

So starting on line 3, just type V]z.

:help fold-commands

MOVING OVER FOLDS

[z

Move to the start of the current open fold. If already at the start, move to the start of the fold that contains it. If there is no containing fold, the command fails. When a count is used, repeats the command [count] times.

]z

Move to the end of the current open fold. If already at the end, move to the end of the fold that contains it. If there is no containing fold, the command fails. When a count is used, repeats the command [count] times.

zj

Move downwards to the start of the next fold. A closed fold is counted as one fold. When a count is used, repeats the command [count] times. This command can be used after an operator.

zk

Move upwards to the end of the previous fold. A closed fold is counted as one fold. When a count is used, repeats the command [count] times. This command can be used after an operator.

like image 38
Casey Jones Avatar answered Nov 11 '22 17:11

Casey Jones