So buffer-string
gets the content of the current buffer. But it doesn't allow specifying other buffers.
How can I get around that? Do I need something like save-window-excursion
to make it work?
So buffer-string
gets the content of the current buffer. But it doesn't allow specifying other buffers.
How can I get around that? Do I need something like save-window-excursion
to make it work?
A lot of things in Emacs operate on the current buffer. You need to change the current buffer and restore it when you're done. Use with-current-buffer
for simple cases where you just need to do something in another buffer, and save-current-buffer
for more complex cases where you need to navigate between several buffers.
(defun buffer-string* (buffer)
(with-current-buffer buffer
(buffer-string)))
If you want the text content of the buffer without properties, call buffer-substring-no-properties
.
buffer-string
returns only the narrowed part of the buffer. If you need the whole content, widen it after saving the narrowing.
(defun buffer-whole-string (buffer)
(with-current-buffer buffer
(save-restriction
(widen)
(buffer-substring-no-properties (point-min) (point-max)))))
If you also need to save the point, call save-excursion
as well. Note that save-excursion
restores the point only in the current buffer, so if you need to switch to another buffer and move around there, call save-excursion
inside save-current-buffer
or with-current-buffer
.