Is there a way to set the display margins for markdown-mode buffers? I've read https://www.gnu.org/software/emacs/manual/html_node/elisp/Display-Margins.html and various suggested solutions but nothing has worked for me. This is what I have currently:

(defun my-margins ()
  (set-window-margins (selected-window) 30 30))

(add-hook 'markdown-mode-hook 'my-margins)

However, nothing happens when I open a .md file. If I evaluate (my-margins) manually, however, then I get the desired result, until I switch to a different buffer, and then the margins are lost.

Ideally, I would like all markdown-mode buffers to have the desired display margins, regardless of whether I open a new frame, switch buffers, etc.

  • Are you trying to center the text in the window ? Jul 3, 2023 at 17:54
  • @TristanRiehs Yes, that's my intention. Is there a better way to do this?
    – jth
    Jul 4, 2023 at 20:46
  • 1
    Yes, the visual-fill-column-center-text feature from visual-fill-column allows you to do it very easily. @jth Jul 5, 2023 at 10:29

1 Answer 1


When you call the my-margins function you provided using markdown-mode-hook, selected-window does not return the window you expect. For example, if you call find-file test.md from the *scratch* buffer, selected-window will return the window displaying the *scratch* buffer, not the new one displaying the buffer of test.md.

To make your function work, you can call it from another hook, one where in the previous example selected-window would return the window displaying the markdown file. You can use window-configuration-change-hook.

We have to adapt my-margins since this hook is not only fired in markdown-mode :

(defun markdown-margins ()
  (when (equal major-mode 'markdown-mode)
    (set-window-margins (selected-window) 30 30)))

(add-hook 'window-configuration-change-hook 'my-margins)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.