# How to replace the first element of the kill-ring by a modification of it?

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 :

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 :

../..\Path\to\file.txt


works fine ...

## 1 Answer

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? – Arch Stanton Feb 4 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. – user1683620 Feb 4 at 10:48