Search code examples
emacskey-bindingscode-formatting

Is there a default binding, or func for 'format to 80 columns a region' in emacs?


When writing text in emacs for Markdown, or even comments I tend to want to keep the number of columns less than or equal to 80 (or 77 -- is what I prefer actually). I'm trying to get more familiar with emacs Lisp to just write this function and then bind it to a global key set (I think). However, if it already exists, then no need, but if it doesn't I'm really only learning stuff about buffers, and rearranging text inside regions. But, if some one had the code I could look at and learn from that would work out well too.

Either way, is there a default binding, or func for 'format to 80 columns a region' in emacs?


Solution

  • The keybinding is M-q, the function is called fill-paragraph, and the mode is called auto-fill-mode !

    so to enable it for markdown buffers:

    (add-hook 'markdown-mode-hook 'auto-fill-mode)
    

    Now you'll ask… where is the unfill-paragraph ?? Well (how embarassing), it doesn't exist (maybe in recent version of emacs ?). I picked it on xahlee's blog, here it is:

    (defun unfill-paragraph ()
      "Replace newline chars in current paragraph by single spaces.
    This command does the reverse of `fill-paragraph'."
      (interactive)
      (let ((fill-column 90002000))
        (fill-paragraph nil)))
    (defun unfill-region (start end)
      "Replace newline chars in region by single spaces.
    This command does the reverse of `fill-region'."
      (interactive "r")
      (let ((fill-column 90002000))
        (fill-region start end)))