Hyphenating Word Phrases

Some word phrases should be hyphenated. For example, you should write “an end-to-end solution” rather than “end to end solution.”1 If you’re like me, you almost always forget about the hyphenation initially and just type “end to end” without stopping to think about the hyphenation. It’s really a pain to have to go back and add them manually. Sometimes it’s easier to just delete the phrase and retype it correctly.

I’ve done this often enough that I realized it was time to automate hyphenating the phrase after the fact. I wrote a bit of Elisp but it seemed a little too complicated so I simplified things and came up with this:

(defun jcs-dashify ()
  "Place hyphens between words in region."
  (interactive)
  (unless (use-region-p)
    (error "No region specified"))
  (replace-regexp "[ \n]+" "-" nil (region-beginning) (region-end)))

Now all I have to do is select the phrase and call jcs-dashify. As with most extensions like this, jcs-dashify is simple but helps reduce friction in my work flow. I’m sure you can do this sort of thing with most (decent) editors but Emacs makes it simple and natural. As Magnar Sveen says, one of the great about Emacs is its extensibility.

Footnotes:

1

The rules are a bit complex but this article is a good guide.

This entry was posted in General and tagged , . Bookmark the permalink.

4 Responses to Hyphenating Word Phrases

  1. Fuco says:

    I have similar set of functions, but I find selecting the regions as quite a slowdown. Rather, I pass in an argument of how many words *backward* I want to affect. So, for example C-3 M-c will capitalize third word from point (useful when writing German), C-2 M-U will upcase two last letters, and so on.

    (Of course, they also work with active region, if one exist :P)

    • jcs jcs says:

      Good idea. Nice if you realize you should have hyphenated right after you type the phrase. Definitely worth adding to the code. Of course, I usually discover the missing hyphen during editing so, as you say, I need to be able to specify the region explicitly too.

  2. (Reposting my comment since WordPress served up a blank page on submission, being unclear about its acceptance. That was hours ago and the comment never showed up.)

    What do you think about this version which doesn’t use a region? I works with a prefix argument, too.

    http://pastebin.com/wKEj8X7m

    Here’s a demo GIF of it in action:

    http://i.imgur.com/cJJSGev.gif

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>