Emacs: Toggle/Cycle Letter Case

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

Here's a command combines emac's letter-case-changing commands into one.

(defun xah-toggle-letter-case (φp1 φp2)
  "Toggle the letter case of current word or text selection.
Always cycle in this order: Init Caps, ALL CAPS, all lower.

In lisp code, φp1 φp2 are region boundary.
URL `http://ergoemacs.org/emacs/modernization_upcase-word.html'
Version 2015-04-09"
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (let ((ξbds (bounds-of-thing-at-point 'word)))
       (list (car ξbds) (cdr ξbds)))))
  (let ((deactivate-mark nil))
    (when (not (eq last-command this-command))
      (put this-command 'state 0))
     ((equal 0 (get this-command 'state))
      (upcase-initials-region φp1 φp2)
      (put this-command 'state 1))
     ((equal 1  (get this-command 'state))
      (upcase-region φp1 φp2)
      (put this-command 'state 2))
     ((equal 2 (get this-command 'state))
      (downcase-region φp1 φp2)
      (put this-command 'state 0)))))

This command is also in ErgoEmacs Keybinding.

Emacs has several user level commands for changing letter case. They are: upcase-wordAlt+u】, downcase-wordAlt+l】, capitalize-wordAlt+c】.

There are also “region” versions for each: upcase-regionCtrl+x Ctrl+u】, downcase-regionCtrl+x Ctrl+l】, capitalize-region, and also upcase-initials-region. (Note: for elisp programing, there are also these functions: upcase, capitalize, downcase, upcase-initials.)

One problem with these commands is that you need to move your cursor to the beginning of the word first. For example, if you have the text “THat”, and your cursor is on the “a”, and you call downcase-word, but it doesn't do anything because it only start at the cursor point to end of word. It would be nice if it'll just automatically perform the operation on the whole word.

Another problem is that it does not consider the final result. For example, if you have “oncE upon a time …”, and you select the whole sentence and call upcase-initials-region, it becomes “OncE Upon A Time …”. Note the capital E is not automatically lowered. For elisp programing, the orthogonal precision is nice, but as user commands, it is better to change the whole sentence.

Also, these commands have a “-word” and “-region” variants, great for precision in elisp programing but not smart as user commands. It would be nice if emacs automatically choose the right command depending whether there is text selection.

Like it? Buy Xah Emacs Tutorial.
blog comments powered by Disqus