1

I have this function:

;; needs work in case of spaces in filenames
(cl-defun filename-from-buffer (&key get-ext get-abs)
  "Returns the absolute name, with or without extension,
   of the file that is open in the current buffer."
  (let ((filename (buffer-name))
        (absname (buffer-file-name)))
    (cond
     ((and get-ext get-abs) absname )
     (get-abs (file-name-sans-extension absname ))
     (get-ext filename)
     (t (file-name-sans-extension filename)))))

You can test it with something like this,

(global-set-key
 (kbd "C-l t")
 (lambda () (interactive)
   (insert (filename-from-buffer :get-ext t :get-abs t))
   ;; /Nuskha/With Space/file.ext
   (insert "\n")
   (insert (filename-from-buffer))
   ;; file
   (insert "\n")
   (insert (filename-from-buffer :get-ext t))
   ;; file.ext
   (insert "\n")
   (insert (filename-from-buffer :get-abs t))))
   ;; /Nuskha/With Space/file

It works fine, but when there are spaces in the name, as shown in the comments above, the names are not such that you could take them verbatim and use with the cd command.

$ cd /Nuskha/With Space/file
bash: cd: too many arguments

I want a function that returns something like this /Nuskha/With\ Space/file. How could this be done?

  • 1
    In Emacs jargon, what you called "path" are called absolute file names. A "path" in Emacs jargon is a list like the value of environment variable $PATH. – Drew Dec 18 '19 at 15:59
  • I see, so the function pathname and absname work the same? Because right now, I am using pathname and it works as in the usual understanding of the word path. – scribe Dec 19 '19 at 6:21
  • I don't understand the question in your comment. Where are you seeing a function pathname or absname? – Drew Dec 19 '19 at 15:33
  • Oh! I am sorry. I forgot what I was doing there. I thought I was calling a function in let instead of assigning variables. – scribe Dec 20 '19 at 1:05
4

Use quotes to make cd think /Nuskha/With Space/file is one single argument, not two, e.g.,

$ cd "/Nuskha/With Space/file"
$ cd '/Nuskha/With Space/file'

You can also use shell-quote-argument:

(shell-quote-argument "/Nuskha/With Space/file")
;; => "/Nuskha/With\\ Space/file"

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.