Emacs: Toggle Letter Case 📜

By Xah Lee. Date: . Last updated: .

Solution: Toggle Letter Case

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

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

URL `http://xahlee.info/emacs/emacs/emacs_toggle_letter_case.html'
Created: 2020-06-26
Version: 2024-06-17"
  (interactive)
  (let ((deactivate-mark nil) xbeg xend)
    (if (region-active-p)
        (setq xbeg (region-beginning) xend (region-end))
      (save-excursion
        (skip-chars-backward "[:alnum:]")
        (setq xbeg (point))
        (skip-chars-forward "[:alnum:]")
        (setq xend (point))))
    (when (not (eq last-command this-command))
      (put this-command 'state 0))
    (cond
     ((equal 0 (get this-command 'state))
      (upcase-initials-region xbeg xend)
      (put this-command 'state 1))
     ((equal 1 (get this-command 'state))
      (upcase-region xbeg xend)
      (put this-command 'state 2))
     ((equal 2 (get this-command 'state))
      (downcase-region xbeg xend)
      (put this-command 'state 0)))))

Give it a easy key, such as Ctrl+9. 〔see Emacs Keys: Define Key

Toggle Previous Letter Case

Another issue, not related to emacs, but related to efficiency of Shift key, is that the conventional way of typing capital letter using the Shift key is inefficient. You have to hold it, type a letter, then release it. (For detail about the Shift key problem, see Keyboard Design: Ban Shift Key.)

A better way to type capital letters, is to have a designated key, so that, when pressed, the previous letter is capitalized. (alternatively, press this key first, then next letter key pressed is capitalized. This is like a Compose key. 〔see Alt Graph Key, Compose Key, Dead Key〕 )

This is better because:

Here's the command.

(defun xah-toggle-previous-letter-case ()
  "Toggle the letter case of the letter to the left of cursor.

URL `http://xahlee.info/emacs/emacs/emacs_toggle_letter_case.html'
Created: 2015-12-22
Version: 2026-01-06"
  (interactive)
  (let ((case-fold-search nil))
    (backward-char)
    (cond
     ((looking-at "[[:lower:]]") (upcase-region (point) (1+ (point))))
     ((looking-at "[[:upper:]]") (downcase-region (point) (1+ (point)))))
    (forward-char)))

For this to work, you need to assign a easy key for this. For example, if you have a ergodox keyboard 〔see Best Keyboards for Emacs〕, set it to a thumb key.

If you have a normal PC keyboard, you could set the right Shift to something such as F20, then bind F20 to the command.

For how to remap keys in OS, see: Keyboard Tutorial: Layout, Keybinding, Key Macro ⌨.