Removing only the function body using `di{` in Vim

I’ve recently started learning Vim and got stuck on its behavior regarding changing/deleting text objects, particularly code blocks surrounded by curly braces.

Here is an example of code:

function main() {
  console.log("Hello world");

If I move my cursor at the beginning of the word function and enter the following combination: di{ Vim will delete the function body, as expected.

However, if I move the function inside a class:

class Program {
    main() {
        console.log("Hello world");

and then move the cursor at the beginning of the word main and enter the same combination again Vim will delete the body of the class, not the function.

Could somebody explain to me how it works and if there is any workaround or what the experienced vim users do in such situations to achieve what I’m trying to do?

>Solution :

The di{ will delete everything inside the braces the cursor is in. It does not account for syntactic elements like a function name.

It will do roughly the same as ?{d% (try it out and see what happens).

In your example, you are on the function name and want to delete the respective function. Vim, however, only sees the braces here and does exactly what it’s told: delete in braces, i.e. the whole class.

Possible workarounds in this situation:

  • move to the next opening brace on the line, then delete: f{di{
  • move to the end of line (the opening brace), then delete: $di{
  • move cursor one line down (to be inside the braces), then delete: jdi{
  • delete everything to the next closing brace: d][

There are probably also plugins for whatever language you want to write.

Leave a Reply