Koobz
Koobz

Reputation: 6938

Vim Visual Select around Variables

I'm wondering if there's a way to select variables intelligently in the same way that one can select blocks using commands like va}. There's some language-specific parsing going on to differentiate php and ruby, for example. For future reference, It'd be nice to tap into that - ideally selecting around various syntactic elements.

For example. I'd like to select around $array['testing'] in the following line of php:

$array['testing'] = 'whatever'

Or, lets say I want to select the block parameter list |item, index| here:

hash.each_with_index { |item, index| print item }

EDIT:

Specific regexps might address the various questions individually, but I have a sense that there ought to be a way to leverage syntactic analysis to get something far more robust here.

Upvotes: 4

Views: 835

Answers (2)

glts
glts

Reputation: 22694

You can define your own arbitrary text objects in Vim.

The simplest way to do custom text objects is defining a :vmap (or :xmap) for the Visual mode part and an :omap for the Operator-pending mode part. For example, the following mappings

xnoremap aC F:o,
onoremap aC :normal! F:v,<CR>

let you select a colon-enclosed bit of text. Try doing vaP or daP on the word "colon" below:

Some text :in-colon-text: more of the same.

See :h omap-info for another short example of :omap.


If you don't mind depending on a plugin, however, there is textobj-user. This is a general purpose framework for custom text objects written by Kana Natsuno. There are already some excellent text objects written for that framework like textobj-indent which I find indispensable.

Using this you can easily implement filetype-dependent text objects for variables. And make it available for everybody!

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172600

Though your given examples are quick to select with built-in Vim text objects (the first is just viW, for the second I would use F|v,), I acknowledge that Vim's syntax highlighting could be a good source for motions and text objects.

I've seen the first implementation of this idea in the SyntaxMotion plugin, and I've recently implemented a similar plugin: SameSyntaxMotion. The first defines motions for normal and visual mode, but no operator-pending and text objects. It does not skip over contained sub-syntax items and uses same color as the distinguishing property, whereas mine uses syntax (which can be more precise, but also more difficult to grasp), and has text objects (ay and iy), too.

Upvotes: 3

Related Questions