15

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?

  • If you don't mind me asking, what are you trying to do? – Luke Oct 5 '14 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. – Maciej Goszczycki Oct 5 '14 at 20:46
25

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, privacy policy and cookie policy

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