Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get v$y to not copy the newline character in Vim on Mac and Linux?

Tags:

vim

I've used the Windows version of Vim in the past, but am new to MacVim. In MacVim, when I switch to visual mode, use the $ motion (highlighting from my cursor to the end of the line), and yank, when I paste the copied content, it includes the carriage return, bumping everything after the paste point down to a new line.

This behavior seemed unfamiliar (not to mention annoying) to me. Is there any way to change this behavior to match the Windows version, where the newline is not included in the yank?

like image 336
Brian Sullivan Avatar asked Sep 20 '10 21:09

Brian Sullivan


People also ask

What is new line character in Vim?

Use \r instead of \n . Substituting by \n inserts a null character into the text. To get a newline, use \r . When searching for a newline, you'd still use \n , however.

How do I copy a line in vi Linux?

Press the ESC key to be sure you are in vi Command mode. Place the cursor on the line you wish to copy. Type yy to copy the line.

How do I copy a whole line in Vim?

To copy text, place the cursor in the desired location and press the y key followed by the movement command. Below are some helpful yanking commands: yy - Yank (copy) the current line, including the newline character. 3yy - Yank (copy) three lines, starting from the line where the cursor is positioned.


2 Answers

There's a little-known motion that serves this need regardless of configuring Windows behaviors and can generally be useful in other contexts: g_. Quoth :help g_:

g_          To the last non-blank character of the line and
            [count - 1] lines downward |inclusive|. {not in Vi}

Personally I don't tend to use this for yanking because I avoid the extra visual mode keystroke and use y$ (which doesn't copy the newline, as @zigdon suggested). Or better yet, nnoremap Y y$ so that Y works consistently with C and D.

I do however often use g_ with surround.vim where the mappings to add surrounds are often harder to remember for me than using visual selection. If you want to select until the end of the line and surround with parens, for instance, it would be ys$), which isn't bad but I tend to forget the ys mnemonic. v$S) seems natural but has the same problem as your question: it includes the newline, and that's a total mess when adding surrounds. vg_S) is exactly what you usually want.

One nice thing about doing it visually is that you can correct mid-selection: I still tend to hit v$ by muscle memory a lot, but if you see that you've overshot before acting, you can still hit g_ and fix the selection.

like image 111
ches Avatar answered Sep 19 '22 08:09

ches


Is just copying the text until the end of the line inappropriate? y$ will just copy from your current cursor until the end of the line, without the newline.

like image 26
zigdon Avatar answered Sep 18 '22 08:09

zigdon