help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

title-case function


From: Paul W. Rankin
Subject: title-case function
Date: Sun, 21 Apr 2019 13:56:26 +1000
User-agent: mu4e 1.0; emacs 26.2

Happy Easter to those who celebrate it!

I couldn't find a title-case function I considered good enough, so I wrote the one below. Please take a look and let me know if there are any edge cases I've missed or improvements you might have.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(defcustom title-case-minor-words
'("the ""a" "an" "and" "but" "for" "of" "or" "nor" "is" "as" "in" "to" "into"
   "v" "vs" "de")
 "List of minor word strings that should be downcased in titles.
These words should be less than four characters."
 :type '(repeat string)
 :group 'editing-basics)

(defun title-case-region (beg end)
 "Convert region from BEG to END to Title Case.
First and last words are capitalized unconditionally, as are
words following colons and dashes. Words in list
`title-case-minor-words' are downcased."
 (interactive "r")
 (save-excursion
   (let (last-word)
     (goto-char end)
     (forward-word -1)
     (setq last-word (point))
     (capitalize-word 1)
     (goto-char beg)
     (unless (looking-at "\\b")
       (forward-word -1))
     (capitalize-word 1)
     (while (< (point) last-word (point-max))
       (if (looking-at "[:\x2013\x2014]")
           (capitalize-word 1)
         (skip-syntax-forward "-." last-word)
(if (looking-at (concat "\\b" (regexp-opt title-case-minor-words)
                                 "\\b"))
             (downcase-word 1)
           (capitalize-word 1)))))))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--
https://www.paulwrankin.com



reply via email to

[Prev in Thread] Current Thread [Next in Thread]