Emacs: Upcase Sentences

By Xah Lee. Date: . Last updated: .

Here's emacs command to fix letter case of sentences. That is, any letter after a period (full stop), question mark, exclamation, will be capitalized.

This saves you typing. You can keep typing without pressing Shift to type uppercase letters. After you finished typing a paragraph, you can press a button and have the letters capitalized.

(defun xah-upcase-sentence ()
  "Upcase first letters of sentences of current text block or selection.

URL `http://ergoemacs.org/emacs/emacs_upcase_sentence.html'
Version 2020-12-08"
  (let ($p1 $p2)
    (if (use-region-p)
        (setq $p1 (region-beginning) $p2 (region-end))
        (if (re-search-backward "\n[ \t]*\n" nil "move")
              (setq $p1 (point))
              (re-search-forward "\n[ \t]*\n"))
          (setq $p1 (point)))
          (re-search-forward "\n[ \t]*\n" nil "move")
          (setq $p2 (point)))))
        (narrow-to-region $p1 $p2)
        (let ((case-fold-search nil))
          ;; after period or question mark or exclamation
          (goto-char (point-min))
          (while (re-search-forward "\\(\\.\\|\\?\\|!\\)[ \n]+ *\\([a-z]\\)" nil "move")
            (upcase-region (match-beginning 2) (match-end 2))
            (overlay-put (make-overlay (match-beginning 2) (match-end 2)) 'face 'highlight))
          ;; after a blank line, after a bullet, or beginning of buffer
          (goto-char (point-min))
          (while (re-search-forward "\\(\\`\\|• \\|\n\n\\)\\([a-z]\\)" nil "move")
            (upcase-region (match-beginning 2) (match-end 2))
            (overlay-put (make-overlay (match-beginning 2) (match-end 2)) 'face 'highlight))
          ;; for HTML. first letter after tag
               (eq major-mode 'xah-html-mode)
               (eq major-mode 'html-mode)
               (eq major-mode 'sgml-mode)
               (eq major-mode 'nxml-mode)
               (eq major-mode 'xml-mode)
               (eq major-mode 'mhtml-mode))
            (goto-char (point-min))
                (re-search-forward "\\(<h[1-6]>[ \n]?\\|<p>[ \n]?\\|<li>\\|<dd>\\|<td>[ \n]?\\|<br ?/?>[ \n]?\\|<figcaption>[ \n]?\\)\\([a-z]\\)" nil "move")
              (upcase-region (match-beginning 2) (match-end 2))
              (overlay-put (make-overlay (match-beginning 2) (match-end 2)) 'face 'highlight))))))))

The following are often useful together:

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode

ELisp Examples

Xah Commands

Text Transform Under Cursor

Commands Do thing-at-point

Command to Insert Things

Script Examples