Fábio Perez
Fábio Perez

Reputation: 26048

Run bash command on Vim and copy result to clipboard

How can I create a Vim command and copy it's results to clipboard?

I want to convert Markdown to HTML and copy the result to the clipboard. So far I got:

nmap md :%!/bin/markdown/Markdown.pl --html4tags

But this will substitute my opened file on Vim to the result of Markdown.

Upvotes: 2

Views: 1069

Answers (3)

Zhora
Zhora

Reputation: 549

Filling in a missing piece (2+ years late). With the clarification that the user was on a Mac and since the asker's "why doesn't it work for me?" question was not answered.

To redirect the output of a command to the system clipboard from within MacVim (GUI version) you need to set the '*' to be the "clipboard register" you need to change the clipboard setting to 'unnamed':

set clipboard 'unnamed'   # 'cb' can be substituted for 'clipboard'

Then sidyll's answer should work except specify the '*' register and not the '+' register:

:let @*=system(...)

The clipboard feature is likely not compiled into the "terminal version" of MacVim and when it is available option setting is different from 'unnamed'. To see more details regarding what works where and how, see the documentation in MacVim using the Vim help command:

 :help 'clipboard'    (include the single quotes since it's a set option!)

(I'll skip the command mapping issue since it always takes me several tries and I still have to look it up; finding the help for the mapping commands should be easier than finding it for the * register.)

Upvotes: 0

sidyll
sidyll

Reputation: 59277

You didn't say which system you're using, but generally saving it in the + register should work. You can call system():

:let @+=system("markdown --html4tags", join(getline(1,line("$")), "\n"))

The system() function takes the second parameter (optional) as input to the command, and here I'm using a chain of other functions to retrieve the contents of the current buffer. Not sure, but there should be a better way to do it (if someone knows, please let me know).

Alternatively, you can pass markdown your file name as input directly:

:let @+=system("markdown --html4tags " . shellescape(expand("%:p")))

But keep in mind that you'll need to write the file before calling this.

Two important notes:

  1. I didn't type your full path to markdown. Use it.
  2. I didn't use maps here, the final result would be something like:
nnoremap md :let @+=system(...)

Upvotes: 4

Kevin
Kevin

Reputation: 1569

get the xsel package

and pipe stdout to xsel --clipboard

For instance:

cat /etc/passwd | xsel --clipboard

Is that what you're looking for?

Upvotes: 1

Related Questions