4

I am dabbling in Emacs Lisp and I am trying to write the following function:

(defun buffer-file-name-body ()
  (last (split-string (buffer-file-name) "/")))

What I am trying to achieve is to extract just the file name and extension from the full path given by (buffer-file-name). However, this implementation returns a list of one item ("scratch.el") ... I tried several things such as passing the result of (last) through (string) but that raises an error... Google did not return anything useful when I searched for Emacs List convert list to string. How to I do this?

6
  • 1
    do you mean you have a list '("scranch.el") and you need to extract "scratch.el" from it? Commented Jul 12, 2012 at 5:14
  • 2
    Yes, that is correct... would a simple CAR suffice? Commented Jul 12, 2012 at 5:17
  • Yes, it does I just tested it Commented Jul 12, 2012 at 5:18
  • 2
    Please post the solution as an answer and accept it. Thanks. Commented Jul 12, 2012 at 5:47
  • 5
    You might want to check out the built-in function file-name-nondirectory. (Also, if you allow me the small hint, your function will barf on buffers that do not visit a file, such as e.g., *scratch*.) Commented Jul 12, 2012 at 6:15

1 Answer 1

5

It sounds to me like what you want is (file-name-nondirectory (buffer-file-name)) which returns the simple file name, sans any directory information, as a string.

Sign up to request clarification or add additional context in comments.

6 Comments

Although the original question was around converting a List to a String and CAR would be a good solution, using (file-name-nondirectory) applies better to this situation and is the cleanner solution...
@HowardWest Hey mate, nice piggy backing on my comment above. Please note again that (buffer-file-name) returns nil for buffers not visiting a file, and that file-name-nondirectory cannot handle a nil argument.
@Thomas If you answer the question, I will give you accepted answer for it... :)
@JonasGorauskas Ah, don't worry about it. I honestly think it's not even the correct answer to your actual question, because it doesn't tell you how to extract a string value from a list. It might have been what you were after, but it doesn't answer what you asked about. If anything, fvwmer should get the credit since he gave the correct answer to that.
I took this to be the question: "What I am trying to achieve is to extract just the file name and extension from the full path given by (buffer-file-name)"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.