Friday, July 14, 2006

Emacs Soft Line Wrap

Today I had to fill out a few forms at work. Web-based forms, requiring long paragraph answers to certain questions.

So naturally I used Emacs (the One True Editor) to edit the paragraphs, then cut-and-pasted them into the web.

The result looked like pure crap. Why? Because I'd set Emacs to wrap lines after 68 characters (trust me, this is exactly the right number). Emacs, in its text-based wisdom, presumes that everyone I'm sending the document to will want to see it wrapped at 68 characters, so it inserts hard carriage returns at every word wrap.

This meant that every time a line extended beyond 68 characters
Emacs put in a carriage return, which the idiot web-based form
input program interpreted as meaning that it should put in a
hard return as well.

Just like that last paragraph. Annoying, huh?

So I had to edit out all of the returns by hand. An annoying task, though it wasn't all that hard with Emacs' macro feature.

Then today I found the answer to my prayers (I pray about very minor things sometimes) in Penguin Pete's Blog. It's an Emacs Lisp script (if you don't know, don't worry) that inserts 'soft' line breaks. That is, it wraps words on the screen, but not in the file. Pete explains how to set it up, all you need is longlines.el, the basic script, and a few lines in your ~/.emacs file.

A couple of additions to what Pete wrote:

  • If you edit program files, e.g. Fortran code, you'll want to turn off the longlines mode before you edit the file. I expect that there is a clever way to do this, but I've got no clue how. So I commented out the line:
    (add-hook 'text-mode-hook 'longlines-mode)
    Now when I want to edit a file and use soft line wrap, I just open the file normally, and then enter
    M-x longlines-mode to toggle the longlines mode on (or off). (For Emacs novices, M-x means "meta-key x." This usually means holding down the "Alt" key and pressing the "x," but you can also press "Esc," release, and then press "x."
  • You can byte-compile the script and then put it into the ordinary list directory. Just enter
    M-x byte-compile-file,
    give Emacs the location of longlines.el, and press return. The file longlines.elc will be produce in about a second, and you can then copy it wherever you please.
  • Blogger itself has some issues with hard line wraps, especially if the wrap occurs in the middle of an HTML command. So this is especially nice for writing long Blogger posts and then cutting and pasting them into Blogger.

Thanks again to Penguin Pete for pointing this out.