Suppose I have a file dir1/this_file.txt and dir2/this_file.txt, and I want to insert different boilerplate code not based on the file name or extension, but based on the directory in which the file is created. How can I do that?

-- Edit --

Additionally, what if the boilerplate code depends on the filename of the file being created?

  • If my answer answers your Q, please consider tagging it as the Answer. Thanks.
    – RichieHH
    Feb 16, 2020 at 14:14

2 Answers 2


As phils said obtain the directory name

(file-name-directory (or buffer-file-name ""))

and then open a boilerplate template in that directory is maybe what you want rather than configure the template code in Emacs itself. I knocked this up and it seems to work.

  (defun insert-boilerplate ()
    (let ((boiler-plate-file (expand-file-name ".boilerplate" (file-name-directory (or buffer-file-name "")))))
      (if (file-exists-p boiler-plate-file)
          (insert-file-contents boiler-plate-file)))
  (add-to-list 'find-file-not-found-functions #'insert-boilerplate)

Simply create a .boilerplate file in the directory and it should be good to go.

  • thanks. Always welcome. I'll edit my answer.
    – RichieHH
    Feb 16, 2020 at 11:25
  • 2
    Or just use (if (file-exists-p ".boilerplate") (insert-file-contents ".boilerplate")) which will do the same.
    – Stefan
    Feb 16, 2020 at 15:00
  • Heh. Indeed. It includes the full path. Noted.
    – RichieHH
    Feb 16, 2020 at 19:20

You can obtain the directory with:

(file-name-directory (or buffer-file-name ""))
  • 1
    You can also just use default-directory which will not always be identical, but for all practical purposes it is.
    – Stefan
    Feb 16, 2020 at 14:57
  • Heh. Yes, I obviously had a bit of a brain-fade there...
    – phils
    Feb 16, 2020 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.