在org-mode中,attachment:格式的链接导出为html后,路径一直是错的?

我发现一个问题:在org文档中,如果使用attachment作为链接前缀,导出html后,对应的链接路径总是错误的。(在emacs内部,用C-x C-o是能访问到对应文件的。)

我举个例子:

  • 文件层级
note/
|---- demo.org
|---- Attachment/test/
|-------- new.txt
  • demo.org中的节点,以及内容是这样的:
** a node
   :PROPERTIES:
   :DIR:      Attachment/test/
   :END:

[[attachment:new.txt]]
  • 使用C-c C-e h h导出
  • 导出后,链接内容并没有使用attachment dir里的路径
<a target="_blank" href="new.txt">new.txt</a>
...

我预想中,上面链接的路径应该是Attachment/test/new.txt

另外,配置中关于org和attachment的相关设置(我觉得跟配置可能没关系):

;; ...
(setq org-directory "~/note")
;; ...
(unless (version< emacs-version "27.0")
  (progn
    (setq org-attach-dir-relative t)
    (setq org-attach-preferred-new-method 'dir)
    (setq org-attach-use-inheritance t)))

版本:emacs27.1,org-mode9.3,Win10 2004

是我的使用姿势出问题了吗?求解答!

1赞

我是这样解决的,重写了一下org-attach中的函数

(defun my/org-attach-expand-links (_)
  (save-excursion
    (while (re-search-forward "attachment:" nil t)
      (let ((link (org-element-context)))
	(when (and (eq 'link (org-element-type link))
		   (string-equal "attachment"
				 (org-element-property :type link)))
	  (let* ((description (and (org-element-property :contents-begin link)
				   (buffer-substring-no-properties
				    (org-element-property :contents-begin link)
				    (org-element-property :contents-end link))))
		 (file (org-element-property :path link))
                 (fullpath (org-attach-expand file))
                 (current-dir (file-name-directory (or default-directory
                                                        buffer-file-name)))
                 (relpath (file-relative-name fullpath current-dir))
		 (new-link ;;(format "[[file:%s][file:%s]]" relpath relpath)))
                           (org-link-make-string
			    (concat "file:" relpath)
			    description)))
	    (goto-char (org-element-property :end link))
	    (skip-chars-backward " \t")
	    (delete-region (org-element-property :begin link) (point))
	    (insert new-link)))))))

(remove-hook 'org-export-before-parsing-hook 'org-attach-expand-links)
(add-hook 'org-export-before-parsing-hook 'my/org-attach-expand-links)

1赞