elisp 函数将字符串大小写从骆驼更改为大写蛇案例

时间:2021-04-04 23:35:48

标签: replace emacs uppercase

我花了 3 个小时试图找出在不同情况下修改字符串的方法,例如isFailedUpgradeIS_FAILED_UPGRADE

我已经到了可以在指向 var text 处获取字符串的地步,但不知道如何将字符串 text 更新为所需的大小写。

(defun change-case ()
  (interactive)
  (let* ((bounds (if (use-region-p)
                     (cons (region-beginning) (region-end))
                   (bounds-of-thing-at-point 'symbol)))
         (text   (buffer-substring-no-properties (car bounds) (cdr bounds))))
    (when bounds
      (delete-region (car bounds) (cdr bounds))
      (insert (change-case-helper text)))))

# the following code is rubbish 
(defun change-case-helper (text)
  (let ((output ""))
    (dotimes (i (length text))
      (concat output (char-to-string (aref text i))))
    output))

由于我自己正在学习一些 emacs 函数,所以我更喜欢自己编写这个函数,而不是使用现有的魔法函数。


好吧,又过了 2 个小时,我想我已经想通了:

(defun change-case ()
  (interactive)
  (let* ((bounds (if (use-region-p)
                     (cons (region-beginning) (region-end))
                   (bounds-of-thing-at-point 'symbol)))
         (text   (buffer-substring-no-properties (car bounds) (cdr bounds))))
    (when bounds
      (delete-region (car bounds) (cdr bounds))
      (insert (change-case-helper text)))))

(defun change-case-helper (text)
  (when (and text (> (length text) 0))
    (let ((first-char (string-to-char (substring text 0 1)))
          (rest-str (substring text 1)))
      (concat (if (upcasep first-char) (string ?_ first-char) (string (upcase first-char)))
              (change-case-helper rest-str))))
  )

(defun upcasep (c) (and (= ?w (char-syntax c)) (= c (upcase c))))

还是觉得这很别扭,请评论告诉我是否有更好的编写此函数的方法。

0 个答案:

没有答案