I think the reason your code is not working as hoped for is because you are using the buffer-local variable projectile-project-root
instead of the eponymous function.
C-hvprojectile-project-root
RET reveals:
projectile-project-root is a variable defined in ‘projectile.el’.
Its value is nil
Automatically becomes buffer-local when set.
Documentation:
Defines a custom Projectile project root.
This is intended to be used as a file local variable.
In other words, projectile.el
never sets this variable itself; it is provided only in case users want to set it buffer- or file-locally (see (emacs) Locals
and (emacs) File Variables
, respectively).
This explains why
(file-relative-name buffer-file-name projectile-project-root)
(which you mentioned in a comment) returns the non-directory part of buffer-file-name
, as opposed to the desired relative path.
Compare this with C-hfprojectile-project-root
RET:
projectile-project-root is a compiled Lisp function in
‘projectile.el’.
(projectile-project-root &optional DIR)
Retrieves the root directory of a project if available.
If DIR is not supplied its set to the current directory by default.
Combining this knowledge with dakra's good suggestion to use file-relative-name
instead of manipulating file names as strings (which should and almost always can be avoided), we arrive at the following means of killing the current buffer's absolute file name relative to its projectile
root:
(kill-new (file-relative-name buffer-file-name (projectile-project-root)))
string-remove-prefix
, andkill-new
should probably be called with only one argumentbuffer-file-name
must be an absolute, not relative, file name. If you want to change the buffer's user-visible name you should userename-buffer
instead. See(elisp) Buffer Names
. If that is not what you're trying to do, then please elaborate on what your ultimate goal is, as it's not very clear from your question.