代码之家  ›  专栏  ›  技术社区  ›  Mike H-R

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

  •  10
  • Mike H-R  · 技术社区  · 10 年前

    我尝试了两种不同的方法来编写函数。我决定编写一个小函数,将其转换为驼色大小写,然后返回 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调用时

    EDIT:修改第一个函数以包含let语法,请参见注释

    编辑#2:这两个函数都正常工作,答案已经被接受,因为它提供了一个更好的替代方案,包括符号信息和正确的书写方式。我的问题是测试,这是由于haskell模式。新问题是 here

    1 回复  |  直到 7 年前
        1
  •  13
  •   Dan    10 年前

    这是另一个定义。注释是正确的,您需要通过 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 'word) 获取蛇案的完整符号。