Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a default path for interactive directory selection to start with in a elisp defun?

Tags:

emacs

elisp

I want a function to interactively prompt for an existing directory, but instead of starting from default-directory, I would like a function local default path like '~/should/start/here/always/in/this/function' to start at when using (interactive "D") how can I achieve this? My first thought is to create another function which first sets default-dir and then calls my original function, but that doesn't seem right, and I am unsure of how interactive would be prompted in that case.

like image 662
re5et Avatar asked Jan 26 '11 05:01

re5et


People also ask

How do I change the default directory in Emacs?

You can type the 'cd' emacs command. ( M-x cd ) to change the default folder as a one off.

What does interactive do in Lisp?

The "call" to `interactive' is actually a declaration rather than a function; it tells `call-interactively' how to read arguments to pass to the function. When actually called, `interactive' just returns nil. The argument of `interactive' is usually a string containing a code letter followed by a prompt.


1 Answers

Since you're writing this yourself, you can do something like this:

(defun choose-directory (directory)
  "sample that uses interactive to get a directory"
  (interactive (list (read-directory-name "What directory? " 
                                          choose-directory-default-directory)))
  (message "You chose %s." directory))

(defvar choose-directory-default-directory "/home/tjackson/work/data"
  "Initial starting point.")

Which uses interactive with a lisp expression to call read-directory to get a directory name (you might want to add additional arguments, check the link/docs).

Your original hunch would work as well, though, as you thought, isn't quite as clean. But, it does work well when you don't want to, or cannot, modify the function whose behavior you want to change. I've included that solution below to show you how you'd achieve it (the only piece of the puzzle you didn't mention was call-interactively):

;; original version of choose-directory, calling (interactive "D")
(defun choose-directory (directory)
  "sample that uses interactive to get a directory"
  (interactive "DWhat directory? ")
  (message "You chose %s." directory))

(defun wrap-choose-directory ()
  (interactive)
  (let ((default-directory choose-directory-default-directory))
    (call-interactively 'choose-directory)))
like image 130
Trey Jackson Avatar answered Nov 03 '22 00:11

Trey Jackson