22

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?

2
  • If you don't mind me asking, what are you trying to do? Oct 5, 2014 at 20:44
  • @King I'm creating an asynchronous process and I want to send buffer's content as it's standard input. I figured I can use process-send-string and I got stuck. Oct 5, 2014 at 20:46

1 Answer 1

30

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.