Converting from camelcase to _ in emacs

前端 未结 7 1980

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

longVariableName

M-x to-underscore

7条回答
  •  时光取名叫无心
    2021-02-05 03:28

    @ens' answer was close, but a little buggy for me on Emacs 26.1. I fixed the bug and added the ability, via C-u prefix arg, to specify if you want the first letter of camel case to be lower case:

    (defun toggle-camelcase-underscores (first-lower-p)
      "Toggle between camelcase and underscore notation for the
    symbol at point. If prefix arg, C-u, is supplied, then make first
    letter of camelcase lowercase."
      (interactive "P")
      (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
                (replace-string "_" " " nil start end)
                (upcase-initials-region start end)
                (replace-string " " "" nil start end)
                (when first-lower-p
                  (downcase-region start (1+ start))))
            (replace-regexp "\\([A-Z]\\)" "_\\1" nil (1+ start) end)
            (downcase-region start (cdr (bounds-of-thing-at-point 'symbol)))))))
    

提交回复
热议问题