reddit / emacs

Switch to buffer if it exists, create new otherwise

pragmat1c1 · 2022-05-05 08:59
I am trying to create a frame that shows two windows side by side with two specific buffers. Now I try to check if those buffers (visiting certain files) are already open by using this snippet: ```elisp (switch-to-buffer (find-file-noselect org-journal-file)) ``` This line does not reliably open the existing buffer (visiting a certain file), but creates new window (+ buffer). Is there another way to switch to a buffer (if it exists), and create a new one otherwise?
T_Verron · 2022-05-05 09:26
`find-file-noselect` should be it, but `switch-to-buffer` might be the problem. I'd use `switch-to-buffer-other-window` instead. But doesn't `(find-file-other-window org-journal-file)` do exactly what you want?
arthurno1 · 2022-05-05 09:39
> Is there another way to switch to a buffer (if it exists) It depends on if you are happy to just switch to a buffer in an existing frame, or you wish to open another view of that buffer in a new frame. Check *switch-to-buffer-other-frame *, and note what happen if it is already displayed in another window. https://www.gnu.org/software/emacs/manual/html_node/elisp/Switching-Buffers.html Otherwise, you could create a new frame, display your buffer with *find-file*, split the window, switch to other window and finally display the second buffer in that window. You will have to check needed elisp functions in the manual yourself.
Ok_Refrigerator_1476 · 2022-05-05 12:51
`get-file-buffer` can check if it's already open in a buffer or not. Try something like (if-let ((buffer (get-file-buffer org-journal-file))) (switch-to-buffer buffer) (find-file org-journal-file))
akirakom · 2022-05-05 15:26
`(find-file-other-window org-journal-file)` should work. If you want to use `switch-to-buffer`/`pop-to-buffer`/etc., you can use the following expression to get or create a buffer: (or (find-buffer-visiting file) (find-file-noselect file))