There is an unfill-paragraph
mentioned here that does the opposite of fill-paragraph
. I would like to bind the key like the follows. M-q
once to fill-paragraph
. If the cursor does not move, push M-q
again to unfill-paragraph
. What is an elegant way to implement this in Emacs?
Asked
Active
Viewed 171 times
5

xuhdev
- 1,839
- 13
- 26
2 Answers
5
The answer provided by @icarus does not let you keep toggling back and forth. If you want that then you also need to set this-command
, so that it alternates.
(defun my-fill-paragraph (&optional arg)
"Fill or unfill paragraph. If repeated, alternate.
A prefix arg for filling means justify (as for `fill-paragraph')."
(interactive "P")
(let ((fillp (not (eq last-command 'fill-paragraph))))
(apply (setq this-command (if fillp 'fill-paragraph 'unfill-paragraph))
(and fillp arg '(full t)))))

Drew
- 75,699
- 9
- 109
- 225
-
1Using "icarus's answer" rather than "the answer of @icarus" stops stack exchange from notifying me. In general I dislike updating `this-command`, although it works in this case. It stops you being able to use my-fill-paragraph as a function to call from some other toggle. You should refactor the body to be `(interactive)(funcall (setq this-command (if (eq last-command #'fill-paragraph) #'unfill-paragraph #'fill-paragraph)))`. I look forward to you adding the support for prefix arg to be passed on to fill-paragraph. – icarus Dec 31 '16 at 06:18
-
@icarus: (I didn't know about "@icarus's".) Edited as suggested (except using a symbol, not a function object, for `this-command` value). HTH. – Drew Dec 31 '16 at 17:30
3
Something like
(defun xuhdev/fill-paragraph ()
(interactive)
(if (eq last-command this-command)
(unfill-paragraph)
(fill-paragraph)))
and then binding xuhdev/fill-paragraph to M-q perhaps? I can't say I am a great fan of the idea, and I am leaving off support for arguments to fill-paragraph...

icarus
- 1,904
- 1
- 10
- 15