Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim object-select with syntax-aware text-objects

I just learned about the truly awesome object-select capabilities of vim. With the cursor within some "text object", a set of simple verbs can select or operate on the whole object. For example, with the cursor anywhere inside the quotes below (e.g. over the 'o'):

print "Hello, world"
           ^

The command vi" will select the whole phrase inside the quotes. The same capability works with a number of "text objects" that vim defines, including words, sentences, paragraphs, and characters enclosed by quotes, parentheses, and braces.

But now I want this notion of a "text object" to be aware of the language I'm writing. For example, consider the following python:

re.sub("[^A-Z ]", " ", string)

I'd like to be able to place the cursor somewhere over that, and to select the whole thing. The function call is a well-defined syntactic construct, but it isn't a "word", "sentence", "paragraph", or enclosed in quotes or braces.

Are there any plugins or vimrc hacks out there that define these sorts of language-dependent "text objects"?

like image 841
user85461 Avatar asked Jul 07 '10 15:07

user85461


2 Answers

This script uses indentation to define a text-object. It'll work for many languages if you're formatting according to common standards, and guaranteed for python.

like image 51
Dav Clark Avatar answered Oct 19 '22 23:10

Dav Clark


Although it's is possible to construct maps that will select an entire syntax region, that wouldn't work with your given scenario since there isn't a "function call" syntax region.

One option is to select the parenthetical expression and then extend that backwards to include the function call.

va)oB
  • va) selects the parenthetical expression
  • o toggles which end of the visual selection the cursor is at and which direction you're expanding.
  • B moves the cursor backwards one WORD. That is, to the character just after the whitespace previous to the cursor.
like image 29
jamessan Avatar answered Oct 20 '22 00:10

jamessan