Friday 8 January 2010

Centring Emacs on Screen

Something I've wanted to do for a while that's nevertheless eluded me is how to centre Emacs on-screen when it launches. I'm a bit old fashioned and so like the default 80 character width, but I like as many rows as possible.

At first, with functions like (set-frame-height), (frame-pixel-height) and (display-pixel-height), it seems like it should be trivial, but the problem is that Emacs measures its frame height and width in characters, whereas the pixel functions (obviously) work in pixels.

The link comes in the from of (frame-char-height) and (frame-char-width), which give the height and width of an idividual character in pixels. Just evaluating the following expression should centre Emacs on your primary monitor:

(set-frame-height (selected-frame)
(floor (* 0.95 (/ (display-pixel-height)
(set-frame-position (selected-frame)
(floor (/ (- (display-pixel-width) (frame-pixel-width))
(floor (* 0.02 (display-pixel-height))))

If you like this (maybe after some tweaking), you can just stuff the instructions in your .emacs to get it every time.