Fork me on GitHub
#emacs
<
2023-07-18
>
teodorlu08:07:44

Hi! I want a function to get the name of the current folder. If I’m editing /home/teodorlu/myproject/myfile.clj, I want "myproject". I wrote a function which seems to work (below), but I suspect that there’s something built in that does this already. Any pointers?

(defun directory-containing-current-file ()
  (car (last (s-split "/" (replace-regexp-in-string "/$" "" default-directory)))))

2
Ellis08:07:34

(thread-last 
  "/home/teodorlu/myproject/myfile.clj"
  f-dirname
  f-split
  cadddr)
Depends on f but pretty much every package includes it so you should have it

💯 2
teodorlu08:07:17

Amazing, thanks! 💯

teodorlu08:07:51

If I want this to work for arbitrary deep paths, should I replace cadddr with last car?

(thread-last
  "/home/teodorlu/a/b/c/myproject/myfile.clj"
  f-dirname
  f-split
  last
  car)

Ellis08:07:22

Yeah or use nth and nreverse to get the exact segment you want

👍 2
teodorlu08:07:43

Great — thanks! Didn’t know about f.el or thread-last, those are going to be useful 🙌

Ellis08:07:28

The latter is built-in since 28.1 in subr-x which is full of other useful macros and the former is depended on by so many packages it's not unreasonable to expect it to exist

👍 2
Benjamin16:07:44

hey this exists 😛

(file-name-parent-directory FILENAME)

Return the directory name of the parent directory of FILENAME.
If FILENAME is at the root of the filesystem, return nil.
If FILENAME is relative, it is interpreted to be relative
to 'default-directory', and the result will also be relative.
(file-name-parent-directory "/home/teodorlu/myproject/myfile.clj") "/home/teodorlu/myproject/"

Benjamin16:07:46

(file-name-base (directory-file-name (file-name-parent-directory "/home/teodorlu/myproject/myfile.clj"))) "myproject"

aisamu19:07:38

Only adding this (from my config) because it surprised me that there was even another way of doing the same thing: (f-base (file-name-directory buffer-file-name))

teodorlu11:07:35

Oooh, nice!! Thanks @U02CV2P4J6S and @U1UQEM078 🙏

🎉 4
adi16:07:38

This is how I have defined my dotemacs' root dir.

(defvar dotemacs-dir  
   (file-name-directory (or load-file-name (buffer-file-name)))
  "The dotemacs' root.  Normally it should be ~/.emacs.d.")

👍 2
adi16:07:10

Of course, this will only work sensibly for file-backed buffers.

adi16:07:02

One thing that tripped me up is that directory names must be terminated correctly (forward slash on linux). To do this I have been using file-name-as-directory:

(defvar dotemacs-savefile-dir
  (file-name-as-directory (expand-file-name "savefile" dotemacs-dir))
  "This folder stores all the automatically generated save/history-files.")

👍 2