I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.
For example, if I have a function like this:
void helloworlds( int num ) { int n; for ( n = 0; n < num; ++n ) { printf( "Hello World!\n" ); } }
How would I be able to delete the whole definition including the function name?
As is common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines.
If your cursor is on the line with the function name, try d}. It will delete everything to the next block (i.e. your function body).
Within the function body itself, dap will delete the 'paragraph'.
You can delete a curly brace block with da}. (If you like this syntax, I recommend Tim Pope's fantastic surround.vim, which adds more features with a similar feel).
You could also try using regular expressions to delete until the next far left-indented closing curly brace: d/^}Enter
]] and [[ move to the next/previous first-column curly brace (equivalent to using /
and ?
with that regex I mentioned above. Combine with the d motion, and you acheive the same effect. In addons like Python-mode, these operators are redefined to mean exactly what you're looking for: move from function to function.
If you're on the header/name, or the line before the block, da} should do the trick.
If you're below a block, you can also make use of the handy 'offset' feature of a Vim search. d?^{?-1 will delete backwards to one line before the first occurrence of a first-column opening curly brace. This command's a bit tricky to type. Maybe you could make a <leader>
shortcut out of it.
I don't do much C programming in Vim, but there are surely plugins to help with such a thing. Try Vim Scripts or their mirror at GitHub.
To delete an entire function, including its definition, such as:
function tick() { // ... }
f{
should do it, or simply $
.V%d
(Visual line, move to matching pair, delete)If your functions look like this:
function tick() { // ... }
J
(join the current line with line bellow. This also puts your cursor at the last character on the resulting line, {
, just the one we need for the next command.)V%d
(Visual line, move to matching pair, delete.)or
V[Down]%d
(Visual line, move one line down, move to matching pair, delete.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With