I am trying to modify the string that is to yanked

My goal is to modify certains paths before yanking, in order to transform them in relative to path actual buffer file.

Following this post, I tried this simple script :

(setq tmp (car kill-ring-yank-pointer))
;;(message tmp)

(defun replace-in-string (what with in)
  (replace-regexp-in-string (regexp-quote what) with in nil 'literal))
(replace-in-string "C:\\Users\\Julien Fernandez\\Dropbox\\JULIEN" "../.." tmp)
(message tmp)

In my kill-ring, I have right now :

C:\Users\Julien Fernandez\Dropbox\JULIEN\Screenshots\Emacs\2021-02-03_16-48-43 - Code.png

I get as a result :

enter image description here

Where the file name has been modified, but obviously not as intended.

What should I do ?

PS : I discovered that I did not have to substitute every \ in `'/' in the path, something like :


works fine ...


replace-regexp-in-string does not do an in-place replacement. C-h f tells us that it returns a new string:

Return a new string containing the replacements.

It sounds like what you want to do is replace the first element of the kill-ring by the result of calling replace-regexp-in-string (which is a different string from the one that is currently the first kill-ring element).

You need to do something like this, with the string you've created:

(setq kill-ring  (cons (replace-in-string
                         "C:\\Users\\Julien Fernandez\\Dropbox\\JULIEN"
                         (car kill-ring))
                       (cdr kill-ring)))

You could instead actually modify the kill-ring list structure, like this, but that's generally not a great idea:

(setcar kill-ring (replace-in-string
                     "C:\\Users\\Julien Fernandez\\Dropbox\\JULIEN"
                     (car kill-ring)))
  • Hi Drew, what's the difference between the first and the second setting? Feb 4 '21 at 6:32
  • @Drew : thx, it works... And I clearly understood my mistake ! I would be glad to understand the difference between the two proposition as well, as per Arch Stanton question. Feb 4 '21 at 10:48

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.