你如何编写emacs lisp函数来替换单词?

时间:2014-08-07 17:01:40

标签: emacs elisp

我尝试过两种不同的方式来编写我的函数。我决定编写一个小函数来转换为驼峰大小写并返回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模式。新问题是here

1 个答案:

答案 0 :(得分:9)

这是另一种定义。评论是正确的,您需要通过let进行本地绑定。请注意,如果该区域处于活动状态,则此版本会使用该区域,或者如果没有区域处于活动状态,则使用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)))))

如果您不关心使用区域的选项,则可以将text本地绑定到(thing-at-point 'symbol),而不是调用buffer-substring-no-properties

更新。事实证明,您可以使用(thing-at-point 'symbol)而不是(thing-at-point 'word)来获取蛇案的完整符号。

相关问题