;;; xsel.el --- use the X clipboard -*- lexical-binding: t -*- ;; ;; Author: Emanuel Berg ;; Created: 2021-05-04 ;; Keywords: unix ;; License: GPL3+ ;; URL: https://dataswamp.org/~incal/emacs-init/xsel.el ;; Version: 2.4.9 ;; ;;; Commentary: ;; ;; This gives you access to the X clipboard from a Linux ;; VT/console/tty Emacs instance (or any Emacs, possibly). ;; Set and/or Insert the X clipboard at point. ;; ;; DWIM: If there is a region, replace it with the ;; X clipboard. ;; ;; Feature: Set the X clipboard programmatically in Elisp or ;; set it interactively to the contents of the region (if ;; there is one), otherwise set it to the most recent ;; Emacs kill. ;; ;; Use $DISPLAY or ":0" with xsel(1x). ;; ;;; Code: (require 'dwim) (let ((xsel-x-display (or (getenv "DISPLAY") ":0"))) (defun insert-x-clipboard () "Insert the X clipboard at point using xsel(1x). If there is a region it is overwritten." (interactive) (when (use-region-p) (delete-region (region-beginning) (region-end)) ) (shell-command (format "xsel --display \"%s\" --clipboard -o" xsel-x-display) 1) ; current buffer insert (goto-char (mark)) ) (declare-function insert-x-clipboard nil) (defun set-x-clipboard (str) "Set the X clipboard to STR. When used interactively, STR is either what is in the region, if available, if not the most recent Emacs kill is used." (interactive (list (if (use-region-p) (buffer-substring-no-properties (region-beginning) (region-end)) (encode-coding-string (current-kill 0 t) 'utf-8-unix) ))) (shell-command (format "echo -n %s | xsel --display %s -b -i" (shell-quote-argument str) xsel-x-display) )) (declare-function set-x-clipboard nil) ) (defun x-copy (&optional beg end) "Copy the buffer text from BEG to END to the X clipboard. Unless optional arguments are provided the whole buffer text is used." (interactive (use-region)) (or beg (setq beg (point-min))) (or end (setq end (point-max))) (set-x-clipboard (buffer-substring beg end)) ) (defun x-copy-symbol (sym) "Copy the value of SYM to the X clipboard." (interactive "S Symbol: ") (let*((val (symbol-value sym)) (str (format "%s" val)) ) (set-x-clipboard str) )) ;; (progn (x-copy-symbol 'fill-column) (insert-x-clipboard)) ;; (progn (call-interactively #'x-copy-symbol) (insert-x-clipboard)) (defun x-clipboard-dwim () "If the region is active, set the X clipboard, if not, insert it." (interactive) (call-interactively (if (use-region-p) #'set-x-clipboard #'insert-x-clipboard) )) (defalias 'x #'x-clipboard-dwim) (defalias 'xo #'insert-x-clipboard) (provide 'xsel) ;;; xsel.el ends here