1

I have a file.c containing

#inlcude<stdio.h>

int main()
{
    printf("Hello world\n");
} 

I can copy the main function using :3,6y. But, when the function is big enough then in order to know in which line the function ends I need to scroll.

Is it possible to copy entire function using something like :copy main?

3

Yet another way is to use the % motion, after placing the cursor on the second line in your example (/main), I would use:

Vj%y
  • V: enable visual-line selection
  • j: go down to the opening curly brace
  • %: find the next matching item
  • y: copy the selected text

Visual selection may not even be needed, I just got this habit.

For more advanced operations, text-object are a good choice as suggested by Peter Rincker, or maybe a plugin like vim-refactor allowing you to extract functions and more.

| improve this answer | |
2

Here is one option:

:/int main(/;/^}/y

This searches for int main(, goes to that line, then searches forward to the ending brace (assumed to be in the first column), takes the two lines as a range, and yanks.

If you are already on the int main line you could simply use

:,/^}/y

or in normal mode, one of the following:

y/^}/e
yv/^}

Without either v (make inclusive) or /e (cursor to end of match) the ending brace will not be included.

| improve this answer | |
  • isn't :Copy main possible? – alhelal Mar 25 '18 at 17:54
  • your solution is not comfortable than using the range(e.g.:2,5y). – alhelal Mar 25 '18 at 17:57
  • @alhelal what do you mean with :Copy? There is no such command. But you can define it of course to do such things. – Christian Brabandt Mar 26 '18 at 7:05
  • @ChristianBrabandt it is a user defined command. It should be implemented. – alhelal Mar 26 '18 at 7:15
  • @alhelal That was not part of your initial questions. It would be straight forward to implement, perhaps you try first before you demand something from others? Or at least show what you have tried and mention where you have problems with? – Christian Brabandt Mar 26 '18 at 8:53
2

You can use [[ & ][ to help you find the start and end of your function. You can also use [m and ]m as well.

[mkV]my

A simply method text-object:

xnoremap aM :<c-u>normal [mv]m<cr>
onoremap aM :normal vaM<cr>

Note: these will probably need to be updated for you needs, but they are a good starting point.

Now you can use yaM or vaM to copy the method/function body.

For more help see:

:h ]]
:h ]m
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.