6
votes

I am now using Emacs 23 with visual-line-mode turned of for text editing but keep hitting M-q out of habit (thus adding hard-wrapping line endings...). I wonder if there is a way to add a conditional to disable fill-paragraph (or remove the binding to M-q) for modes in which visual-line-mode is turned on, but to re-enable it for those in which I am still using the auto-fill-mode? Thanks!

3

3 Answers

7
votes
(defun maybe-fill-paragraph (&optional justify region)
  "Fill paragraph at or after point (see `fill-paragraph').

Does nothing if `visual-line-mode' is on."
  (interactive (progn
         (barf-if-buffer-read-only)
         (list (if current-prefix-arg 'full) t)))
  (or visual-line-mode
      (fill-paragraph justify region)))

;; Replace M-q with new binding:
(global-set-key "\M-q" 'maybe-fill-paragraph)

Instead of using global-set-key, you can also rebind M-q only in specific modes. (Or, you could change the global binding, and then bind M-q back to fill-paragraph in a specific mode.) Note that many modes are autoloaded, so their keymap may not be defined until the mode is activated. To set a mode-specific binding, I usually use a function like this:

(add-hook 'text-mode-hook
  (defun cjm-fix-text-mode ()
    (define-key text-mode-map "\M-q" 'maybe-fill-paragraph)
    (remove-hook 'text-mode-hook 'cjm-fix-text-mode)))

(The remove-hook isn't strictly necessary, but the function only needs to run once.)

5
votes

you can use an advise for this.

For your .emacs:

(defadvice fill-paragraph (around disable-for-visual-line-mode activate)
  (unless visual-line-mode
    ad-do-it))

This will change fill-paragraph to do nothing when visual-line-mode is on. You can also add an error if you prefer that.

2
votes

visual-line-mode has its own keymap: visual-line-mode-map. I recommend rebinding M-q only in that keymap.

The map is defined as part of startup, so you don’t need eval-after-load. Just disable the binding in that mode:

(define-key visual-line-mode-map [remap fill-paragraph] 'ignore)