Want a simple way, like notepad++ plugin: NppExport
- Export to RTF
, to copy selected text with syntax highlighting.
Notepad++, NppExport, Export to RTF example:
It's a bit roundabout, but one way to achieve this with built-in tools is to use the :TOhtml
command to create an HTML file that contains the highlighted text, open that file in a browser, and then copy from there.
:TOhtml
takes a range, so you can use this method to "copy" the highlighted contents of a visual selection.
See :help :TOhtml
and :help 2html
for details.
I found an email discussion about the same topic: http://vim.1045645.n5.nabble.com/convert-syntax-highlighted-text-to-RTF-td1177362.html
They also suggest :TOhtml
and also an alternative plugin to convert to html. And then they suggest pandoc to convert html → rtf.
And also found a vim plugin that claims to export to rtf (OS X only): https://github.com/zerowidth/vim-copy-as-rtf
It has been forked for Windows and Linux support too: https://github.com/adah1972/vim-copy-as-rtf
I'm not on windows, but @root described in his answer, that you can copy formatted HTML to clipboard with the command scb -as
(that's what I understood).
The following just collects @roots steps in a function. Put the following in your vimrc
:
function! CopyFormatted(line1, line2)
execute a:line1 . "," . a:line2 . "TOhtml"
%yank *
!start /min powershell -noprofile "gcb | scb -as"
bwipeout!
endfunction
command! -range=% HtmlClip silent call CopyFormatted(<line1>,<line2>)
Then restart Vim and execute:
:HtmlClip
a:line1
and a:line2
? Does this pass particular lines from a file as input to the function?
_vimrc
and reloaded gvim. After, I open a document that has syntax highlighting, I run :command! -range=% HtmlClip silent call CopyFormatted(<line1>,<line2>)
, and nothing happens. No change if I remove silent
.
:command...
also belongs into vimrc
. You then have to run :HtmlClip
.
"gcb | scb -as"
). The only drawback I see with this is also present in my solution, in that you must wait several seconds for PS to load before it can process the input. I was hoping -noprofile
would help but my machine incurs a 1-3 sec load time.
I am using the following in gVim on Windows 10:
Record a macro that does the following:
:TOhtml
ggVG
(select all)"*y
(yank to system clipboard):q!
(close the TOhtml file):!start /min powershell -noprofile "gcb | scb -as"
Start a minimized instance of Powershell that runs a shorthand equivallent of Get-Clipboard | Set-Clipboard -AsHtml)
After running this macro and allowing Powershell to complete, I can then paste directly into Outlook 2016.
NppExport
does.