How can I check if a current buffer exists in Emacs? - emacs

I would like to write a function which takes action if a give buffer name already exists. For example:
(if (buffer-exists "my-buffer-name")
; do something
)
Does elisp have a function that will check the for the existence of a buffer similar to how my made up "buffer-exists" function does?
Thanks

From the documentation:
(get-buffer name)
Return the buffer named name (a string).
If there is no live buffer named name, return nil.
name may also be a buffer; if so, the value is that buffer.
(get-buffer-create name)
Return the buffer named name, or create such a buffer and return it.
A new buffer is created if there is no live buffer named name.
If name starts with a space, the new buffer does not keep undo information.
If name is a buffer instead of a string, then it is the value returned.
The value is never nil.

This is what I did:
(when (get-buffer "*scratch*")
(kill-buffer "*scratch*"))
This checks for the buffer scratch. If there's such a thing, kill it.
If not, do nothing at all.

not sure about version this predicate appeared, but now Emacs has buffer-live-p:
buffer-live-p is a built-in function in `buffer.c'.
(buffer-live-p OBJECT)
Return non-nil if OBJECT is a buffer which has not been killed.
Value is nil if OBJECT is not a buffer or if it has been killed.

If you'd like to define your hypothetical function as above, this works:
(defun buffer-exists (bufname) (not (eq nil (get-buffer bufname))))
I use this to automatically close the *scratch* buffer on startup, so I don't have to cycle through it in my list of buffers, as follows:
(defun buffer-exists (bufname) (not (eq nil (get-buffer bufname))))
(if (buffer-exists "*scratch*") (kill-buffer "*scratch*"))

Related

&optional BUFFER for other-buffer function does not work?

When I need to switch to another buffer I have a key binding that will create a buffer called "*Buffer List*" from which I select the new buffer.
I need a command to switch between current buffer and the previous one. Except I don't want "*Buffer List*". I looked up function definition for other-buffer:
(other-buffer &optional BUFFER VISIBLE-OK FRAME)
Return most recently selected buffer other than BUFFER...
so I tried using:
(other-buffer "*Buffer List*")
Now if in the new buffer I execute above code with C-x C-e it will echo "*Buffer List*", instead of the initial buffer that I called "*Buffer List*" from. So &optional BUFFER does not seem to work the way I do it. Can anyone explain why?
BUFFER must be a buffer object. To use the buffer name you would need to use:
(other-buffer (get-buffer "*Buffer List*"))
Notice that when you can use a buffer's name as the argument, the documentation tends to name that argument BUFFER-OR-NAME (e.g. see the docstring for get-buffer itself), and to be explicit about the fact in the text.
If you see BUFFER as an argument, it likely requires the actual buffer object (as in this instance).

emacs - after-change-functions are not executed after buffer modification

I have added a function to after-change-functions list using this code
(defun test-func ()
(message "foo"))
(add-hook 'after-change-functions 'test-func nil t)
Now whenever i change buffer manually, test-func is getting called. But when i programatically modify the buffer using insert, the contents of buffer are getting updated, but test-func is not getting called.
Any pointers on how to activate test-func everytime buffer is updated?
Update:
I am trying to convert markdown to html and serve that on browser, so that whenever user types some markdown, html will be updated automatically.
Here is original implementation of test-func
(defun impatient-markup-update (&rest args)
"Update html buffer if markup buffer updates."
(save-buffer impatient-markup-buffer)
(with-current-buffer (get-buffer impatient-markup-html-buffer)
(erase-buffer)
(insert (shell-command-to-string
(format "%s %s" impatient-markup-pandoc impatient-markup-buffer)))))
Use sleep-for after the call to message, as a test, to see whether you see the message then.
after-change-functions does not necessarily run your hook in the buffer you expect. And as the doc says:
*Buffer changes made while executing the after-change-functions don't call any before-change or after-change functions. That's because inhibit-modification-hooks is temporarily set non-nil.
Check what else is on that hook, etc. IOW, do a little debugging.

Emacs: How do I create a new "empty" buffer whenever creating a new frame?

My Emacs is on OS X system. Is there any way to make a new frame defaulted to an empty buffer whenever I use ⌘N (just like the way TextEdit works)? I prefer to write contents first and decide an appropriate filename later. However, Emacs wants me to decide the filename first and write contents later. I don't see any advantage for it. Does anyone know why Emacs works that way?
Basically, if I use C-x 5 2, Emacs always pops up a frame with whatever file I am currently working on. This is inconvenient. I also don't want my Emacs to pop up a new frame defaulted to *scratch* (many Google search results somehow suggest this approach). I prefer it to have a buffer temporarily called "Untitled" in the new frame, and if I use ⌘N again, Emacs pops up another temporarily "Untitled 2" buffer, and so on. In this way, I can decide the buffer filenames later.
You can create new buffers with switch-to-buffer. Type C-x b, enter a buffer name, and press RET. If no buffer with that name exists, Emacs creates a new one automatically in Fundamental Mode. You may switch to any other mode as usual with M-x, e.g. M-x python-mode. To change the default buffer, set the default value of major-mode to the desired buffer.
If you'd like to have a buffer name chosen automatically, and create a new frame, however, you need to write your own command:
(defun lunaryorn-new-buffer-frame ()
"Create a new frame with a new empty buffer."
(interactive)
(let ((buffer (generate-new-buffer "untitled")))
(set-buffer-major-mode buffer)
(display-buffer buffer '(display-buffer-pop-up-frame . nil))))
Bind this to C-c n:
(global-set-key (kbd "C-c n") #'lunaryorn-new-buffer-frame)
Now pressing C-c n creates a new frame with a new empty buffer named “untitled” where x is a consecutive number.
The following will create a buffer with a unique name. The buffer is not associated with any file, so if/when you ever C-x C-s save-buffer, you will be prompted to supply a filename.
(defun empty-frame ()
"Open a new frame with a buffer named Untitled<N>.
The buffer is not associated with a file."
(interactive)
(switch-to-buffer-other-frame (generate-new-buffer "Untitled")))
This might work for you, if I understand your request:
(defun empty-frame ()
(interactive)
(let ((fl (make-temp-file "Untitled")))
(switch-to-buffer-other-frame fl)))
This will open a new temporary file for each new buffer. If you'd rather not actually create the file, you can use this instead:
(defun empty-frame ()
(interactive)
(let ((bn "Untitled-")
(num 1))
(while
(get-buffer (concat bn (number-to-string num)))
(setq num (1+ num)))
(switch-to-buffer-other-frame
(concat bn (number-to-string num)))))
You've seen answers as to how to create new "Untitled" buffers, but as for why Emacs wants you to first choose a name, some of the reasons are:
Historical: that's just how it worked, and once you get used to it, it's no worse than the alternative.
Major modes and various other details are usually chosen based on the name of the file. So instead of creating an Untitled buffer and having to choose whether to put it into LaTeX mode or C mode, you just open a file with extension ".tex" or ".c".
Having a file name means that Emacs can use the standard auto-save procedure, whereas with the Untitled approach, applications need to have some special way to auto-save those Untitled documents at some "standard" place.
C-x b *untitled* will open new buffer if not exist. Also, see Emacs manual

Emacs: send output of eval to a new buffer

I want to eval a buffer and send the result to a new buffer. How do I "send" the result of the eval-buffer function to the content of a new buffer? here my attempt:
(set-buffer (get-buffer-create "test")) ; create new buffer
(let ((value (eval-buffer)) .... ; how to put this inside the new buffer?
This evaluates the contents of buffer evaluate-me and prints the value of each toplevel form to the buffer output:
(eval-buffer "evaluate-me" (get-buffer-create "output"))
Do C-h f eval-buffer to see the documentation that explains why this works. The second argument to eval-buffer is named PRINTFLAG, of which the docstring says:
PRINTFLAG controls printing of output:
A value of nil means discard it; anything else is stream for print.
The slightly confusing thing about this is Emacs's unusual concept of what counts as an "output stream". Buffers, markers (locations in buffers), and the echo area can all be treated as "streams", as can any function that takes a character argument. Look up the docstrings of the print function or standard-output variable for more info.
The more general way to make things happen inside another buffer is the macro with-current-buffer. Unlike set-buffer, it takes care of restoring the original context cleanly even if errors happen in the wrapped code.
(with-current-buffer (get-buffer-create "output")
(insert "some text"))
Your value calculation appears wrong: since set-buffer will switch to the new buffer, eval-buffer will evaluate the contents of the new empty buffer. My understanding is that you want to evaluate the contents of the previous buffer and print its value in the new buffer:
(let ((value (eval-buffer)))
(set-buffer (get-buffer-create "test"))
(print value))
If you want the new buffer to be visible to the user, replace set-buffer with switch-to-buffer.

emacs lisp, how to get buffer major mode?

I have tried to search Google and look in the manual, but still cannot find how to get major mode of a buffer object. Can you help me with an example or a reference. Thanks
only solution I could find was to query major-mode after changing the buffer and then changing back to original buffer. Is there a better way to do it?
Is there a problem with that?
(defun buffer-mode (buffer-or-string)
"Returns the major mode associated with a buffer."
(with-current-buffer buffer-or-string
major-mode))
with-current-buffer will restore your buffer when it returns.
For current buffer:
(message "%s" major-mode)
A simple way to do this is to use the buffer-local-value function since major-mode is a buffer-local variable:
(buffer-local-value 'major-mode (get-buffer "*scratch*"))
Just extending from previous answers - call with no arguments to get the current buffer's mode:
(defun buffer-mode (&optional buffer-or-name)
"Returns the major mode associated with a buffer.
If buffer-or-name is nil return current buffer's mode."
(buffer-local-value 'major-mode
(if buffer-or-name (get-buffer buffer-or-name) (current-buffer))))
E.g. in *scratch* buffer:
(buffer-mode) => 'lisp-interaction-mode
(buffer-mode "tasks.org") => 'org-mode
Well, describe-mode takes an optional buffer argument, but that displays the help... and I'm not exactly sure what it returns...
But that's the best I could find in a brief search... sorry...
Simply evaluate this:
(print major-mode)
Another way, apart from directly readind the major-mode variable would be by directly readind the mode-name variable.