Nifty emacs hack: how to wrap only certain files
For a long time I've wanted some, but not all, text and html files to line-wrap automatically in emacs. For instance, it drives me nuts when I edit a system configuration file and it wraps each long line, or when I edit an html file containing lots of long links and it keeps wrapping between the <a and the href=. But for files which are mostly text (such as these blog entries), I want line wrapping.I'd been trying to do this with html-mode-hook and text-mode-hook, then checking the filename and calling (auto-fill-mode) if appropriate, but it wasn't working, because buffer-file-name isn't always defined at the time the mode hook is called. (No one seems to know why.) The buffer name seems to be defined at that point, but it doesn't contain path information so I can't say "Use wrapping for anything under ~/Docs" or "Don't wrap anything in /etc".
But with some help from sachac and the nice folks on #emacs I came up with a much better solution, and it's way simpler than the mode-hook approach: derived modes.
I set up two new modes, called html-wrap-mode and text-wrap-mode, which are the same as html-mode and text-mode except that they turn on auto-fill. Then I use the easy auto-mode-alist mechanism, which already does string matching on the filename, to call these modes, instead of the regular text and html modes, based on the extension or some other aspect of the file's pathname. Here's what I added to .emacs:
;; Want auto-fill-mode for some text and html files, but not all. ;; So define two derived modes for that, and we'll use auto-mode-alist ;; to choose them based on filename. (define-derived-mode html-wrap-mode html-mode "HTML wrap mode" (auto-fill-mode)) (define-derived-mode text-wrap-mode text-mode "Text wrap mode" (auto-fill-mode)) (setq auto-mode-alist (cons '("\\.blx$" . html-wrap-mode) (cons '("Docs/.*.html$" . html-wrap-mode) (cons '("Docs/" . text-wrap-mode) auto-mode-alist) ) ) )
Here's my current .emacs.
I wonder if vim has a way to do this?
[ 23:30 Jan 13, 2005 More linux/editors | permalink to this entry | ]