【发布时间】:2016-12-06 05:13:45
【问题描述】:
如何在异步调用期间使用cl-letf 或类似方法覆盖符号的函数值?我想在调用start-process 或start-process-shell-command 后停止显示缓冲区,而是取回一个字符串。
这是一个简化的示例,其中绑定display-buffer 适用于同步版本,但不适用于异步版本。另外,我已将 lexical-binding 设置为 true。
(defun tst-fun-sync (url)
(call-process "wget" nil "*wget*" nil url "-O" "-")
(with-current-buffer "*wget*"
(display-buffer (current-buffer))))
(defun tst-fun-async (url)
(set-process-sentinel
(start-process "wget" "*wget*" "wget" url "-O" "-")
#'(lambda (p _m)
(when (zerop (process-exit-status p))
(with-current-buffer (process-buffer p)
(display-buffer (current-buffer)))))))
(defun tst-fun-no-display (fun &rest args)
(cl-letf (((symbol-function 'display-buffer)
#'(lambda (&rest _ignored)
(message "%s" (buffer-string)))))
(apply fun args)))
;; The first has desired result, but not the second
;; (tst-fun-no-display 'tst-fun-sync "http://www.stackoverflow.com")
;; (tst-fun-no-display 'tst-fun-async "http://www.stackoverflow.com")
【问题讨论】:
-
使用
shell-command-to-string怎么样?例如,(replace-regexp-in-string "\n" "" (shell-command-to-string "date"))不需要显示缓冲区来使用它——也就是说,在我可以看到的示例中,不需要使用display-buffer。 -
您可能还对能够以字符串形式捕获所有进程输出的进程过滤器感兴趣。 gnu.org/software/emacs/manual/html_node/elisp/…
标签: asynchronous emacs elisp lexical-scope