Use the mouse to properly select text in less

lessterminal

I've just discovered that I can add the following lines to ~/.vimrc.

set mouse=a
:vmap <C-C> "+y

This has the effect of being able to select text with the mouse (i.e. in visual mode), and then copy the actual text to the X clipboard with Ctrl+c. This differs from the default copy from the terminal, as it's the real text I'm copying, not what the terminal sees. For example, if there were tabs in the text, then previously I'd copy them as spaces.

Is there a way to make less behave the same way? i.e. can I copy verbatim what is in the text file I'm viewing in less?

Best Answer

Not a task for less

No,
I do not think you can do that directly, because less does not have a cursor to begin with.
It would need one to navigate to start and end of the text to select.
less is just not the right tool for character-level navigation.

Tabs already expanded

You can use the key shift and the mouse to make a selection; This is handled by the terminal, not by less. But the terminal does not know how spaces and tabs where arranged - less does the interpretation of tabs internally, and writes only normal " " characters to the screen.

There are tools like screen, tmux and byobu, which can do lots of impressive things in this area. I did not check, but I assume that these terminal multiplexers do not have a way around that - being terminals, in the end - and will behave the same.

Use vim

If you are showing a file in less, there is a nice solution:
Press the key v in less to open the current file in vim - asuming your $EDITOR etc. is set up for vim.

This does not work when showing stdin from a pipeline or so, although there are workarounds.

Mouse scrolling, at least

But you can at least scroll with the mouse wheel:

That seems even to be enabled by default, but the mouse wheel events get suppressed by a different option.

For a quick test, try:

LESS=-r man less

The option -X (--no-init) blocks scrolling - check what your environment variable LESS contains:

$ echo $LESS

The option -q (--quiet, --silent) also causes trouble, according to SU: How to make mouse wheel scroll the less pager using bash and gnome-terminal?