I want to insert content from one file anytime a file with a particular name is opened, i have this:

(defun insert-foo-bar(filename)
  (when (string= (file-name-nondirectory filename) "foo")
    (insert-file-contents "~/bar")))

(add-hook 'find-file-hook 'insert-foo-bar)

However after visiting a file with C-x C-f i get a "wrong number of arguments" error. Can anyone tell me what am I doing wrong?


  • When you call function from hook it have no arguments, but your function insert-foo-bar needs one - filename. Change your question if you want to get an answer with code. – Konstantin Morenko Jul 30 '16 at 18:19

You could use this version of your function

(defun insert-foo-bar ()
  (when (string= (find-file-nondirectory buffer-file-name) "foo")
    (insert-file-contents "~/bar")))

(add-hook 'find-file-hook 'insert-foo-bar)

Or shorter

(add-hook 'find-file-hook (lambda ()
  (when (string= (find-file-nondirectory buffer-file-name) "foo")
    (insert-file-contents "~/bar"))))
  • 1
    buffer-file-name (without something else added to the equation) will never equal foo -- the doc-string states (in part): "This should be an absolute file name." The original poster has indicated that he/she wishes to use the function file-name-nondirectory to ascertain the top level name of the file. – lawlist Jul 30 '16 at 18:42
  • @lawlist you are right, I have changed that part to this (when (string= (file-name-nondirectory buffer-file-name) "foo") and it works as expected – user12812 Jul 30 '16 at 18:42
  • I'll fix it, sorry, mistake. – Konstantin Morenko Jul 30 '16 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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