When in console mode, syntax highlighting can get in the way and generate whole lines of "spaces" being copied within your selected code.
Checking this is the culprit
To check if this is what is plaguing you:
- disable syntax highlighting temporarily with
- Then try to copy-paste and see if you can still reproduce the issue.
- Once confirmed/infirmed, you can set syntax highlighting back with the same command.
If disabling syntax highlighting fixed your copy/paste issue, you might want the read the following to fix this definitively.
Why is that happening ?
What triggers the issue is that you have set a background color to some fonts (often on the default font). As a result, emacs is filling the background with empty chars so it can "paint" the screen as you wanted, and any copy-paste action will contains these spurious white spaces.
How to fix that ?
You should check your face customizations (for default font you could use
M-x customize-face <RET> default <RET>) and if you have a background-color different from
unspecified-bg then this is the culprit.
unspecified-bg is some sort of transparent background color, and it's actually the default background color of emacs if you didn't customize it.
We can force the background to use
unspecified-bg upon emacs start by adding this in you
~/.emacs, after any auto-generated
'(default ((t (:background "unspecified-bg"))))))
Then either restart your emacs, or
M-x eval-region on this block to check the result.
As a side note, you will also get back any fancy terminal's background trick in your emacs (I'm thinking of transparency or background images...).
NOTE: even with this, you could have some bad surprise with ghost white-spaces being captured in some special text, that would get a poorly highlighted font. In these cases, you might consider using the first trick.
More explanation of why this is happening
Terminals have a background color of their own (some terminal can even allow to display an image as background or to even be transparent).
So for the console, there is like a nothing color (see it like an alpha channel), and this is the default color for console.
Console application can change both the color of the font and the background through ANSI escape sequences.
If you ask emacs to change the background color, it'll have to artificially paint the screen with white-spaces characters having their own background color set to whatever you chose.
When selecting, you often use the terminal copy-pasting functionality, that is totally unaware of the console application you are using. It does it job by copy-pasting whatever characters are on the screen, and will thus copy the white-spaces.
Note that you can have setup that will allow your console application to actually receive the mouses input and manage the selection and copy-paste. But it is not that common and the shell, which is the most common app that is active in your terminal do not support the mouse.