Search code examples
stringemacstitle-case

Convert string to title case - Emacs Lisp


I am looking for an elisp function that accepts a string and returns the same in title case (i.e., all words capitalized, except for "a", "an", "on", "the", etc.).

I found this script, which requires a marked region.

Only, I need a function that accepts a string variable, so I can use it with replace-regex. I would love to see a version of the above script that can accept either or...


Solution

  • I'd say that the script you linked to does a good job at title casing. You can use it as-is.

    That leaves us with two more questions:

    • How can we make it accept a string?
    • How can we write a function which accepts both a string or a (marked) region?

    Working with strings in Emacs is idiomatically done in temporary buffers which are not displayed. You could write a wrapper like this:

    (defun title-capitalization-string (s)
      (with-temp-buffer
        (erase-buffer)
        (insert s)
        (title-capitalization (point-min)
                              (point-max))
        (buffer-substring-no-properties (point-min)
                                        (point-max))))
    

    Now, for a function which magically does what you mean, consider something like this:

    (defun title-capitalization-dwim (&optional arg)
      (interactive)
      (cond
       (arg
        (title-capitalization-string arg))
       ((use-region-p)
        (title-capitalization-string
         (buffer-substring-no-properties (region-beginning)
                                         (region-end))))
       (t
        (title-capitalization-string
         (buffer-substring-no-properties (point-at-bol)
                                         (point-at-eol))))))
    

    It accepts an optional argument, or an active region or falls back to the text on the current line. Note that this function is not really useful when used interactively, because it doesn't show any effects. Hat tip also to https://www.emacswiki.org/emacs/titlecase.el

    License

    I put all this code under the Apache License 2.0 and the GPL 2.0 (or later at your option) in addition to the site's default license.