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?
The di{
will delete everything inside the curly braces the cursor is in (mnemonic: Delete In {). It does not account for syntactic elements like a function name. Vim does, however, honor that some characters appear in pairs, e.g. { and }, ( and ), [ and ], ...
It will reverse-search to the previous opening brace and delete everything to the matching closing brace. It does roughly the same as ?{<CR>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:
f{di{
$di{
jdi{
d][
The list goes on ...
There are probably also plugins for whatever language you want to write.