Adding clipboard link to top-right of all code blocks

In my wiki I have lots of code blocks and like most modern UIs, I was hoping to have some sort of link on the top-right which when clicked, would copy the entire copy block to the clipboard.

Is there any easy way of adding this today? It seems like this would be a handy default.

see https://tiddlywiki.com/#copy-to-clipboard%20Macro

For example:

@@float:right;<$macrocall $name=copy-to-clipboard src={{HelloThere}}/>@@
<$codeblock code={{HelloThere}}/>

enjoy,
-e

Thanks Eric. I was aware of that facility, but I have hundreds of existing tiddlers, many of which contain multiple code blocks in the one tiddler. I was hoping there would be some tweaks available where these blocks could somehow automatically be rendered to get a copy clipboard link without having to change any tiddler text.

You can use the \widget pragma to redefine the $codeblock widget to add the copy-to-clipboard macrocall, like this:

Define a tiddler (e.g., “MyCodeBlockWidget”), tagged with $:/tags/Global, containing:

\widget $codeblock(code)
@@float:right;<$macrocall $name=copy-to-clipboard src=<<code>>/>@@
<$genesis $type="$codeblock" $remappable="no" code=<<code>>/>
\end

That’s all you need. Now all $codeblock widgets will have the “copy to clipboard” button in the upper right corner.

For more info, see https://tiddlywiki.com/#Custom%20Widgets

enjoy,
-e

2 Likes

Many thanks… that works on a plain tiddlywiki fine. My old wiki has CSS customisations to show scrollbars with (large) code blocks which I think is interferring with this working right…

pre {
    height: auto;
    max-height: 40em;
    overflow: auto;
}

pre.code {
    font-family:monospace;
    font-size:.9em;
    border:1px solid #e1e1e8;
    border-radius:3px;
    padding: 0em .1em .2em .1em;
}

Also see the tweak wilk-tweaks — TW tweaks, settings, styles, palettes. and implemented as plugin https://wilk-plugin-library.tiddlyhost.com/#%24%3A%2Fplugins%2Fwilk%2Fcopy-code-button

Try this:

\widget $codeblock(code)
@@float:right;<$macrocall $name=copy-to-clipboard src=<<code>>/>@@
<div style="clear:both;"><$genesis $type="$codeblock" $remappable="no" code=<<code>>/></div>
\end

By wrapping the $genesis widget inside a <div style="clear:both;">...</div>, it ensures that the $codeblock will always start on a new line following the “copy to clipboard” button.

Let me know how it goes…

-e

Actually, my node-based TW was just a bit old and required updating and that fixed things. It also works fine in my non-node JS wikis with your original suggestion.

This was just my preference, but I cloned $:/language/Buttons/CopyToClipboard/Caption and set it to :clipboard:. I also cloned $:/core/images/copy-clipboard and made it blank, to get the effect I was after:

Many thanks for your help!

I have created buttons for use on the view and edit toolbars to copy the text field or title, which is another approach.

Can you share the code for those?