4

Say I have this code which shows usage examples of mapcar

(mapcar #'1+ (list 10 20 30)) ; ⇒ (11 21 31)

(mapcar (lambda (it)
          (* 2 it))
        (list 0 1 2 3))
;; ⇒ (0 2 4 6)

(require cl-lib)
(cl-mapcar #'+
           '(1 2 3)
           '(10 20 30))
;; ⇒ (11 22 33)

I may be keeping that code somewhere written so that I can use it on a tutorial or so that whenever I forget how mapcar works, I can quickly read the code.

Now suppose I want to update some of the examples in the code. For example, I may change (list 0 1 2 3) in the second example to some other list. Right after I change the example, the corresponding result comment is then outdated. The result comment need to be updated as well. So I evaluate the form, copy the result, and replace the old result in the comment with new result. Is there a package I can use to help me do that all easily and less tediously? This is a different problem than problems that the litable or ielm package solve because this is simply about updating existing example code.

Right now what I use is:

(defun my-insert-eval-last-sexp ()
  (interactive)
  (let ((beg (point)))
    (let ((current-prefix-arg '(4)))
      (call-interactively 'eval-last-sexp))
    (goto-char beg)
    (if (looking-back ")")
        (insert " ; "))
    (insert "⇒ ")
    (move-end-of-line 1)))

which still isn't enough because it simply adds the result comment rather than updating an old one, and has a bug of odd stuff getting inserted when the form evaluates to a number:

(+ 1 2)
;; ⇒ 3 (#o3, #x3)
4

2 回答 2

2

好吧,我不确定我是否要鼓励这种事情;-),但这会让你更接近你想要做的事情,IIUC:

 (defun my-insert-eval-last-sexp ()
   (interactive)
   (let ((this-command  'eval-print-last-sexp))
     (save-excursion (eval-last-sexp-1 t)))
   (when (looking-back ")") (insert " ; "))
   (insert "⇒ ")
   (move-end-of-line 1))
  1. 你不需要保存点然后明确地回到它——使用save-excursion.

  2. 您不需要绑定前缀 arg 并以交互方式调用命令。只需直接调用它(或其辅助函数),传递您想要的 arg。

  3. 您需要调整行为以防止它认为这是该命令的第二次出现,这就是导致它打印八进制等数字信息的原因。绑定可以做到这let一点(但这是一个丑陋的小技巧)。

于 2013-08-17T02:59:29.130 回答
2

您的函数所做的相应事情是在 org-mode 中实现的,即 org-babel。

参见 Info, Org Mode, 14 使用源代码

于 2013-08-17T07:27:53.127 回答