damd
damd

Reputation: 6957

Emacs: Define a function which loads the file where the function itself is defined

I'm refactoring a bit in my Emacs set up and have come to the conclusion that I want to use a different init file than the default one. So basically, in my ~/.emacs file, I have this:

(load "/some/directory/init.el")

Up until now, that's been working just fine. However, now I want to redefine an old command that I've used for ages, which opens my init file:

(defun conf ()
  "Open a buffer with the user init file."
  (interactive)
  (find-file user-init-file))

As you can see, this will open ~/.emacs no matter what I do. I want it to open /some/directory/init.el, or wherever the conf command itself is defined.

How would I do that?

Upvotes: 9

Views: 351

Answers (3)

Stefan
Stefan

Reputation: 28531

You can also use a sneakier way:

(defun conf () "blabla" (interactive) (find-file #$))

Because #$ works a bit like _FILE_ in C: it's replaced by the filename when the file is read.

Upvotes: 3

Cheeso
Cheeso

Reputation: 192467

This works for me.

;;; mymodule.el --- does my thing

(defvar mymodule--load-path nil  "load path of the module")

   ...

(defun mymodule-load-datafile () 
  "load a data file from the directory in which the .el resides"
  (let* ((dir-name (concat
                        (file-name-directory mymodule--load-path)))
         (data-file-name (concat dir-name "datafile.csv")))
    (if (file-exists-p  data-file-name) 
         ... )))

;; remember load time path
(setq mymodule--load-path load-file-name)

(provide 'mymodule)

Upvotes: 0

Trey Jackson
Trey Jackson

Reputation: 74430

You can use find-function for this:

(defun conf ()
  "Open a buffer with the user init file."
  (interactive)
  (find-function this-command))

Upvotes: 6

Related Questions