22

I can use vi{ and va{ to select C++ code blocks. It helps me a lot when I need to yank/delete them.

But Python uses indentation to indicate code blocks. I cannot find any better way. Any ideas?

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
kev
  • 155,172
  • 47
  • 273
  • 272
  • possible duplicate of [Mark block based on indentation level in Vim](http://stackoverflow.com/questions/7377771/mark-block-based-on-indentation-level-in-vim) – Chris Johnsen Jan 01 '12 at 03:06

4 Answers4

31

I have not had much of an occasion to use it yet, but Michael Smith’s vim-indent-object sounds like it may be close to what you want.

Example usage (line numbers shown as with set number active):

  1 This is
  2   some text
  3     with multiple
  4   levels of
  5   indentation.
  6 There is also
  7     another stanza.

With the cursor on the line 2, 4 or 5, type Vii to select lines 2 through 5.
With the cursor on line 3, type Vai to select lines 2 through 3.
With the cursor on line 3, type Vaiii (or Viiii), to select lines 2 through 5 (in visual mode multiple uses of indentation objects extend the selection to the next level up/out).

The text objects it defines are:

  • ai: the current indentation level plus the line above
    useful when you want to grab the introductory line (e.g. grab the if and its “then” block)
  • ii: the current indentation level
  • aI: the current indentation level plus the one line above and one line below
    useful for languages that use “end” statements: if/endif).
  • iI: the current indentation level (effectively, ii, and iI are the same)

The objects can also be used with other commands that expect text objects (i.e. cii to delete the current indentation level and start inserting its replacement).

Chris Johnsen
  • 214,407
  • 26
  • 209
  • 186
7

I simply hit v for visual mode then ( or ). This will take you to the next blank line. That should correspond to your code blocks if you are formatting nicely.

Pete
  • 16,534
  • 9
  • 40
  • 54
3

For python, usually I use "zM" to fold the whole file, and then "2yy" to yank the whole function.

If your function is inside some class, you can use "zc" instead of "zM"

You need add following line to ~/.vimrc to make zM/zc work:

autocmd FileType python set foldmethod=indent
Sting Jia
  • 145
  • 1
  • 8
1

You can show lines (:set nu) and then go to the line where the code block begins (:lineNumber) and yank them.

Wilmer
  • 1,025
  • 5
  • 9