Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to apply a sed transformation to a vim buffer before copying it to the clipboard?

Tags:

vim

sed

I'm using the following command to copy all lines of text in a document to the system clipboard:

%y+

Usually, especially in order to copy code to StackOverflow ;), I apply a sed transformation to my buffer in order to make it easier to paste in with MarkDown:

%s:^:\t:g

Is there a way to chain the commands without actually applying it to my buffer, only to the copied text?

like image 403
Naftuli Kay Avatar asked Dec 21 '22 09:12

Naftuli Kay


2 Answers

I suggest using a CLI utility to put it on the clipboard: there are several I found previously, but here's one:

  • http://www.debian-administration.org/articles/565

So you'd do

:%!sed 's:^:\t:g`|xclip

or

:%!sed 's:^:\t:g`|xclip -selection c

the latter uses the X clipboard instead of the primary clipboard (assuming UNIX).

On windows, there are likely similar utilities

Edit

A pure vim solution would be:

:let @+=substitute(join(getbufline("%", 1, "$"), "\r\n"), "^\\|\n", "\&\t", "g")

Notes:

  • it is not very efficient (but you use it SO posts... so it's not Homer's Oddyssee)
  • I assume that you want Windows line-ends (which is what I get when copying from SO anyways)
like image 116
sehe Avatar answered May 19 '23 15:05

sehe


If you do not mind adding an entry to the undo list (that means actually editing contents of the buffer), you can perform substitution, yank the text, and undo that substitution in one command.

:%s/^/\t/|%y+|u

Another solution would be to make the substitution right in the contents of the + register just after copying.

:%y+|let@+=substitute(@+,'^\|\n\zs','\t','g')
like image 28
ib. Avatar answered May 19 '23 13:05

ib.