Merge pull request #114 from sourcelair/fix-copy-nbsp

Stop copying non-breaking spaces into clipboard
This commit is contained in:
Paris Kasidiaris 2016-06-10 17:05:10 +03:00 committed by GitHub
commit c908f849c5
2 changed files with 44 additions and 6 deletions

View File

@ -549,17 +549,41 @@
}, true);
};
/**
* Prepares text copied from terminal selection, to be saved in the clipboard by:
* 1. stripping all trailing white spaces
* 2. converting all non-breaking spaces to regular spaces
* @param {string} text The copied text that needs processing for storing in clipboard
* @returns {string}
* @static
*/
Terminal.prepareCopiedTextForClipboard = function (text) {
var space = String.fromCharCode(32),
nonBreakingSpace = String.fromCharCode(160),
allNonBreakingSpaces = new RegExp(nonBreakingSpace, 'g'),
processedText = text.split('\n').map(function (line) {
/**
* Strip all trailing white spaces and convert all non-breaking spaces to regular
* spaces.
*/
var processedLine = line.replace(/\s+$/g, '').replace(allNonBreakingSpaces, space);
return processedLine;
}).join('\n');
return processedText;
};
/**
* Bind copy event. Stript trailing whitespaces from selection.
* Binds copy functionality to the given terminal.
* @static
*/
Terminal.bindCopy = function(term) {
on(term.element, 'copy', function(ev) {
var selectedText = window.getSelection().toString(),
copiedText = selectedText.split('\n').map(function (element) {
return element.replace(/\s+$/g, '');
}).join('\n');
ev.clipboardData.setData('text/plain', copiedText);
var copiedText = window.getSelection().toString(),
text = Terminal.prepareCopiedTextForClipboard(copiedText);
ev.clipboardData.setData('text/plain', text);
ev.preventDefault();
});
};

View File

@ -54,4 +54,18 @@ describe('xterm.js', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ ctrlKey: true, keyCode: 39 }).key, '\x1b[5C'); // CSI 5 C
});
});
describe('evaluateCopiedTextProcessing', function () {
it('should strip trailing whitespaces and replace nbsps with spaces', function () {
var nonBreakingSpace = String.fromCharCode(160),
copiedText = 'echo' + nonBreakingSpace + 'hello' + nonBreakingSpace,
processedText = Terminal.prepareCopiedTextForClipboard(copiedText);
// No trailing spaces
assert.equal(processedText.match(/\s+$/), null);
// No non-breaking space
assert.equal(processedText.indexOf(nonBreakingSpace), -1);
});
});
});