diff --git a/src/xterm.js b/src/xterm.js index a806a03..273fdca 100644 --- a/src/xterm.js +++ b/src/xterm.js @@ -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(); }); }; diff --git a/test/test.js b/test/test.js index e603d65..ffbc285 100644 --- a/test/test.js +++ b/test/test.js @@ -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); + }); + }); });