0

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?

Prikshet Sharma
  • 237
  • 1
  • 3

2 Answers2

1

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)))
    nil)
  (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.

Stefan
  • 26,154
  • 3
  • 46
  • 84
RichieHH
  • 848
  • 4
  • 9
0

You can obtain the directory with:

(file-name-directory (or buffer-file-name ""))
phils
  • 48,657
  • 3
  • 76
  • 115