Put cursor at the end of selected block after some operation - vim

Couple of examples that I encounter quite often.
Indenting some code
E.g. I want to put code block inside if statement:
puts("hello");
puts("world");
I enter if (pid > 0) { before the first line, then press Esc,j,Shift+v,j,>:
if (pid > 0) {
puts("hello");
puts("world");
Now cursor is at the beginnig of the first puts and to enter closing bracket I need one extra j to go to the end of the indented block.
Pasting block and adding to end of it
Almost the same example. When extracting some code to function, after pasting it with p I need to append return statement or closing bracket at the end. If I'm lucky there will be empty line after pasted block and I can use } to jump right there, but it's not always the case.
Question
So the question is how to jump to the end of the selected block after some operation performed on it (pasting, indenting, etc)?

`]
Will move you to the end of yanked or previously changed text.
See
:h `]

As an alternative behaviour, you could insert the closing } first and then indent the code inside the new scope automatically.
Being at the last line of the new scope in normal mode:
o}ESCv%=

Related

Vim: Moving cursor to the end of a block

Given that I am in the middle of a code block, I want to go to the end of the block without using h,j,k,l.
I am looking for similar behaviour with %, which will also work when my cursor is somewhere in the code block.
Example:
I want to move the cursor to where to the line 22, where Container block ends.
I would appreciate for your help, thanks.
Take a look at the following commands:
]) -> Move the cursor to the closed closing of first bracket '('
]} -> Move the cursor to the closed closing of second bracket '{'
As you are looking for the nearest first bracket, the first one should work for your case.

Wrapping a code block around code in VIM

Is it possible to wrap a code block around a piece of code in VIM? For example, if I want to wrap a while loop around the following, how can I do it without having to scroll to the bottom of the code to add the closing brace:
if(z > y)
{
switch(x)
{
case 1:
addPoint();
break;
case 2:
addValue();
break;
}
}
This is what the code will look like afterwards:
while (a > 10)
{
if(z > y)
{
switch(x)
{
case 1:
addPoint();
break;
case 2:
addValue();
break;
}
}
}
Vim does not have a built in surrounding system. I suggust you look at Tim Pope's excellent surround plugin. Then assuming you are positioned on the if you can do this:
Vj%SBIwhile (a > 10)
The Vj% selects the block + the conditional.
SB surrounds the selected text with a {,} (read surround with block)
Insert your loop text at the beginning of the newly inserted block.
You don't need surround to do this. You can do it with plain vanilla vim.
Vj%>`]o}<esc>g;g;Owhile (a > 10)<cr>{<esc>
However I prefer to use surround as it is a very handy plugin to have.
For more help see:
:h %
:h g;
:h `]
You can use the vim plugin surround.vim. It lets you wrap lines or fragments in blocks (and change the wrapping pairs).
Check something like Snipmate, it's possible they have an ability of surrounding Visually selected code with a snippit.
http://www.vim.org/scripts/script.php?script_id=2540
snipMate-visual-selection-support There is a special placeholder called {VISUAL}. If you visually select text, then press Vim
switches to insert mode. The next snippet you'll expand will replace
{VISUAL} by the text which was selected previously
You can make a mapping to do this in vanilla Vim e.g.:
:imap <S-F2> <Esc>j>>j>%%o<C-D>}
Use the mapped key after typing the opening brace for the surrounding code. Goes without saying that you should change <S-F2> to a keymap you like.
Breakdown of the key sequence:
Esc: go to Normal mode
j>>: move cursor to next line (in your example the if line) and indent it.
j>%: move cursor to the line with opening brace of if, indent from there to matching brace (the cursor will jump back to the opening brace)
% goes to the closing brace of if
o add a new line after the closing brace, and enter Insert mode.
CTRL+D: unindent (to undo the effect of smartindent)
} add the closing brace for the surround code (in your example, while)
Of course the plugins recommended by others have many more features so you should look at those as well.

How to delete a paragraph as quickly as possible

I want to delete the following codes in my config file:
server {
listen 80;
server_name xxx;
location / {
try_files xx;
}
}
I know I can use 7dd, but this is not handy enough- if the section is too long, counting the rows would be inconvenient.
Is there a better way to do this?
Sometimes, I have to delete a whole function, any ideas for that?
As in common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines within the block.
If your cursor is on the server line, try d}. It will delete everything to the next block.
Within the entry itself, dap will delete the 'paragraph'.
You can delete a curly brack 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.
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.
Note that much of this answer is taken from previous answer I gave on a similar topic.
If there is a blank line immediately after these lines, Vim will identify it as a paragraph, so you can simply use d} to delete it (assuming the cursor is on the first line).
Try using visual mode with %.
For example, say your cursor is at the beginning of the "server" line.
Press v to go into visual mode. Press % to highlight to the end of the block. Press d to delete it.
As David said their are many ways. Here are a few that I like:
Vf{%d This assumes you are on the line w/ server and you do a visual line selection, find the { and then find the matching } via the % command.
set relativenumber or set rnu for short. This turns on line numbering relative to your cursor. So you do not have to count the lines just look and 7dd away to deleting your block.
Use VaB to visually select a block i.e. { to }, line-wise. While still in visual mode continue doing aB until the proper block is selected then execute d. This means you can select a block from inside the block instead of at the start or end.
d} will delete a paragraph. This works in your current scenario because there is no blank line inside the block. If there is one then all bets are off. Although you can continue pressing . until the block is properly deleted.
If inside a block you can jump to the current block via [{ then continue executing [{ until you are at the correct block then V%d or d%dd to delete the block
Using the techniques above you can delete a function as well, but you can also use the [M and friends ([m, ]m, ]M) to jump to the start and endings of methods but they commonly work for functions as well.
For more information
:h %
:h 'rnu'
:h aB
:h }
:h .
:h [{
:h [m
Given matching parens, or braces, you can use % with d to delete, spanning lines.
So, assuming that you're on the server { line, you can do d%. This is generally useful for all code blocks, e.g. function blocks, loop blocks, try blocks.
Similarly, dip works, but d} is shorter. However, both will only delete to the next empty line.

Is there an easy built-in way to delete the first and last line of a block in vim?

Quite a common task in programming is to remove the condition on the current block.
In vim, is there an easy way to delete the first line (the 'if' statement) and last line (the closing curly brace) of the current block and perhaps reindent accordingly. If there is no simple key combination for this built in, what is a straightforward way to script it?
Thinking about this a bit further, of course the condition on the if statement may span multiple lines so presumably a script is required to capture this completely. However, for my code just deleting the first and last lines would capture 95% of cases.
Possible solution
yiBvaBVpgv<
yiB yanks the inner block
vaBV viaually select a block, then select it linewise
p paste over visually selected text
gv< reselect text and de-indent
Surround like mappings aka delete surrounding block:
nnoremap dsB yiBvaBVpgv<
ib provided a shorter solution. This solution will not mutate the visual marks: '<, '>
diB]pkdk
diB deletes the current inner block
]p paste the newly deleted text below the end of the block but adjust the indent.
kdk move up a line and then delete 2 lines up thereby deleting the start and end of the block.
How about something like di{ dk k "2p? Or a little more elegant, <i{ di{ dk k "2p. Note that you have to be inside the block for this to work — if you're on the opening or closing lines of the block, you'll affect the surrounding block instead.
command! -range=% Delete1$ <line1>delete _|<line2>delete _

Vim: replacing text within function body

I have some very useful plugins to find and replace text through files (see EasyGrep vim script - it's very helpful for programmers). I can even replace text only in the current buffer - by using plugins or :%s .... But what if I just want replace text within the current function body?
Consider the following example:
void f0()
{
int foo = 0;
// ...
}
// 99 other functions that uses foo as local variable.
void f100()
{
int foo = 0; // I want to replace foo with bar only in this function
// 1000 lines of code that uses foo goes below
// ...
}
Of course, I can use :%s ... with c flag for confirmation, but I believe there is a faster way to do this.
Thanks.
You can apply a substitution to the whole file using % or on a selection.
To create a selection :
Go in Visual mode Linewise for example, with Shift+v, select a few line and then type :.
Your prompt will look like :
:'<,'> it means : current selection
Type then s/foo/bar/g and it will replace foo by bar in the current selected line.
The better way to select a function content is to go inside a function with your cursor and type :
vi} it will select everything between { and }.
See :help text-objects for more tips on selection.
You could mark the function with V. Then when you type a command in :, it'll automatically be prefixed by and only be executed in the marked area.
There's probably a command for jumping to beginning of function and end of function, so you could do begin-function, V, end-function, substitute very quickly. Don't know those commands though.
I've always used [[ to jump to the beginning of the function, then use % to jump to the end of the function. I used mt and mb to mark the top and bottom of the function, respectively. Then to search and replace within the marked top and bottom, :'t,'bs/pattern/newpattern/g. This has always worked for me. I'm sure you can create a macro for this.
The visual select (vi}) is much easier and faster. It is aware of the cursor position. So, if the cursor is inside a fucntion sub block, then vi} selects all lines in that block. If you want to select the entire function, one needs to place the cursor outside of the sub blocks then do vi}. This is great for function blocks that fits in the current window. For functions that spans beyond the current window, the selection is lost once scroll up.
I really like the visual select of the vi} because it's so much easier and faster, but I have to resort the old school method on occasion.

Resources