paarshad
paarshad

Reputation: 295

Emacs buffer creation/switching function

I would like to make function that creates a buffer named 'console', if it does not exist and runs a few commands. If the buffer already exists I want it to only switch to it.

Upvotes: 1

Views: 372

Answers (2)

Trey Jackson
Trey Jackson

Reputation: 74480

Try this, obviously replacing (insert "something\n") with the commands you want to run:

(defun jump-to-console ()
  "go to console buffer if it exists, otherwise create"
  (interactive)
  (let ((buffer-name "console"))
    (if (get-buffer buffer-name)
        (pop-to-buffer buffer-name)
      (pop-to-buffer (get-buffer-create buffer-name))
      (insert "something\n"))))

Upvotes: 2

please delete me
please delete me

Reputation:

get-buffer-create ("Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.") will handle creating the buffer if one doesn't exist. Then use switch-to-buffer ("Make BUFFER-OR-NAME current and display it in selected window.") to switch to the buffer.

So something like this will do the trick:

(switch-to-buffer (get-buffer-create "console"))

Upvotes: 4

Related Questions