Skip to content

Instantly share code, notes, and snippets.

@unhammer
Created October 28, 2015 08:51
Show Gist options
  • Save unhammer/103e8ad5823ea323d328 to your computer and use it in GitHub Desktop.
Save unhammer/103e8ad5823ea323d328 to your computer and use it in GitHub Desktop.
(defun glyph-pixel-width (pos)
(let* ((font (font-at pos))
(glyphs (when font (font-get-glyphs font pos (1+ pos))))
(glyph (when glyphs (aref glyphs 0))))
(if glyph
(aref glyph 4)
0)))
(defun line-pixel-width ()
(save-excursion
(goto-char (line-beginning-position))
(let ((sum 0)
(end (line-end-position)))
(while (< (point) end)
(let ((x (glyph-pixel-width (point))))
(when x
(setq sum (+ sum x))))
(forward-char))
sum)))
(defun buffer-max-line-pixel-width ()
(save-excursion
(goto-char (point-min))
(let ((max (line-pixel-width)))
(while (eq (forward-line 1) 0)
(let ((x (line-pixel-width)))
(when (and x (> x max))
(setq max x))))
max)))
(defun center-current-window (&optional pixel-padding)
"Center the current window, allowing for at least the longest
lines in the buffer."
(interactive)
(let* ((window (get-buffer-window (current-buffer)))
(max-line-pixel-width (buffer-max-line-pixel-width))
(window-pixel-width (window-width window 'pixelwise))
(pixel-padding 30)
(pixel-margin (max 0 (/ (- window-pixel-width
(+ pixel-padding
max-line-pixel-width))
2)))
(window-width (window-width window))
(pixel-ratio (/ (float window-width) (float window-pixel-width)))
(margin (floor (* pixel-margin pixel-ratio))))
(set-window-margins window margin margin)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment