代码块执行前如何检查 :file 参数是否合法,例如检查对应目录是否存在?

在使用 ditaa 生成图片的时候,如果对应的目录不存在会进行报错。 有没有类似 org-babel-after-execute-hook 这样的hook,可以在代码执行前进行相关检查?

Use advice around `org-babel-execute-src-block’. Reported here.

Advice version:

(defun check-file-exists-advice (orig-fun
                                 &optional arg
                                 info
                                 params)
  ;; Copied from ob-core.el. May not be compatible.
  (let* ((org-babel-current-src-block-location
	  (or org-babel-current-src-block-location
	      (nth 6 info)
	      (org-babel-where-is-src-block-head)
	      ;; inline src block
	      (and (org-babel-get-inline-src-block-matches)
		   (match-beginning 0))))
	 (info (if info
		   (copy-tree info)
		 (org-babel-get-src-block-info)))
	 (merged-params (org-babel-merge-params (nth 2 info) params))) 
    (when (cdr (assoc :file merged-params))
      (unless (file-exists-p (cdr (assoc :file merged-params)))
        (error "File does not exist"))))
  (funcall orig-fun arg info params))

(advice-add 'org-babel-execute-src-block :around #'check-file-exists-advice)

1 个赞

Thanks a lot.

I modified the code and it work expected, thanks again.