【问题标题】:Adding hook on elisp function在 elisp 函数上添加钩子
【发布时间】:2014-03-19 02:26:07
【问题描述】:

我正在使用 Emacs。

有什么方法可以在函数上添加钩子吗?

假设有一个markdown-export函数。

它旨在将 HTML 文件导出到当前工作的“markdown 文件”所在的当前目录。

但是,我想将 HTML 文件导出到另一个目录。如何在不修改 Emacs markdown 插件 (markdown-mode.el) 的情况下做到这一点?

这是markdown-mode.el的导出函数:

(defun markdown-export (&optional output-file)
  "Run Markdown on the current buffer, save to file, and return the filename.
If OUTPUT-FILE is given, use that as the filename.  Otherwise, use the filename
generated by `markdown-export-file-name', which will be constructed using the
current filename, but with the extension removed and replaced with .html."
  (interactive)
  (unless output-file
    (setq output-file (markdown-export-file-name ".html")))
  (when output-file
    (let* ((init-buf (current-buffer))
           (init-point (point))
           (init-buf-string (buffer-string))
           (output-buffer (find-file-noselect output-file))
           (output-buffer-name (buffer-name output-buffer)))
      (run-hooks 'markdown-before-export-hook)
      (markdown-standalone output-buffer-name)
      (with-current-buffer output-buffer
        (run-hooks 'markdown-after-export-hook)
        (save-buffer))
      ;; if modified, restore initial buffer
      (when (buffer-modified-p init-buf)
        (erase-buffer)
        (insert init-buf-string)
        (save-buffer)
        (goto-char init-point))
      output-file)))

================================================ =======================

我已建议将导出的 HTML 保存在临时目录中 这是代码。

(defadvice markdown-export (around set-temp-path-for-exported-file activate)
  (ad-set-arg 0 (format "%s/%s" "~/.emacs.d/temp-dir" (file-name-nondirectory buffer-file-name)))
  ad-do-it)

谢谢!!!!!!!!!!!!!!!

【问题讨论】:

    标签: emacs lisp elisp


    【解决方案1】:

    在这种情况下,您不需要挂钩此函数,因为它已经接受文件名作为参数,不幸的是它在交互调用时不接受文件名。作为一种解决方法,您可以在函数周围定义一个简单的包装器,如下所示

    (defun my-markdown-export (&optional file)
      (interactive (list (ido-read-file-name "Export as: ")))
      (markdown-export file))
    

    【讨论】:

      【解决方案2】:

      advice 机制有点像为任意函数提供挂钩,但在这里您可以使用 实际 挂钩,以及直接满足您要求的函数参数。

      所以你可以:

      (a) 将任意输出文件名传递给函数。

      (b) 使用提供的markdown-before-export-hook 来设置您需要的任何变量(乍一看类似于output-fileoutput-bufferoutput-buffer-name)。

      【讨论】:

      • 谢谢。解决方案(a)很容易。但我正在考虑制作自己的 markdown-before-export-hook。因为我不想在需要挂钩时依赖提供的挂钩,例如 markdown-before-export-hook。你能告诉我如何制作自己的钩子吗?
      • 如果您询问的是建议系统,手册中有记录:C-h i g (elisp) Advising Functions RET。但是,如果有更清洁(和更简单)的替代方案,请不要使用它,就像这个问题一样。
      • 我也不确定我是否理解您所说的“我正在考虑制作自己的 markdown-before-export-hook”是什么意思。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多