May I know how do I highlight a code region say for example
public void foo()
{
blah();
blah1();
blah2();
}
where my cursor is at 'b' of first blah(), how can I highlight the whole code region using viEmu or VIM per se?
In Vim, that's va{ (or va}, or vaB as synonyms). The v enters visual mode, and a{ is a text object that selects a Block. If you don't want the curly braces included, use i{ (inner Block) instead. And if you want to operate (e.g. delete) on the block, you can skip visual mode and just use a command that takes a motion, e.g. da{.
Related
As a Neovim user, I am able to type di( (also di", di{ and so on) in order to delete the content delimited by matching brackets/quotes. For example, in a situation like the following
(cursor here)
/
void foo(int bar)
-
By running di( I would get
(cursor here)
/
void foo()
-
And by running da( I would get
(cursor here)
/
void foo
-
However, in vim this behaviour can be accomplished only by placing the cursor on the starting bracket/quote first. So di( works only if the cursor is positioned as follows
(cursor here)
/
void foo(int bar)
-
Because of that, in vim I have to run f(di( or F(di( according to where my cursor is on the line in order to move the cursor to the starting delimiter and, then, deleting the content. In neovim I can, instead, directly run di( obtaining the same result.
Is there any remap I can set in order to make vim behave like neovim does?
Vim used to treat nesting pairs (where the beginning and end are different) and non-nesting pairs (where the beginning and end are identical) differently but it all changed late in 8.2's lifecycle.
Your Neovim build includes the patch but your Vim build doesn't.
Update Vim to a version > 8.2.3255 and you will have the desired behavior.
I want to wrap some code :
myObj.text;
with a function call where the code is passed as an argument.
console.log(myObj.text);
I've thought about using surround.vim to do that but didn't manage to do it.
Any idea if it's possible ? I
With Surround in normal mode:
ysiwfconsole.log<CR>
With Surround in visual mode:
Sfconsole.log<CR>
Without Surround in normal mode:
ciwconsole.log(<C-r>")<Esc>
Without Surround in visual mode:
cconsole.log(<C-r>")<Esc>
But that's not very scalable. A mapping would certainly be more useful since you will almost certainly need to do it often:
xnoremap <key> cconsole.log(<C-r>")<Esc>
nnoremap <key> ciwconsole.log(<C-r>")<Esc>
which brings us back to Surround, which already does that—and more—very elegantly.
I know and use two different ways to accomplish this:
Variant 1:
Select the text you want to wrap in visual mode (hit v followed by whatever movements are appropriate).
Replace that text by hitting c, then type your function call console.log(). (The old text is not gone, it's just moved into a register, from where it will be promptly retrieved in step 3.) Hit <esc> while you are behind the closing parenthese, that should leave you on the ) character.
Paste the replaced text into the parentheses by hitting P (this inserts before the character you are currently on, so right between the ( and the )).
The entire sequence is v<movement>c<functionName>()<esc>P.
Variant 2:
Alternatively to leaving insert mode and pasting from normal mode, you can just as well paste directly from insertion mode by hitting <ctrl>R followed by ".
The entire sequence is v<movement>c<functionName>(<ctrl>R")<esc>.
You can use substitution instruction combined with visual mode
To change bar to foo(bar):
press v and select text you want (plus one more character) to surround with function call (^v$ will select whole text on current line including the newline character at the end)
type :s/\%V.*\%V/foo\(&\)/<CR>
Explanation:
s/a/b/g means 'substitute first match of a with b on current line'
\%V.*\%V matches visual selection without last character
& means 'matched text' (bar in this case)
foo\(&\) gives 'matched text surrounded with foo(...) '
<CR> means 'press enter'
Notes
For this to work you have to visually select also next character after bar (^v$ selects also the newline character at the end, so it's fine)
might be some problems with multiline selections, haven't checked it yet
when I press : in visual mode, it puts '<,'> in command line, but that doesn't interfere with rest of the command (it even prevents substitution, when selected text appears also somewhere earlier on current line) - :'<,'>s/... still works
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.
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.
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.