Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emacs: visual-line-mode and fill-paragraph

Tags:

emacs

elisp

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!

like image 578
hatmatrix Avatar asked Sep 12 '09 21:09

hatmatrix


People also ask

How do you wrap lines in Emacs?

On a text terminal, Emacs indicates line wrapping by displaying a ' \ ' character at the right margin. Most commands that act on lines act on logical lines, not screen lines. For instance, C-k kills a logical line.

What is visual line mode Emacs?

Visual Line mode is often used to edit files that contain many long logical lines, so having a fringe indicator for each wrapped line would be visually distracting. You can change this by customizing the variable visual-line-fringe-indicators . By default, Emacs only breaks lines after whitespace characters.


2 Answers

(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.)

like image 99
cjm Avatar answered Sep 24 '22 23:09

cjm


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.

like image 20
mihi Avatar answered Sep 23 '22 23:09

mihi