天天看點

emacs-async庫簡要說明async簡介API說明

Table of Contents

  • 1. async簡介
  • 2. API說明
    • 2.1. (async-start START-FUNC FINISH-FUNC)
    • 2.2. (async-get FUTURE)
    • 2.3. (async-start-process NAME PROGRAM FINISH-FUNC &rest PROGRAM-ARGS)
    • 2.4. (async-ready FUTURE)
    • 2.5. (async-wait FUTURE)
    • 2.6. (async-inject-variables INCLUDE-REGEXP &optional PREDICATE EXCLUDE-REGEXP)

async簡介

async包提供了在Emacs中異步執行elisp代碼的一種方式

API說明

(async-start START-FUNC FINISH-FUNC)

async-start會建立一個Emacs子程序,并由子程序執行START-FUNC. 子程序執行完START-FUNC後,START-FUNC的傳回值會作為參數觸發父程序Emacs中的FINISH-FUNC調用.

下面是個例子:

(async-start
           ;; What to do in the child process
           (lambda ()
             (message "This is a test")
             (sleep-for )
             )

           ;; What to do when it finishes
           (lambda (result)
             (message "Async process done, result should be 222: %s" result)))
           

這裡FINISH-FUNC一般為帶一個參數的函數,但也可以是nil或直接不填. 這種情況下可以在後期使用`async-get’函數擷取`START-FUNC’的值. (在調用async-get函數前,會有一個*emacs*程序一直存在)

若對`START-FUNC’的傳回值不感興趣,則`FINISH-FUNC’的值可以為’ingore

async-start傳回一個process對象,該process對象被稱為 FUTURE

(async-get FUTURE)

若`async-start’中的FINISH-FUNC為nil或沒填時,可以使用`async-get’函數來阻塞式地擷取`START-FUNC’的傳回值.

這裡參數`FUTURE’為`async-start’或`async-start-process’的傳回process對象.

下面是一個例子

(let ((proc (async-start
                       ;; What to do in the child process
                       (lambda () (message "This is a test") (sleep-for ) ))))

            (message "I'm going to do some work here") ;; ....

            (message "Waiting on async process, result should be 222: %s"
                     (async-get proc)))
           

(async-start-process NAME PROGRAM FINISH-FUNC &rest PROGRAM-ARGS)

使用`PROGRAM-ARGS’作為指令參數異步執行`PROGRAM’. 當`PROGRAM’執行完畢後,以該process對象為參數調用`FINISH-FUNC’.

`PROGRAM’執行時的目前工作目錄被設定為變量`DEFAULT-DIRECTORY’的值.

若`FINISH-FUNC’為nil,則`async-start-process’一直等到`PROGRAM’執行完畢後才傳回 FUTURE 對象

(async-ready FUTURE)

判斷`FUTURE’是否執行完畢

(async-wait FUTURE)

等待FUTURE,直到其執行完畢

(async-inject-variables INCLUDE-REGEXP &optional PREDICATE EXCLUDE-REGEXP)

該函數會生成一個`setq’語句,該語句常用于為子Emacs程序置所有比對`INCLUDE-REGEXP’和符合`PREDICATE’判定的變量為目前主Emacs中的值.

若設定了`EXCLUDE-REGEXP’,則标示了哪些變量即使符合INCLUDE-REGEXP或PREDICATE的條件,也要排除在外.

例如

(async-start
           `(lambda ()
              (require 'smtpmail)
              (with-temp-buffer
                (insert ,(buffer-substring-no-properties (point-min) (point-max)))
                ;; Pass in the variable environment for smtpmail
                ,(async-inject-variables "\\`\\(smtpmail\\|\\(user-\\)?mail\\)-")
                (smtpmail-send-it)))
           'ignore)
           

繼續閱讀