I use external drives pretty often – for backups, for moving files between machines, and for storing mp4 files, for example. I’ve been using UDisks for quite some time now. It automounts an external drive under the /run/media/$USER/VolumeName
directory (where VolumeName
is different for each drive, of course).
I also use Dired as my main file manager. As most Emacsers know, it’s far from shiny, but it’s incredibly powerful, especially combined with some other Emacs features.
One problem I have is that when I insert a drive into one of the USB ports, I’d like to be able to open it in Dired. I could of course create a bookmark pointing to it, but I don’t want to maintain a seperate bookmark for every drive I use. I could also bookmark the /run/media/mbork
directory, but then I’d have to press one more key to get to the VolumeName
directory. I figured that I could create a function which opens Dired in the root directory of my drive, assuming that it’s the only mounted one. (If there are more mounted drives – which means more directories under /run/media/mbork
– the function should allow me to select one of them.) Of course, I could probably go even further, detect that a drive was mounted and open its directory in Dired automatically, but that might be a bit too much. Sometimes I don’t want to do anything with the drive (for example, when I use it only to make my daily backups), and sometimes I might be doing something else (for example reading or writing), and Emacs suddenly switching to another buffer would not be helpful.
Anyway, here’s some Lisp code I wrote in about 10 minutes.
(defcustom automount-directory (format "/run/media/%s" user-login-name) "Directory under which drives are automounted.") (defun automount-open-in-dired () "Open the automounted drive in Dired. If there is more than one, let the user choose." (interactive) (let ((dirs (directory-files automount-directory nil "^[^.]"))) (dired (file-name-concat automount-directory (cond ((null dirs) (error "No drives mounted at the moment")) ((= (length dirs) 1) (car dirs)) (t (completing-read "Open in dired: " dirs nil t)))))))
And of course, if you want to learn to code your own convenience commands like this, as usual I recommend Introduction to programming in Emacs Lisp by the late Robert J. Chassell as an appetizer, and my book, Hacking your way around in Emacs, as the next course.