I'm trying to define a function which will keep my fixed width body in Emacs centered in the buffer rather than aligned to the left side. In particular I want this to be buffer-local, and I'm trying to do this by locally setting left- and right-margin-width.
This works fine by itself, but I also want a hook to adjust the margins when the window size changes, and this is causing problems for me. Here's the code (adapted from https://stackoverflow.com/a/23731757/3822233):
(defun center-body ()
(let* ((max-text-width 70)
(margin (max 0 (/ (- (window-width) max-text-width) 2))))
(setq-local left-margin-width margin)
(setq-local right-margin-width margin)
(set-window-buffer nil (current-buffer))))
(defun uncenter-body ()
(setq-local left-margin-width 0)
(setq-local right-margin-width 0)
(set-window-buffer nil (current-buffer)))
(defun body-center-mode ()
(interactive)
(if (= left-margin-width 0)
(progn
(center-body))
(add-hook 'window-configuration-change-hook 'center-body nil 1))
(uncenter-body)
(remove-hook 'window-configuration-change-hook 'center-body 1)))
When the add-hook and remove-hook lines are removed, everthing's ok. But as soon as I call the add-hook I get a nesting exceeds max-lisp-eval-depth error.
I don't really understand lisp so I'm having trouble debugging this.