Skip to content

Commit 9c18138

Browse files
authored
Merge pull request #4 from hackmdio/feature/yank-to-system-clipboard
Copy text to clipboard with */" registers in vim mode
2 parents 8ce8e88 + ae2ecad commit 9c18138

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

keymap/vim.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,27 @@
4444
})(function(CodeMirror) {
4545
'use strict';
4646

47+
// from https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
48+
function copyToClipboard (str) {
49+
var el = document.createElement('textarea'); // Create a <textarea> element
50+
el.value = str; // Set its value to the string that you want copied
51+
el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
52+
el.style.position = 'absolute';
53+
el.style.left = '-9999px'; // Move outside the screen to make it invisible
54+
document.body.appendChild(el); // Append the <textarea> element to the HTML document
55+
const selected =
56+
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
57+
? document.getSelection().getRangeAt(0) // Store selection if found
58+
: false; // Mark as false to know no selection existed before
59+
el.select(); // Select the <textarea> content
60+
document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
61+
document.body.removeChild(el); // Remove the <textarea> element
62+
if (selected) { // If a selection existed before copying
63+
document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
64+
document.getSelection().addRange(selected); // Restore the original selection
65+
}
66+
};
67+
4768
var defaultKeymap = [
4869
// Key to key mapping. This goes first to make it possible to override
4970
// existing mappings.
@@ -2233,6 +2254,10 @@
22332254
var endPos = vim.visualMode
22342255
? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
22352256
: oldAnchor;
2257+
if (['+', '*'].indexOf(args.registerName) !== -1) {
2258+
copyToClipboard(text)
2259+
cm.focus()
2260+
}
22362261
vimGlobalState.registerController.pushText(
22372262
args.registerName, 'yank',
22382263
text, args.linewise, vim.visualBlock);

0 commit comments

Comments
 (0)