Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to copy text within parentheses in Vim?

Tags:

linux

vim

vi

unix

I want to copy the parameters foo(bar).baz in the following code:

function(foo(bar).baz)

First attempt: Cursor on one of the parentheses, then y%. This gives me the parameters plus a bit extra:

(foo(bar).baz)

Second attempt: Cursor on opening parenthesis. Set a mark ma, jump to end with % then y`a to copy back to the mark. This gives me:

(foo(bar).baz

Setting a mark at the end and going the other way gives me exactly the same. Setting a mark on the f, then typing mah%y`a does give me the foo(bar).baz that I want, but maybe there's something more concise. Is there?

like image 956
YXD Avatar asked May 05 '11 10:05

YXD


People also ask

How do I copy text and paste outside in Vim?

In this mode, you can run Vim commands and navigate through the file. To go back to normal mode from any other mode, just press the Esc key. Vim has its own terminology for copying, cutting, and pasting. Copy is called yank ( y ), cut is called delete ( d ), and paste is called put ( p ).

How do I add a bracket in Vim?

lh-brackets simply binds ( to surround the selection with the brackets. Unlike surround it doesn't follow the vim usual keybinding philosophy as does. Instead less keys are required.


2 Answers

Use text objects:

yi( (or ya( if you want to include the parenthesis).

You can also use " to work inside quotes, etc. See the link for details, or type :help text-objects in Vim.

like image 111
hammar Avatar answered Oct 23 '22 20:10

hammar


A slightly shorter alternative to yi( is yib. Similarly yiB is equivalent to yi{ - yanks the contents inside braces.

Personally I usually do vib (visual select the text inside braces) first to make sure that the expected text is selected, followed by a y.

For more text object goodness, see :help text-objects.

like image 32
Walter Avatar answered Oct 23 '22 22:10

Walter