Insert file name

Here is a simple function from the emacs wiki to insert the name of a file into the current buffer. The convenient thing is that it uses the normal find-file prompt with whatever your completion setting is, so it works very easily. I bind it to C-c b i and as the documentation says, by default it inserts a relative path but called with a prefix (C-u C-c b i) it inserts the full path.

;; insert file name at point                                              ;;
(defun bjm/insert-file-name (filename &optional args)
  "Insert name of file FILENAME into buffer after point.

  Prefixed with \\[universal-argument], expand the file name to
  its fully canocalized path.  See `expand-file-name'.

  Prefixed with \\[negative-argument], use relative path to file
  name from current directory, `default-directory'.  See

  The default with no prefix is to insert the file name exactly as
  it appears in the minibuffer prompt."
  ;; Based on insert-file in Emacs -- ashawley 20080926
  (interactive "*fInsert file name: \nP")
  (cond ((eq '- args)
         (insert (expand-file-name filename)))
        ((not (null args))
         (insert filename))
         (insert (file-relative-name filename)))))

;; bind it
(global-set-key (kbd "C-c b i") 'bjm/insert-file-name)
  • Tassilo Horn

    An alternative is to use hippie-expand instead of dabbrev with file-name completion and dabbrev-completion. Then you can complete file-names everywhere without having a separate command. That works really awesome.

    (global-set-key (kbd “M-/”) ‘hippie-expand)
    (setq hippie-expand-try-functions-list ‘(try-complete-file-name

    • Thanks – I didn’t know about this. Does it only complete files in the directory of the current buffer, or files from other locations too?

      • Tassilo Horn

        It completes any path, e.g., ~/ will show completions from your home directory.

  • You have a stray set of parens, so this doesn’t work with a prefix.

    (insert (filename)) should be (insert filename).