Vim - yank from current cursor position till beginning of line - vim

in VIM, I understand that we can do a yank till the end of line using y$ but if e.g. my text is abcdefg and my cursor is at 'g' and I enter y^ the line will be copy without the g. My idea is to copy the whole line without the line break, any similar action will do.

0y$$ - copy the line without line break and move cursor back to the end

Making it a visual selection and then yanking that includes the character under the cursor:
v0y

If all the characters are indeed together and conform to a "vim sentence", you could use visual selection for the sentence object. A sentence in this case would match abcdefg even if that is not starting at the beginning of a line and it will not include the line ending:
visy
If you want to include trailing whitespace you would use a instead of i (mnemonic for "inside"):
vasy
The only problem with this approach (which may be what you do not want) is that it will not include leading whitespace. So if you have something like:
abcdefg
The selection will not include the leading chunk of whitespace, just abcdefg.

Turns out yanking till end of line is a thing you'll find yourself doing quite often. As such, the following mapping is quite popular.
noremap Y y$
It's so popular, it's even listed under :h Y!
If you use this mapping, the answer to your question would be 0Y

0yg_
is another option.
But visual mode is better:
v0y
v^y

Related

Delete trailing whitespace, alternative to substitute command

To delete trailing whitespace on a line or across a file I can do:
:[range]s/\s\+$//
However, I was wondering for a single line in normal mode if there's an easier approach, for example if the line is:
Hi, I am a line |
And my cursor is past the e, is there a more generic command than doing dTe in normal mode? The next best I could find was dg_, but that goes one too far. And then, one more option might be gElD.
Generic way without :substitute
Use diw to delete multiple whitespace (including tabs) while the cursor is on one of the whitespaces (like in the example).
This works for any whitespace sequence: trailing, leading, etc.
Use dw to delete from the cursor to the end of the sequence. This is useful when you want to re-indent a line or fix alignment.
As this is independent of the first/last character of the previous/next word this is the most generic way.
Using a mapping with :substitute
Use nmap <leader>tr :%s/\s\+$// to remove all trailing whitespace in the whole buffer by pressing \tr (assuming the original mapleader)1.
Replace tr with what ever suits you best.
Omit the the % in the mapping to make it only work on the current line.
--
As a side note: Use set list listchars=trail:· to show trailing whitespace (replace · with any character you like).
--
1 Removing all whitespace may not be what you want, especially when using a version control system and the file contains whitespace not added by yourself.

Select entire line in VIM, without the new line character

Which is the shortest way to select an entire line without the new line character in VIM?
I know that SHIFT + v selects the entire line, but with new line character.
To do this I go to the line and I press:
^ (puts the cursor at the start of the line)
v (starts the visual select)
$ (selects the entire line including new line character)
Left (unselects the new line character)
I also know that I can create a recording that does such a thing. But I am asking if is there any built-in shortcuts...
Yes, g_ is what you are looking for. g_ is like $, but without the newline character at the end.
Use 0vg_ or ^vg_, depending if you want to copy from the beginning of the line, or the first character on the line, respectively.
No, there is nothing built-in that does the job. That's why people have even created plugins to address the need.
Probably the most popular choice is textobj-line. With textobj-line you get two new text objects, al "a line" and il "inner line". Then,
vil selects the printable contents of the line (like ^vg_),
val selects the entire line contents (like 0v$h).
Both do not include the newline in the selection.
Pretty handy plugin if you ask me. And it works with operators, too.
By request, the installation:
With plain Vim:
Get the latest textobj-user and extract its directories into ~/.vim.
Get the latest textobj-line and extract its directories into ~/.vim.
Generate the help tags :helptags ~/.vim/doc.
With a plugin manager (recommended): just follow the usual installation procedure for your plugin manager, and don't forget to install the textobj-user dependency as well.
0v$
^v$
0vg_
^vg_
$v0
$v^
g_v0
g_v^
all do the job with different conceptions of what a line is (from first column or from first printable character, to last character or to last printable character). You can create a custom mapping if you like.
Note that selecting text is often unnecessary in vim.
Adding on to the answer by #glts, you can replicate the functionality of the textobj-line plugin using only vanilla vim mappings, no plugin installation required.
To do so, add the following to your .vimrc
vnoremap al :<C-U>normal 0v$h<CR>
omap al :normal val<CR>
vnoremap il :<C-U>normal ^vg_<CR>
omap il :normal vil<CR>
The al text object (short for 'a line') includes all characters in a line, but not the terminating newline. This includes all white space.
The il text object (short for 'inside line') goes from the first non-blank character to the last non-blank character.
Commands such as yil,val, and cil work as expected.
If you want to copy line into the buffer, you can use Du, which will delete from the cursor position to the end of line with D, and then revert changes with u. Text will be copied to the buffer without new line symbol.
Redefine $ for visual mode
The unwanted selection of the linefeed in visual mode can be permanently eliminated by adding the following visual mapping to .vimrc:
vnoremap $ g_
This replaces the standard behaviour of $ in visual mode for the move towards right before the linefeed g_.
You can still a mapping to what you want, e.g.:
nnoremap <leader>v 0v$
Another solution $ will be working as you want it to
:vnoremap $ $h
maps your original $ command to new one
Not exactly an answer to your question, but I wonder if you can skip selecting the line and do directly what you want next:
If you want to change the line, just cc
If you want to yank the line, 0y$ (note $ here does not capture the line break because it does not move over it in normal mode, unlike in visual mode)

Yank first word from specific line

I figured out that :23y will yank the entire 23rd line.
But what I want to do is yank only the first word on line 23.
I tried :23yw, but that does not work. Is there an easy way to do this?
Can this be done without going to the line first and then yanking and then typing ` to go back to the line I was editing on?
23ggyw will do it. I don't think there's a quicker way.
Explanation: 23gg moves the cursor to line 23, yw yanks one word.
Note that this only works if you have the startofline option set (which is the default). Otherwise you need to explicitly move to to the first non-whitespace character: 23gg^yw.
The :y is an abbreviation of the :yank Ex command, that's why :yw does not work; it's a normal mode command. As the other answers have already shown, you can trigger those from the command line via :normal yw.
I'm afraid there's no way avoiding the jump in a practical way (but, as mentioned, <C-O> lets you jump back to the original position). You could use Vimscript:
:let #" = matchstr(getline(23), '^\w\+')
But that's hardly easier to type, and only suitable for a function.
I don't think there's a way to do that without moving the cursor.
Anyway, here is another way to do it:
:23norm! yw
Breakdown:
: because we are using an Ex command,
23 is the line on which we want to do something, it is a range of 1,
norm[al] executes a normal mode command on the given range,
yw yanks the first word.
Add <C-o> to go back to where you come from.
type 23Gyw in normal mode should do the job.
G Goto line [count], default last line, on the first
non-blank character |linewise|. If 'startofline' not
set, keep the same column.
G is a one of |jump-motions|.
Following would work without moving the cursor as requested but it's a hassle to type.
:23y|norm PJ0eld$
or you could try working out something with
:23t.|norm eld$
23jyw should be able to do it, it will take you to 23rd line and yank first word

How can I insert text in the middle of the line to multiple lines in Vim?

Say I have ten lines and I want to prepend text to some word that occurs in those lines? It does not have to be at the beginning of the line.
From:
sdfsd foo sdfsd
sfsd foo fsdf
sdfsdf foo sdfsdf
to:
sdfsd bar(foo sdfsd
sfsd bar(foo fsdf
sdfsdf bar(foo sdfsdf
Is it also possible to not only prepend the bar( but actually surround foo with bar(foo)?
I would also like a quick way to append // comments to multiple lines (C-style comments).
I use Vim/GVim 7.2.
Go to the first foo, press Ctrl-v to enter visual block mode and press down until all the lines with foo are marked. Then press Shift-i to insert at the beginning (of the block). When you are finished and press Esc, the inserted characters will be added to each line at the left of the marked block.
To insert at the end, press again Ctrl-v, move up/down to mark all affected lines and then press End or $ to extend the selection until the end of the lines. Now you can press Shift-a to append at the end of all the lines, just like previously with Shift-i.
The visual selection can also be done with normal movement commands. So to comment a whole block in C you could move to the opening brace and type Ctrl-v % Shift-i // Esc.
To answer your first question, the below
:%s/foo/bar(&)/g
will look for foo, and surround the matched pattern with bar(). The /g will do this multiple times in one line.
Since you're just matching foo, you could do a simple :s/foo/bar(foo)/g. The above will work, however, if you decide to match on a regular expression rather than a simple word (e.g. f[a-z][a-z]). The '&' in the above represents what you've matched.
To prefix a set of lines I use one of two different approaches:
One approach is the block select (mentioned by sth). In general, you can select a rectangular region with ctrl-V followed by cursor-movement. Once you've highlighted a rectangle, pressing shift-I will insert characters on the left side of the rectangle, or shift-A will append them on the right side of the rectangle. So you can use this technique to make a rectangle that includes the left-most column of the lines you want to prefix, hit shift-I, type the prefix, and then hit escape.
The other approach is to use a substitution (as mentioned by Brian Agnew). Brian's substitution will affect the entire file (the % in the command means "all lines"). To affect just a few lines the easiest approach is to hit shift-V (which enables visual-line mode) while on the first/last line, and then move to the last/first line. Then type:
:s/^/YOUR PREFIX/
The ^ is a regex (in this case, the beginning of the line). By typing this in visual line mode you'll see '<,'> inserted before the s automatically. This means the range of the substitution will be the visual selection.
Extra tip: if your prefix contains slashes, you can either escape them with backslash, or you can use a different punctuation character as the separator in the command. For example, to add C++ line comments, I usually write:
:s:^:// :
For adding a suffix the substitution approach is generally easier unless all of your lines are exactly the same length. Just use $ for the pattern instead of ^ and your string will be appended instead of pre-pended.
If you want to add a prefix and a suffix simultaneously, you can do something like this:
:s/.*/PREFIX & SUFFIX/
The .* matches the whole line. The & in the replacement puts the matched text (the whole line) back, but now it'll have your prefix and suffix added.
BTW: when commenting out code you'll probably want to uncomment it later. You can use visual-block (ctrl-V) to select the slashes and then hit d to delete them, or you can use a substitution (probably with a visual line selection, made with shift-V) to remove the leading slashes like this:
:s:// ::
:normal to the rescue!
:%norm Wibar(
:%norm WEa)
:norm(al) replays the commands as if you had typed them:
W - goes to the next word
i - starts insertion mode
bar( - types the sequence 'bar('
Or in one line:
:%norm Wibar(ctrlvESCEa)
If you're running Windows then type ctrlq instead of ctrlv.
Yet another possibility (probably not-so-useful in your test case, but handy in other situations) is to cordon off the area you want to change with marks.
Put the cursor anywhere in the top line and press 'a
Put the cursor anywhere in the last line and press 'b
Issue the command :'a,'b s/foo/bar(&)/
I usually like visual block mode if everything is visible on the screen, and I usually prefer marks if the start and stop are separated by many screens.
Another simple regular expression is:
%s/^/<text you want to prepend>/
For the C-style comments, use the regexp answer by Brian, and match on line ending $, and insert away.

In Vim, what is the best way to select, delete, or comment out large portions of multi-screen text?

Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?
I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?
And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?
Well, first of all, you can set vim to work with the mouse, which would allow you to select text just like you would in Eclipse.
You can also use the Visual selection - v, by default. Once selected, you can yank, cut, etc.
As far as commenting out the block, I usually select it with VISUAL, then do
:'<,'>s/^/# /
Replacing the beginning of each line with a #. (The '< and '> markers are the beginning and and of the visual selection.
Use markers.
Go to the top of the text block you want to delete and enter
ma
anywhere on that line. No need for the colon.
Then go to the end of the block and enter the following:
:'a,.d
Entering ma has set marker a for the character under the cursor.
The command you have entered after moving to the bottom of the text block says "from the line containing the character described by marker a ('a) to the current line (.) delete."
This sort of thing can be used for other things as well.
:'a,.ya b - yank from 'a to current line and put in buffer 'b'
:'a,.ya B - yank from 'a to current line and append to buffer 'b'
:'a,.s/^/#/ - from 'a to current line, substitute '#' for line begin
(i.e. comment out in Perl)
:'s,.s#^#//# - from 'a to current line, substitute '//' for line begin
(i.e. comment out in C++)
N.B. 'a (apostrophe-a) refers to the line containing the character marked by a. ``a(backtick-a) refers to the character marked bya`.
To insert comments select the beginning characters of the lines using CTRL-v (blockwise-visual, not 'v' character wise-visual or 'V' linewise-visual). Then go to insert-mode using 'I', enter your comment-character(s) on the first line (for example '#') and finally escape to normal mode using 'Esc'. Voila!
To remove the comments use blockwise-visual to select the comments and just delete them using 'x'.
Use the visual block command v (or V for whole lines and C-V for rectangular blocks). While in visual block mode, you can use any motion commands including search; I use } frequently to skip to the next blank line. Once the block is marked, you can :w it to a file, delete, yank, or whatever. If you execute a command and the visual block goes away, re-select the same block with gv. See :help visual-change for more.
I think there are language-specific scripts that come with vim that do things like comment out blocks of code in a way that fits your language of choice.
Press V (uppercase V) and then press 40j to select 40 lines and then press d to delete them. Or as #zigdon replied, you can comment them out.
The visual mode is the solution for your main problem. As to commenting out sections of code, there are many plugins for that on vim.org, I am using tComment.vim at the moment.
There is also a neat way to comment out a block without a plugin. Lets say you work in python and # is the comment character. Make a visual block selection of the column you want the hash sign to be in, and type I#ESCAPE. To enter a visual block mode press C-q on windows or C-v on linux.
My block comment technique:
Ctrl+V to start blockwise visual mode.
Make your selection.
With the selection still active, Shift+I. This put you into column insert mode.
Type you comment characters '#' or '//' or whatever.
ESC.
Or you may want to give this script a try...
http://www.vim.org/scripts/script.php?script_id=23
For commenting out lines, I would suggest one of these plugins:
EnhancedCommentify
NERD Commenter
I find myself using NERD more these days, but I've used EnhancedCommentify for years.
If you want to perform an action on a range of lines, and you know the line numbers, you can put the range on the command line. For instance, to delete lines 20 through 200 you can do:
:20,200d
To move lines 20 through 200 to where line 300 is you can use:
:20,200m300
And so on.
Use Shift+V to go in visual mode, then you can select lines and delete / change them.
My usual method for commenting out 40 lines would be to put the cursor on the first line and enter the command:
:.,+40s/^/# /
(For here thru 40 lines forward, substitute start-of-line with hash, space)
Seems a bit longer than some other methods suggested, but I like to do things with the keyboard instead of the mouse.
First answer is currently not quite right?
To comment out selection press ':' and type command
:'<,'>s/^/# /g
('<, '> - will be there automatically)
You should be aware of the normal mode command [count]CTRL-D.
It optionally changes the 'scroll' option from 10 to [count], and then scrolls down that many lines. Pressing CTRL-D again will scroll down that same lines again.
So try entering
V "visual line selection mode
30 "optionally set scroll value to 30
CTRL-D "jump down a screen, repeated as necessary
y " yank your selection
CTRL-U works the same way but scrolls up.
v enters visual block mode, where you can select as if with shift in most common editors, later you can do anything you can normally do with normal commands (substitution :'<,'>s/^/#/ to prepend with a comment, for instance) where '<,'> means the selected visual block instead of all the text.
marks would be the simplest mb where u want to begin and me where u want to end once this is done you can do pretty much anything you want
:'b,'ed
deletes from marker b to marker e
commenting out 40 lines you can do in the visual mode
V40j:s/^/#/
will comment out 40 lines from where u start the sequence

Resources