Switching identifier naming style between Camel Case and C style in Emacs
Friday 11 December 2009 @ 10:50 pm

There are several naming styles for identifiers used in programming. Some use-dashes-between-words (e.g. Lisp), others MashWordsTogetherAndCapitalizeThem (most often called Camel Case), and a third one puts_underscores_between_characters_and_converts_everything_to_lower_case (sometimes called “C style”).

Often I have to convert code from one naming convention to another. When I have to do that this usually happens with languages that often use both styles, e.g. C/C++ or even PHP and Ruby. For those cases I’ve written an Emacs Lisp function that can convert the identifier at point from C style naming to Camel Case style and back. It detects the current style by looking for an underscore. Here’s the code:

  1. (defun motoggleidentifiernamingstyle ()
  2.   "Toggles the symbol at point between C-style naming,
  3. e.g. `hello_world_string', and camel case,
  4. e.g. `HelloWorldString'."
  5.   (interactive)
  6.   (let* ((symbolpos (boundsofthingatpoint 'symbol))
  7.          casefoldsearch symbolatpoint cstyle regexp func)
  8.     (unless symbolpos
  9.       (error "No symbol at point"))
  10.     (saveexcursion
  11.       (narrowtoregion (car symbolpos) (cdr symbolpos))
  12.       (setq cstyle (stringmatchp "_" (bufferstring))
  13.             regexp (if cstyle "\\(?:\\_<\\|_\\)\\(\\w\\)" "\\([A-Z]\\)")
  14.             func (if cstyle
  15.                      'capitalize
  16.                    (lambda (s)
  17.                      (concat (if (= (matchbeginning 1)
  18.                                     (car symbolpos))
  19.                                  ""
  20.                                "_")
  21.                              (downcase s)))))
  22.       (gotochar (pointmin))
  23.       (while (researchforward regexp nil t)
  24.         (replacematch (funcall func (matchstring 1))
  25.                        t nil))
  26.       (widen))))

The code was inspired by a question on StackOverflow about this topic.

Comments (4) - Posted in Programming by  

 4 responses to “Switching identifier naming style between Camel Case and C style in Emacs”