Emacs: create a new buffer quickly

I love to use Emacs, mostly for org-mode. I also use Notepad++ as an text editor (when using MS Windows), although I would like to use Emacs more. I noticed I choose Notepad++ when I quickly need an editor buffer to paste some text to because Notepad++ has this “New” icon in its toolbar that creates a new buffer quickly.

Emacs is easily extendible, so how about creating a “quick new buffer” function myself? It is really easy.

To create a new buffer you use Ctrl-x b (for function switch-to-buffer) and type a buffer name. But even typing in a name is too much for me. Automatically name the buffer “New” and add a unique number to it! There is a function called rename-uniquely which does what it says. Now we can create a function make-new-buffer:

  1. (defun make-new-buffer ()
  2.   "makes a new buffer, uniquely named"
  3.   (interactive)
  4.   (switch-to-buffer "New")
  5.   (rename-uniquely))

Super easy: it creates a buffer named “New” and renames it so that it has a unique name. Bind this to a key, I use F5:

  1. (global-set-key (kbd "<f5>") 'make-new-buffer)

Put this code in your .emacs or whatever.

When you have a bunch of buffers called “New<2>”, “New<3>” etc., take a look at buffer-menu. You get a list of all buffers. Now you can operate on them. For instance, mark a buffer for deletion with d, repeat for other buffers and execute the command with x. Now you have killed a bunch of buffers quickly and easily.

If you are new to customizing keybindings and writing custom functions, Sacha Chua wrote a nice article “Read Lisp Tweak Emacs (Beginner 3/4): How can I make things more convenient?

Update: Xah Lee over at ErgoEmacs has published a similar article. He came up with the following, slightly more complex function:

  1. (defun xah-new-empty-buffer ()
  2.   "Open a new empty buffer."
  3.   (interactive)
  4.   (let ((buf (generate-new-buffer "untitled")))
  5.     (switch-to-buffer buf)
  6.     (funcall (and initial-major-mode))
  7.     (setq buffer-offer-save t)))

What is the difference? It uses generate-new-buffer to generate a new buffer and make sure it has a unique name (line 4). Then it switches to that buffer (line 5). It sets the major mode of the new buffer to the one declared in variable initial-major-mode, if any (line 6). Setting buffer-offer-save to t let Emacs ask you for saving that buffer before exiting Emacs (line 7).

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>