dotfiles

🎜 Clone'em, tweak'em, stick'em in your $HOME 🎝
git clone https://git.kevinlegouguec.net/dotfiles
Log | Files | Refs | README

commit 2b3b773158fdf8842d797f5c46517001d95fe791
parent 7a73548789c10ba2350e4adb5b5db561fd10d386
Author: KΓ©vin Le Gouguec <kevin.legouguec@gmail.com>
Date:   Thu, 26 May 2022 22:57:16 +0200

Add minor mode to keep buffer content centered on window

Diffstat:
M.emacs | 44+++++++++++++++++++++++++++++---------------
1 file changed, 29 insertions(+), 15 deletions(-)

diff --git a/.emacs b/.emacs @@ -163,21 +163,35 @@ (set-variable 'tab-width new-width) (message "changed from %s to %s" old-width new-width))) -(defun my/center-window (text-width) - (interactive - (list (cond - ;; Explicit length. - ((integerp current-prefix-arg) - current-prefix-arg) - ;; C-u. - ((and (listp current-prefix-arg) current-prefix-arg) - nil) - ;; Default. - (80)))) - (let ((margin-width (when text-width - (/ (- (window-width) text-width) 2)))) +(defvar-local my/centered-width 'fill-column) + +(define-minor-mode my/centered-mode + "Update margins to keep content centered." + :init-value nil + (if my/centered-mode + (progn + (add-hook 'window-state-change-functions 'my/centered-set-margins nil t) + (dolist (win (get-buffer-window-list)) + (my/centered-set-margins win))) + (remove-hook 'window-state-change-functions 'my/centered-set-margins t) + (dolist (win (get-buffer-window-list)) + (set-window-margins win nil)))) + +(defun my/centered-set-margins (window) + (let* ((target-body-width + (cond + ((symbolp my/centered-width) + (buffer-local-value my/centered-width (window-buffer window))) + ((integerp my/centered-width) + my/centered-width))) + (adjustable-width + (- (window-total-width window) + (+ (fringe-columns 'left) (fringe-columns 'right)))) + (target-margin + (when (> adjustable-width target-body-width) + (/ (- adjustable-width target-body-width) 2)))) ;; Only set left margin, so that long lines are not truncated. - (set-window-margins nil margin-width))) + (set-window-margins window target-margin))) (defun my/kill (stuff) (kill-new stuff) @@ -232,7 +246,7 @@ (my/define-prefix-command my/display-map "Keymap for display-related commands." - '(("c" my/center-window) + '(("c" my/centered-mode) ("t" toggle-truncate-lines) ("v" visual-line-mode)))