19.3 输入函数

本节介绍了和读取有关的一些 Lisp 函数及变量。

在以下的函数中,stream 表示一个输入流(详情查阅前一节)。如果 stream 为 nil 或被 略去,那么会默认将其设置为变量 standard-input 的值。

如果读取中出现 未结束的 列表,向量,或字符串,则会抛出 end-of-file 错误。

Function: read &optional stream

该函数从stream中读取一个Lisp表达式的文本表示,并返回对应的Lisp对象。这是最基础的Lisp输入函数。

Function:read-from-string string &optional start end

该函数从字符串string中读取一个Lisp表达式的文本表示。该函数返回一个点对,其CAR为读取的表达式,其CDR为一个整数,该整数指明了下一个待读取字符的位置。

如果提供了参数 start,那么将会读取 start 后的字符串(其中第一个字符的索引为0)。如果你提供了参数 end,那么将会强制 Lisp 在end位置停止读取,就好像end之后啥都没有。

举个例子:

(read-from-string "(setq x 55) (setq y 5)")
     ⇒ ((setq x 55) . 11)
(read-from-string "\"A short string\"")
     ⇒ ("A short string" . 16)

;; Read starting at the first character.
(read-from-string "(list 112)" 0)
     ⇒ ((list 112) . 10)
;; Read starting at the second character.
(read-from-string "(list 112)" 1)
     ⇒ (list . 5)
;; Read starting at the seventh character,
;;   and stopping at the ninth.
(read-from-string "(list 112)" 6 8)
     ⇒ (11 . 8)

Variable: standard-input

这个变量指明了默认的输入流。当 read 的stream参数为nil时,会默认使用该变量的值作为数据流。该变量的默认值为 t,也就是使用 minibuffer。

Variable: read-circle

若该变量为 non-nil,那么读取函数将支持循环结构和共享结构。详情查阅循环对象。其默认值为 t。

在批处理模式下,当向 Emacs 进程的 标准输入/输出流 读取或输出时,有时需要确保将逐字读取/写入任何任意二进制数据,执行或不执行换行符与 CR-LF 对之间的转换。在 POSIX 标准下并不存在这样的问题,但在 MS-Windows 和 MS-DOS 下会存在这样的问题。下面的函数允许你控制Emacs进程中任何标准流的 I/O模式。

Function: set-binary-mode stream mode

将流切换到 二进制 或 文本 模式。若参数mode 为 non-nil,则切换到二进制模式,否则切换到文本模式。参数stream的值可以为 stdin,stdout 或 stderr。这个参数会刷新接下来读取或输出的模式,并返回更改前的模式。在 POSIX 标准下,该函数始终返回 non-nil 值,并仅刷新流读取模式。

最后更新于