On startup, I want to create an empty buffer and switch to it, but only if no file has been specified in the command line.

The closest I have is

(switch-to-buffer "untitled")

at the end of init.el but this still creates an "untitled" buffer even when I specify a file in the command line. I don't want this because it slows things down and leaves an unneeded buffer lying around.

  • 1
    The default *scratch* buffer will give you the same functionality. If you launch emacs without specifying a file (and if you don't use desktop), the *scratch* buffer will be the first buffer you see. – Kaushal Modi Mar 17 '15 at 17:19
  • yes, but the scratch buffer is special (can't be deleted), I prefer an ordinary buffer – Ernest A Mar 17 '15 at 17:25
  • 1
    By default the scratch buffer can be deleted like any other, so perhaps you've configured something to prevent that. You could also customize initial-buffer-choice. – glucas Mar 17 '15 at 17:39

Using the *scratch* buffer as an empty buffer, as suggested in the comments, is a possible solution.

However, if you prefer to leave the *scratch* buffer alone, then this is an alternative

(add-hook 'emacs-startup-hook
          (lambda () (when (cl-notany 'buffer-file-name (buffer-list))
                        (generate-new-buffer-name "untitled")))))

It will create a new "untitled" buffer and will switch to it, but only if there isn't any buffer that is visiting a file (as would occur when Emacs is started with a filename argument).

Customizing initial-buffer-choice didn't work for me, as it creates the buffer unconditionally.

  • Ah, I should have tested the initial-buffer-choice approach first. :-D It does allow specifying a function so one could presumably use the same conditional logic you've used here -- but the startup hook seems like a logical solution. – glucas Mar 17 '15 at 19:33

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.