【问题标题】:ELISP interactive function with both prefix argument and user input as optional arguments具有前缀参数和用户输入作为可选参数的 ELISP 交互式函数
【发布时间】:2019-12-28 20:12:07
【问题描述】:

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

P -- 原始形式的 arg 前缀。不做 I/O。 ... s -- 任意文本,在 minibuffer 中读取并作为字符串返回...提示。

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

(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)))

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

【问题讨论】:

    标签: function arguments lisp elisp optional


    【解决方案1】:

    这个函数如何[交互地]接受前缀参数和用户输入?

    它没有——没有获得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

    要将多个参数传递给命令,请连接各个字符串,并用换行符分隔它们。

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

    (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 来生成交互式参数(这可能涉及也可能不涉及提示用户)。

    【讨论】:

    • 干得好。我弄错了关于由换行符分隔的多个参数的部分,并且 No I/O 仅适用于前缀参数,而不适用于其他参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2017-02-04
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多