Vim: match next/previous line in search pattern - vim

I'm trying to practice my search patterns for ex commands and trying to do stuff I would usually do with macros using them, and I got stuck with one I'm not sure is possible.
I have some code that looks like this:
public myFunc (): any {
return {};
}
And I'm trying to yank it with this command (with the cursor after the function):
:?\vpublic\s*\w+\s*\(.*\)\s*:\s*\w+\s*\{?;/}$/y
This works as expected and matches the function that I mentioned up there.
What I would like to do but haven't found a way is to ignore the first line and the last one (I just want the contents of the function). I suspect it is possible to do it somehow (maybe +/- search offsets?), but I haven't had any luck yet.
Does anyone know how to do this? Thanks!

Yes, this is a simple matter of adding the appropriate offsets (:help search-offset). You basically define a range with two searches (one upwards from the current position, one downwards from there): ?...?;/.../. To exclude the targets, you just add / subtract 1; this is done by appending the offset to the search: ?...?+1;/.../-1. Applied to your example:
:?\vpublic\s*\w+\s*\(.*\)\s*:\s*\w+\s*\{?+1;/}$/-1y

To insert carriage return (Enter) like below use Ctrl-v Enter
:normal ?public^Mjwyiw
Explanation
:normal ............ in normal mode
?public ............. search backward for public
^M .................. Enter
j ................... move to the line below
yiw ................. yank inner word

Related

Move to the next row which has non-white space character in the same column in VIM?

As source code is usually indented, it will help navigate source code quickly if I can move to the next/previous row which has non-empty white character in the same column. Using below code snippet as example and the cursor in on the last }, is there a way to navigate the cursor to i which starts if?
if (condition) {
// some code
}
To search for the same screen column, you can use the special /\%v atom; the current column can be queried with virtcol('.'). Assert a non-whitespace (\S) at that position, and trigger a backwards search() for it:
:call search('\%' . virtcol('.') . 'v\S', 'bW')
You can easily turn this into a normal-mode mapping.
I've now implemented this motion in my JumpToVerticalOccurrence plugin; by default mapped to ]| / [|. There are other, related mappings like a ]V{char} mapping that works just like f, but vertically.
So if you don't mind installing a plugin (plus dependencies), this is more robust and functional (it supports [count] as well).
Not exactly what you're asking for, but if you start at } and hit %, the cursor moves to the matching {.
If your code has a defined indentation system, jeetsukumaran/vim-indentwise works well for relative, absolute, or block-scope movements across indented blocks.

Vim - Find pattern on currently line ONLY

I'm wondering if there is a way to find a pattern, but restrict it to the current line. Basically, the equivalent of /PATTERN but restricted to the current line, rather than the entire document.
I've tried :s/PATTERN, but that deletes the pattern from the line and places my cursor at the beginning of the line, which is not at all what I need. I was hoping you could search without replacing...
I'm hoping to use this for a macro in order to place my cursor at the start of that pattern, as would happen when you do /PATTERN on the entire file, so anything that is macro-friendly is even better.
Any vim users out there that might have an idea?
EDIT: 0/PATTERN in a macro would work for my current need, but I'm hoping there's a more specific way to restrict the search.
ANSWER: There's a few ways posted in here so far, but the one I like best right now is using Shift+V to select the current line visually, followed by /\%V to search only in the visual selection. Then Shift+V again will turn off the visual mode.
My knowledge about macro is limited, but interactively, you can select current line with Shift + V, and then do /\%Vsearch (see http://vimdoc.sourceforge.net/htmldoc/pattern.html#/\%V).
try to Find first character of the Pattern by typing
f <letter>
It's not exactly what you need but can help to solve the problem.
/\%9lsearch
Where \%9 means line number 9.
Typing in the line number is still a bit lame. You can ctrl+r= followed by a vim expression and enter to evaluate the vim expression and insert its output. line('.') will return the line of the cursor.
In one complete step
/\%<c-r>=line('.')<cr>lsearch
For more help see:
:h /\%l
:h i_CTRL-R
Place the cursor on the line you want to search in
Select it with shift+v
Type / to begin searching
Prefix your term with \%V, e.g. \%Vabc to search for abc in only the visually selected blocks (in our case the single line)
You can search without replacing by using
:s/PATTERN//gc
Then press n to skip the replacement. If the pattern is not found, you won't even be asked.
You could also just highlight the current line or the range of lines.

Vim: Yank distant line without moving

Suppose I have the following (* = cursor):
...
*
Kittens
Puppies
Humans
...
How do I yank the "Humans" (cursor relative 3rd line) while leaving the cursor in place?
Preferably in one motion or one (generic) command.
Try this:
:+3y
It uses the range +3 , that it is the point where it will begin to yank. and by default it does one line.
UPDATE: If you wanted to copy both the second and third line without moving cursor, you would use same command but with a range of two points, like:
:+2,+3y
It would copy both Puppies and Humans.
Now, for those who are wondering, based on Birei's answer, you can also do :ny, where n is the line number you want to yank. This is actually what I was looking for when I came to this page, and is helpful if you've got set number on and don't want to count relative lines.
Now, I wonder, how to perform this yank to a particular register! :D
My LineJuggler plugin combines yanks and puts into various short mappings; e.g. with 3[f you can fetch a line 3 lines below the current line and put it below the current line.

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.

Vim copy and paste

My previous question seems to be a bit ambiguous, I will rephrase it:
I have a file like this:
copythis abc
replacethis1 xyz
qwerty replacethis2
hasfshd replacethis3 fslfs
And so on...
NOTE: replacethis1, replacethis2, replacethis3, ... could be any words
How do I replace "replacethis1","replacethis2","replacethis3",.. word by "copythis" word by using minimum vim commands.
One way I can do is by these steps:
delete "replacethis1","replacethis2","replacethis3",.. by using 'dw'
copy "copythis" using 'yw'
move cursor to where "replacethis1" was and do 'p'; move cursor to where "replacethis2" was and do 'p' and so on...
Is there a better way to do this in VIM (using less number of vim commands)?
Since you changed your question, I'd do it this way:
Move to the first "replacethis1" and type cw (change word), then type "copythis" manually.
Move to the next "replacethis", hit . (repeat last operation)
Move to the next "replacethis", hit .,
and so on, and so on.
If "copythis" is a small word, I think this is the best solution.
The digit needs to be included, and there could be more than one instance per line:
:%s/replacethis\d/copythis/g
Given that "replacethis[1-3]" can be arbitrary unrelated words, the quickest/simplest way to do this globally would be:
:%s/replacethis1\|replacethis2\|replacethis3/copythis/g
(Note that you need to use \| to get the pipes to function as "or". Otherwise, vim will look for the literal | character.)
I've been struggling with this for a long time too, I think I just worked out the cleanest way:
Use whichever command is cleanest to put copythis into register r:
/copythis
"rye
Then go to the replacement and replace it with the contents of r:
/replacethis
cw<CTRL-R>r<ESC>
Then you can just n.n.n.n.n.n.n. for the rest of them, or if they're wildly different just go to the beginning of each and hit .
The key is replacing and pasting in one step so you can use . later.
:%s/copythis/replacethis/g
To replace all occurrences of copythis with replacethis. Or you can specify a range of line numbers like:
:8,10 s/copythis/replacethis/g
Note, the /g on the end will tell it to replace all occurrences. If you leave that off it will just do the first one.
create this mapping:
:map z cwcopythis^[
( ^[ is the escape character, you can type it in vim using Ctrl+V Ctrl+[ )
go to each word you want to replace and press z
if u need to do essentially the same action multiple times - swap 1st word of one line with second word of the next line, I say you could record a macro and call it whenever you need to
Have you tried string replacement?
%s/replacethis/copythis
A host of other parameters are possible to fine-tune the replacement. Dive into the Vim help for more details. Some more examples here.
You can remap e.g. the m key in normal mode to delete the word under the cursor and paste the buffer: :nnoremap m "_diwP.
Then you can just copy the desired word, move the cursor anywhere onto the to-be-replaced word and type m.
EDIT: Mapping to m is a bad idea since it is used to mark locations. But you can use e.g. ; anyway.

Resources