![](/img/trans.png)
[英]Emacs: Define a function which loads the file where the function itself is defined
[英]How to define a function which repeats itself when passed an argument
有沒有簡單的方法來定義在傳遞參數時重復自身的函數?
例如,我定義了以下函數
(defun swap-sign ()
(interactive)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))
)
我想Cu swap-sign
呼叫swap-sign
的四倍。
我試過了
(defun swap-sign (&optional num)
(interactive)
(let ((counter 0)
(num (if num (string-to-number num) 0)))
(while (<= counter num)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))
(setq counter (1+ counter)))))
但Cu swap-sign
仍僅運行一次swap-sign(或更准確地說,while循環的主體)。 我猜是因為if num
不是測試num
是否為空字符串的正確方法。
我是在正確的軌道上嗎,還是有更好/更容易的方法來擴展swap-sign
?
(defun swap-sign (arg)
(interactive "p")
(dotimes (i arg)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))))
有關更多詳細信息,請參見interactive
特殊格式的文檔: Ch f interactive
RET 。
您需要通過添加“ p”作為交互式的參數規范來告訴emacs期望並傳遞參數(通過Mx apropos interactive
獲取文檔)。 在這里,我對您的代碼進行了最小的更改以使其正常工作-但是請注意,您不需要let / while來進行迭代,並且arg不需要是可選的。
(defun swap-sign (&optional num)
(interactive "p")
(let ((counter 1))
(while (<= counter num)
(search-forward-regexp "[+-]")
(if (equal (match-string 0) "-")
(replace-match "+")
(replace-match "-"))
(setq counter (1+ counter)))))
請注意,您不需要從字符串轉換參數-使用“ p”告訴emacs為您執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.