1

I'm a novice in Lisp, so I feel like I'm missing something very basic here. My intention was to create a function/shortcut to remove all whitespace and newline chars from the selected text and copy the resulting string to the X primary clipboard/selection. For example, when selecting the text:

line 1
line 2

The function should copy line1line2 to the clipboard. To be precise, it should be copied to the primary selection. I've written the following code for this presumably easy task:

(defun copy-no-white-space ()
  (interactive)
  (gui-set-selection
    'PRIMARY
    (replace-regexp-in-string "[\s\n]" "" (buffer-substring (region-beginning) (region-end))))

Unfortunately, this does not work this way. When I try to paste the modified pattern, it only yields the original region with no modifications and I just can not wrap my head around why: It works when PRIMARY is replaced with CLIPBOARD (only that I really want to use PRIMARY). What confuses me even more is the fact that it works with PRIMARY when I remove the regular expression in favor of a fixed string and that it also works when I put it outside of the function. (edit: only when nothing is marked) Why? ;)

2

After reading Primary Selection I got a clue for the solution. A simple deactivate-mark did the trick for me:

(defun copy-no-white-space ()
  (interactive)
  (deactivate-mark)
  (gui-set-selection
    'PRIMARY
    (replace-regexp-in-string "[\s\n]" "" (buffer-substring (region-beginning) (region-end))))

My interpretation is the following: After leaving the interactive function, X or Emacs(?) re-evaluates the current selection, to bring the highlighted region to the primary clipboard again. Thinking about it, this probably makes a lot sense for other functions that do not actually want to fiddle with the primary selection, I see that my intention is kind of goofy in this sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.