Let's assume I invoke EMACS (24.3.1) always with just one file name to visit. How do I get the buffer for that file while in my .EMACS startup? I tried it and the function (current-buffer) will return my scratch buffer.

3 Answers 3


You can use the variable command-line-args to get a list of elements making up the command line used to invoke emacs. If your command line consists of just two elements — "emacs" and the filename to visit — you can get the buffer associated with the file visited like this:

(get-buffer (file-name-nondirectory (cadr command-line-args)))

However, this won't work in your .emacs startup file because the buffer for the file being visited isn't available yet. Instead, you can add code to your .emacs file to add something like the above to the emacs-startup-hook, which is run after command line arguments are handled. For example, this code augments the hook to set a variable named cmd-line-file-buffer to the buffer of the file being visited:

(add-hook 'emacs-startup-hook
      (lambda ()
        (if (= 2 (length command-line-args))
            (setq cmd-line-file-buffer
                  (get-buffer (file-name-nondirectory (cadr command-line-args)))))))

There are two issues to solve: the .emacs file is loaded too early, and there are multiple buffers in a running instance of Emacs, even just after startup.

The first issue is solved by putting your code in emacs-startup-hook, as pointed out in the other answers. The second issue is solved by ignoring any buffers that don't have any associated files:

(defun my-file-buffers ()
  (remove nil
          (mapcar #'(lambda (buffer) (and (buffer-file-name buffer) buffer))

(add-hook 'emacs-startup-hook
          #'(lambda ()
              (message "The following buffers are interesting today: %s"

I guess this is because the init file is loaded and run before the file to visit is loaded. You could use the hook after-load-functions to run code just after the file to visit is loaded. For example, put this in your init file:

(add-hook 'after-load-functions (lambda (f) (setq my-buffer (current-buffer))))

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.