Linux - disabling primary selection and using only clipboard selection
There are 2 clipboard-like mechanisms in Linux - primary selection (copy by selecting text and paste by middle mouse button) and clipboard selection (copy by CTRL+C, paste by CTRL+V). Since I prefer using only the latter, I wanted to completely disable the primary selection.
Note: This solution (specifically the echo -n "" | xclip -i -selection primary
part of it) clears the selection in GTK applications. This problem happens even when using the xsel
tool instead of xclip
. If you use this or a similar solution and see problems in selecting text in GTK applications, it may be related.
Install xclip and clipnotify, e.g. in Arch Linux:
pacman -S xclip clipnotify
Create the following script (e.g. in /home/user/clipboard_fix):
#!/bin/bash
set -e
set -u
while clipnotify; do
echo -n "" | xclip -i -selection primary
echo -n "" | xclip -i -selection secondary
done
The script:
- waits for the clipboard contents to change
- after each change, clears the contents of
primary
andsecondary
selections, while not touching theclipboard
selection
Leave the script running in the background when X starts, e.g. add this to ~/.xinitrc
:
/home/user/clipboard_fix &
For me, this mechanism avoids pasting some random content after I accidentally press the middle mouse button.
The clipboard selection (CTRL+C, CTRL+V) is actually supported in many applications, e.g.:
- GUI applications (Qt, GTK)
- terminology (terminal emulator)
- far2l (file manager) when running in
--notty
mode - Visual Studio Code - in its terminal, it can be configured to CTRL+C and CTRL+V in File -> Preferences -> Keyboard Shortcuts
If some applications cannot work together correctly through the clipboard because of different data formats (targets), we can create a workaround by adding an automatic conversion to our script, e.g.:
CURRENT_TARGETS=$(xclip -o -t TARGETS -selection clipboard | tr '\n' '|')
if [ "${CURRENT_TARGETS}" == "text/plain;charset=utf-8|application/x-elementary-markup|" ]; then
xclip -o -selection clipboard | xclip -i -selection clipboard -t STRING
fi