在elisp函数上添加钩子

时间:2014-03-19 02:26:08

标签: emacs lisp elisp

我正在使用Emacs。

有没有办法在函数上添加钩子?

假设有降价输出功能。

它旨在将HTML文件导出到当前正在运行的标记文件的当前目录中。 exsits。

但是,我想将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)

由于!!!!!!!!!!!!!!

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

advice机制有点像任意函数的钩子,但是你可以使用实际的钩子,以及直接满足你需求的函数参数。

所以你可以:

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

(b)使用提供的markdown-before-export-hook来设置您需要的变量(一目了然output-fileoutput-bufferoutput-buffer-name)。