当前位置: 动力学知识库 > 问答 > 编程问答 >

Vim keyboard shortcut: Deleting code without deleting the if statement

问题描述:

This is probably a basic vim questions to all those vim gurus out there.

If I want to delete a particular if statement and its closing bracket, but without deleting the code inside the expression, how can I achieve this through some keyboard shortcuts?

eg:

if (a == 2) {

// do not delete this part.

for (int i = 1; i < 10; i++) {

// code

}

}

The result will be:

// do not delete this part.

for (int i = 1; i < 10; i++) {

// code

}

Thanks for any help.

网友答案:

Move your cursor anywhere on the line with the if statement. Here is the sequence of commands (will be explained after)

$%dd''.

Explanation:

$ goes to the end of the line (cursor is now on {).

% goes to the matching curly brace (or parentheses etc...). Cursor is now on } of the if statement

dd deletes the line the cursor is on (} is now deleted)

'' goes to the line of the last jump. The last jump was when we used %. (cursor is back on if statement line)

. Repeats the last command (dd). This deletes the line (if statement line is now deleted)

Result:

    // do not delete this part.
    for (int i = 1; i < 10; i++) {
        // code 
    }

The indentation will be off so you can use gg=G (which correctly indents the file) to fix it.

If you do this alot you can make map it to a key in your .vimrc or you can make it into a macro

Making it into a mapping:

Example of a mapping in your .vimrc:

nnoremap <C-d> $%dd''.gg=G

Whenever you press control-d (you can choose any key, just replace <C-d>) Vim will run those commands, doing what I explained before followed by an entire file indentation this time. Make sure your cursor is on the if statement line when using this command otherwise there could be unintended results.

网友答案:

Alternatively to Zachs solution, you could use this:

di{Vk]p

Explanation:

You start inside the { } block, and with di{ you delete inside the { } block.

Then, you select the the if statement, which you want to remove, which now is two lines. Vk selects both, and you paste the block you just deleted over it with p. The ] makes the pasted block be correctly indented (thanks, Kache)

There could be a more elegant solution to the pasting part, buth this was the first one that came to mind.

The anvantage over Zachs answer is that you don't have to move the cursor to the line with the if, you just need to be inside it (although you may run into trouble with nested {} blocks, which there usually are). In addition, you don't need to fix indentation.

分享给朋友:
您可能感兴趣的文章:
随机阅读: