Is there any way to convert camel-cased names to use underscores in emacs?

8

1

For instance, I want to convert "CamelCasedName" to "camel_cased_name". Is there a way to do this in emacs?

Jason Baker

Posted 2010-04-01T14:00:09.850

Reputation: 6 382

4The short answer to any question of the form "Is there any way to _____ in emacs?" is Always "YES" – Brian Postow – 2010-04-09T21:33:19.620

Answers

4

This small bit of code from this page, with a wrapper function and an underscore replacing the hyphen with an underscore, could easily be turned into a command to do that. (Check that it treats leading caps to suit you):

Sample EmacsLisp code to un-CamelCase a string (from http://www.friendsnippets.com/snippet/101/):

(defun un-camelcase-string (s &optional sep start)
  "Convert CamelCase string S to lower case with word separator SEP.
Default for SEP is a hyphen \"-\".

If third argument START is non-nil, convert words after that
index in STRING."
  (let ((case-fold-search nil))
    (while (string-match "[A-Z]" s (or start 1))
      (setq s (replace-match (concat (or sep "-") 
                                             (downcase (match-string 0 s))) 
                                     t nil s)))
    (downcase s)))

JRobert

Posted 2010-04-01T14:00:09.850

Reputation: 6 128

4

Emacs has glasses-mode which displays camelcase names with underscores in between. (See also http://www.emacswiki.org/emacs/GlassesMode).

If you want to actually change the text of the file M-x query-replace-regexp is probably suitable.

Allen

Posted 2010-04-01T14:00:09.850

Reputation: 170

3

Moritz Bunkus wrote an elisp function to toggle between CamelCase and c_style

Natan Yellin

Posted 2010-04-01T14:00:09.850

Reputation: 572

the package string-inflection is more complete now: https://github.com/akicho8/string-inflection (note that there's also string-inflection-camelize-lower to change hello_world to helloWorld).

– Ehvince – 2014-05-07T12:42:51.643

2

I was able to do this across a whole file quickly with just a query replace regexp.

The search pattern is \([a-z]+\)\([A-Z]\)\([a-z]+\) and the replacement is \1_\,(downcase \2)\3.

The replacement pattern uses elisp right in the pattern. This requires Emacs 22 or later.

In emacs documentation style:

M-C-% \([a-z]+\)\([A-Z]\)\([a-z]+\) RET \1_\,(downcase \2)\3

derekv

Posted 2010-04-01T14:00:09.850

Reputation: 121

2

For display purposes only, you can use this:

M-x glasses-mode

If you want a script which actually converts the text, I imagine you'd have to write some elisp. That question is better asked on stack overflow.

Trey Jackson

Posted 2010-04-01T14:00:09.850

Reputation: 3 731