Search code examples
emacs

Centre Emacs buffer within window


I wrap all my code at 80 columns, and there are times where the Emacs window is wider than 80 columns and there is a lot of unused whitespace on the right side.

I would like to position the Emacs buffer, so all the text is displayed in the middle of the window.

This is different to centre aligning text (more akin to the whitespace on either side of the text when viewing pdfs).

I think this can be achieved by dynamically adjusting the fringe mode widths, depending on the current window size, but I'm not sure where to start. Any ideas?


Solution

  • As demonstrated here this is indeed possible:

    (set-fringe-mode
     (/ (- (frame-pixel-width)
           (* 80 (frame-char-width)))
        2))
    

    However, as I am testing this I seem to have more luck with using margins, at least when also resizing my frame:

    (defun my-resize-margins ()
      (let ((margin-size (/ (- (frame-width) 80) 2)))
        (set-window-margins nil margin-size margin-size)))
    
    (add-hook 'window-configuration-change-hook #'my-resize-margins)
    (my-resize-margins)