Search code examples
emacselisprelative-path

elisp - Get path to file relative to script


Say I am writing an emacs lisp function that interfaces with a file located relative to the file in which the function is defined.

- bin/executable
- foo.el

foo.el:

(defun foo ()
  (shell-command-to-string
   (format "echo '%s' | ./bin/executable"
           (buffer-substring-no-properties
            (point-min)
            (point-max)))))

If I run this from foo.el then it works great. If I invoke the function while editing any other file it doesn't work because the path ain't right.

How can I reliably reference ./bin/executable from within foo.el no matter where the function is invoked?


Solution

  • Use load-file-name variable.

    (defconst directory-of-foo (file-name-directory load-file-name))
    
    (defun foo ()
      (shell-command-to-string
       (format "echo '%s' | %s"
               (buffer-substring-no-properties
                (point-min)
                (point-max))
               (expand-file-name "./bin/executable" directory-of-foo))))