Trailing spaces when copying from console

clipboardterminaltmuxvimwhitespace

It's this annoying behavior I've been experiencing here and there occasionally: when you select text with mouse in console (that is, copy it), paste it, and realize you've got extra spaces at the end of each line. That is,

line 1                                                                          
line 2                                                                          

instead of

line 1
line 2

So, not just one space at the end of each line.

I couldn't reliably reproduce the issue, and couldn't find the answer. I believe with some software it manifests itself only after a while.

But I've just noticed, that when I open the same file in vim, first right from console, then from tmux, it works out well in the former case. And doesn't in the latter one. Considering TERM=xterm-256color in console, and TERM=screen-256color in tmux, my conjecture is that it has to do with terminal not doing it properly, or not enabling applications to do it properly. Quite a vague conjecture, I presume. So, the first question is, "What exactly is causing it?"

And the other one is, "How do I go about it?" The worst case is when the file is located remotely. I used to copy it locally and open it with gedit lately. Now I supposedly have an option to open it in new console (since I'm mostly working in tmux sessions), and copy from there. Could this be done any simpler?

When I run vim from tmux with TERM=xterm-256color vim, it behaves strangely. Like not drawing background where there is no text. And it doesn't seem okay to me to change TERM variable (making software think it's dealing with other terminal).

When editing local file, I usually do :!gedit %.

Best Answer

You'll have spaces at the end of the line when selecting and copying from the terminal if the application displayed spaces at that spot. Applications may display spaces in order to erase what was there before. Terminals have commands to delete a whole line or delete characters to the right of the cursor; applications choose between that and displaying spaces based on what they consider most efficient. For example, if you type some stuff at a prompt, then press Backspace, the application (e.g. the shell) is likely to overwrite the last character with a space.

If you have an X11 connection, you can use xsel or xclip to copy a file to the local clipboard.

Experimentally, Vim seems to go through pains not to display lines ending with spaces (even when the buffer contains a line that ends with spaces). So copying from that is an option if you don't have an X11 connection.

An alternative would be to post-process after copying:

xsel | sed 's/  *$//' | xsel
Related Question