我尝试了两种不同的方式来编写我的函数。我决定编写一个小函数来转换为驼峰大小写并返回 this elisp string library .起初通过搜索我找到了this tutorial在点替换东西并实现此功能:
; use string manipulation library to switch between camel and snake (s.el)
(defun my_test ()
"test"
(interactive)
;; get current selection or word
(let (bds p1 p2 inputStr resultStr)
;; get boundary
(if (use-region-p)
(setq bds (cons (region-beginning) (region-end) ))
(setq bds (bounds-of-thing-at-point 'word)) )
(setq p1 (car bds) )
(setq p2 (cdr bds) )
;; grab the string
(setq inputStr (buffer-substring-no-properties p1 p2) )
(setq resultStr (s-lower-camel-case inputStr))
(message inputStr)
(delete-region p1 p2 ) ; delete the region
(insert resultStr) ; insert new string
)
)
这不会修改
resultStr
正如预期的那样,只是吃饭inputStr
在那里。我对此不明白的是,当我评估(使用
M-:
)(setq resultStr (s-lower-camel-case "other_string"))
我得到了预期的结果("otherString"
)我什至尝试了一种不同的(对我的目的来说更好的)方法来编写受 this SO question 启发的函数。 :
(defun change-word-at-point (fun)
(cl-destructuring-bind (beg . end)
(bounds-of-thing-at-point 'word)
(let ((str (buffer-substring-no-properties beg end)))
(delete-region beg end)
(insert (funcall fun str)))))
(defun my_test_camel ()
(interactive)
(change-word-at-point 's-lower-camel-case))
遇到同样的问题。这让我觉得
s-lower-camel-case
有问题函数(或我如何调用它)但是当如上所述从 eval 调用时有效编辑:修改第一个函数以包含 let 语法,请参阅注释
编辑#2:这两个功能都可以正常工作,答案已被接受,因为它提供了一个更好的选择,包括符号信息和正确的书写方式。我的问题是由于haskell-mode而导致的测试。新问题是 here
最佳答案
这是一个替代定义。您需要通过 let
进行本地绑定(bind)的评论是正确的.请注意,如果该版本处于事件状态,则此版本使用该区域,否则使用 bounds-of-thing-at-point
如果没有区域处于事件状态,则在该点获取单词:
(defun word-or-region-to-lcc ()
"Convert word at point (or selected region) to lower camel 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 (s-lower-camel-case text)))))
如果你不关心使用区域的选项,你可以绑定(bind)
text
本地到 (thing-at-point 'symbol)
而不是调用 buffer-substring-no-properties
.更新。原来你可以使用
(thing-at-point 'symbol)
而不是 (thing-at-point 'word)
获取蛇盒的完整符号。
关于emacs - 你如何编写一个 emacs lisp 函数来替换一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25188206/