Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from camelcase to _ in emacs

Is there an emacs function to convert a camel-cased word to underscore? Something, like:

longVariableName

M-x to-underscore

long_variable_name

like image 498
David Nehme Avatar asked Feb 15 '12 05:02

David Nehme


People also ask

What is CamelCase conversion?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.


2 Answers

Use the string-inflection package, available on MELPA, or at https://github.com/akicho8/string-inflection.

Useful keyboard shortcuts, copied from https://www.emacswiki.org/emacs/CamelCase :

;; Cycle between snake case, camel case, etc.
(require 'string-inflection)
(global-set-key (kbd "C-c i") 'string-inflection-cycle)
(global-set-key (kbd "C-c C") 'string-inflection-camelcase)        ;; Force to CamelCase
(global-set-key (kbd "C-c L") 'string-inflection-lower-camelcase)  ;; Force to lowerCamelCase
(global-set-key (kbd "C-c J") 'string-inflection-java-style-cycle) ;; Cycle through Java styles
like image 112
Nik Avatar answered Oct 17 '22 13:10

Nik


I use the following for toggling between camelcase and underscores:

(defun toggle-camelcase-underscores ()
  "Toggle between camelcase and underscore notation for the symbol at point."
  (interactive)
  (save-excursion
    (let* ((bounds (bounds-of-thing-at-point 'symbol))
           (start (car bounds))
           (end (cdr bounds))
           (currently-using-underscores-p (progn (goto-char start)
                                                 (re-search-forward "_" end t))))
      (if currently-using-underscores-p
          (progn
            (upcase-initials-region start end)
            (replace-string "_" "" nil start end)
            (downcase-region start (1+ start)))
        (replace-regexp "\\([A-Z]\\)" "_\\1" nil (1+ start) end)
        (downcase-region start (cdr (bounds-of-thing-at-point 'symbol)))))))
like image 25
ens Avatar answered Oct 17 '22 12:10

ens