Tuesday, March 3, 2015

Two of my most-used Vim mappings (yo)

I’ve been complaining (sometimes misdirecting my complaints) about this being broken for a while now, so perhaps as I have it working again now I might as well give it a Shout-Out.™

One of the cool things to result from my recent re-upgrade to Vim 7.4 was the return of the * clipboard. I have these two (well, four, with the comments) lines in my .vimrc:

" In visual mode, use Y to copy to system clipboard
vnoremap Y "*y

" In normal mode, do the same with the current line
nnoremap Y "*yy

They might explain themselves (well, with the comments), no? In case they don’t: They map the Y key so that it yanks text into the * register. This register represents Vim’s view of your OS’s clipboard… it’s a little hard to get from the docs, but here is from clipboard under :help quotestar:

There is a special register for storing this selection, it is the "* register.  Nothing is put in here unless the information about what text is selected is about to change (e.g. with a left mouse click somewhere), or when another application wants to paste the selected text.  Then the text is put in the "* register.  For example, to cut a line and make it the current selection/put it on the clipboard:


Similarly, when you want to paste a selection from another application, e.g., by clicking the middle mouse button, the selection is put in the "* register first, and then 'put' like any other register.  For example, to put the selection (contents of the clipboard):


(I copied that using my Y mapping! Hee, hee!)

This was not working for me on pre-7.4 Vim, but it is on post-7.4. Also, I do not know what the hubbub seems to be about left mouse clicks or middle mouse buttons; I just use a keyboard-derived visual selection in Vim. So what this means is that I can select text using v or V (Vim’s visual mode, either linewise or characterwise), hit Y, and then Cmd+V into TextEdit, or Messages or Blogger via Firefox. (I’m on a Mac.)

This is hugely helpful, since I prefer to deal with text from inside Vim (and I use terminal Vim), but then of course text is often needed elsewhere and to be dealt with from within other apps. My terminal emulator (iTerm2, although I don’t know that I use any of its distinguishing-from-Terminal features) was always more or less a first-class application in this regard, but not its Vim; with these mappings making use of this register, I can copy from Vim and then paste into primitive text-handling facilities unaware of its existence anything.

Tip #984 on the venerable Vim Tips Wiki covers this, with additional and related discussion.

No comments:

Post a Comment