带有前缀参数和用户输入作为可选参数的 ELISP 交互函数

ELISP interactive function with both prefix argument and user input as optional arguments

在 ELISP 中,interactive codes 的文档提到:

P -- Prefix arg in raw form. Does not do I/O. ... s -- Arbitrary text, read in the minibuffer and returned as a string ... Prompt.

我假设我可以编写一个带有可选前缀参数的函数,如:

(defun some-function (&optional prefix)
    (interactive "P")
    ...
)

或带有用户输入的函数,如:

(defun some-function (user-argument)
  (interactive "sProvide an argument: ")
  ...
)

但不是两者。然后我找到了 Org-mode 函数 org-match-sparse-tree,我可以用 C-u C-c \ 调用它,其中前缀参数限制匹配打开 org-mode 标题,我仍然提示匹配.源代码在下面,我找不到变量 match 是如何赋值的:

(defun org-match-sparse-tree (&optional todo-only match)
  "..."
  (interactive "P")
  (org-agenda-prepare-buffers (list (current-buffer)))
  (let ((org--matcher-tags-todo-only todo-only))
    (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
           org--matcher-tags-todo-only)))

此函数如何同时接受前缀参数和用户输入?

How does this function [interactively] take both prefix argument and user input?

它不是 -- match 参数未获得,因此是 nil。您看到的是随后以 nil 值作为参数调用 (org-make-tags-matcher match) 的效果:

(defun org-make-tags-matcher (match)
  "..."
  (unless match
    ;; Get a new match request, with completion against the global
    ;; tags table and the local tags in current buffer.
    (let ((org-last-tags-completion-table
           (org-tag-add-to-alist
            (org-get-buffer-tags)
            (org-global-tags-completion-table))))
      (setq match
            (completing-read
             "Match: "
             'org-tags-completion-function nil nil nil 'org-tags-history))))
  ...)

函数可以接受多个interactive参数。

参见C-hf interactive

To pass several arguments to the command, concatenate the individual strings, separating them by newline characters.

该帮助中的第一个示例说明了这一点:

(defun foo (arg buf) "Doc string" (interactive "P\nbbuffer: ") .... )

这在 (elisp)Using Interactive 中进行了详细说明 -- 您链接到的文档中的上一级:

It may be a string; its contents are a sequence of elements
separated by newlines, one for each argument(1).  Each element
consists of a code character (*note Interactive Codes::) optionally
followed by a prompt (which some code characters use and some
ignore).  Here is an example:

     (interactive "P\nbFrobnicate buffer: ")

The code letter ‘P’ sets the command’s first argument to the raw
command prefix (*note Prefix Command Arguments::).  ‘bFrobnicate
buffer: ’ prompts the user with ‘Frobnicate buffer: ’ to enter the
name of an existing buffer, which becomes the second and final
argument.

不过,您应该完整阅读该文档——您可以做更复杂的事情,包括编写任意 elisp 来生成交互式参数(这可能涉及也可能不涉及提示用户)。