Search code examples
emacselisp

Recenter a named buffer that is not necessarily the current buffer in Emacs Lisp


I'd like to recenter a buffer, called *Lense*, where I've inserted some text. I wished to make it the current buffer by (set-buffer "*Lense*"), then (recenter 0)). By the following code segments:

(save-excursion (set-buffer "*Lense*")
                (recenter 0))

However, it seems that the above code would only recenter the buffer which is the current buffer, and (set-buffer "*Lense*") has no effect to make the current buffer to be *Lense*.

Please help me to figure out the right way to recenter the named buffer *Lense*.


Solution

  • If the buffer you want to recenter is visible, then you want to recenter its window.

    (with-selected-window (get-buffer-window "*Lense*")
      (recenter 0))
    

    This will blow up if the buffer is not being displayed, so you may want to condition-case or unwind-protect.

    If you want to handle the case where the buffer is not visible, you need to move the point. The window that will eventually display the buffer will center near the point, so you will have to move the point somewhere that will make that happen. Seems like your insert operation will DTRT, so you don't need to worry in that case.