让 C-x C-e 支持被跨行注释的代码

C-x C-e (eval-last-sexp) 支持

;; (+ 1 2 3)

却不支持

;; (+ 1
;;    2
;;    3)

之前遇到这种情况就只能取消注释、执行、加上注释,有点儿烦。刚刚想了个一步到位的办法:

(define-advice elisp--preceding-sexp (:around (old-fun) multiline-comment)
  "Support sexp in multiline comment."
  (condition-case err
      (funcall old-fun)
    (scan-error
     (if (nth 4 (syntax-ppss))
         (let ((work-buffer (current-buffer))
               (temp-buffer (generate-new-buffer " *temp*"))
               found sexp error)
           (with-current-buffer temp-buffer
             (delay-mode-hooks (emacs-lisp-mode)))
           (save-excursion
             (comment-normalize-vars)
             (while (and (comment-beginning)
                         (not found))
               (let ((code (buffer-substring-no-properties
                            (point) (line-end-position))))
                 (with-current-buffer temp-buffer
                   (goto-char (point-min))
                   (insert code ?\n)
                   (goto-char (point-max))
                   (condition-case err
                       (setq sexp (funcall old-fun)
                             found t)
                     (scan-error (setq error err)))))
               (when (= -1 (forward-line -1))
                 (error "[email protected] error"))
               (goto-char (line-end-position))))
           (cond (found sexp)
                 (error (signal (car error) (cdr error)))
                 (t (error "[email protected] error"))))
       (signal (car err) (cdr err))))))
4 个赞

给我的 *scratch* 做做广告

找链接中。。。。

刚才在做测试的时候想到这个帖子,现在可以用 separedit 来实现:

(defun separedit/eval-last-sexp-in-comment ()
  (interactive)
  (let ((separedit-default-mode 'emacs-lisp-mode))
    (with-current-buffer (separedit)
      (prog1 (call-interactively #'eval-last-sexp)
        (execute-kbd-macro (kbd "C-c C-k"))))))
5 个赞

决定把这个函数纳入日常配置:

(keymap!
 :mode emacs-lisp-mode
 :prefix "C-x"
 "C-e" (lambda ()
         (interactive)
         (call-interactively
          (if (separedit--point-at-comment)
              #'separedit/eval-last-sexp-in-comment
            #'eval-last-sexp)))))

好评 :100: www