如何正确使用org-capture的功能选项?

How to use the function option of org-capture correctly?

我想使用 function 选项在 orgmode 捕获模板中动态打开正确的文件:

("a" "foo" plain
    (function my-visit-timestamped-file)
    "<some content>")

函数my-visit-timestamped-file定义为

(defun my-visit-timestamped-file ()
  (interactive)
  (let
      ((theDate (format-time-string "%Y%m%d-%H%M.org")))
  (find-file (concat "<some_path>" theDate))))

如果我 运行 捕获模板 a,emacs 在缓冲区中打开文件 <some_path>theDate 并使用该文件打开捕获缓冲区。 因此,我的 window 被分成 2 个显示相同内容的缓冲区。

能否以某种方式更改函数 my-visit-timestamped-file,以便不打开缓冲区但 org capture 仍然获得正确的文件 pointer/file 句柄?

您可能需要 find-file-noselect 而不是 find-file。请注意 org-capture-templates 的文档是这样说的:

         (function function-finding-location)
            Most general way: write your own function which both visits
            the file and moves point to the right location

因此您可能想要添加一些代码以转到文件中的正确位置(我猜是 (point-min)(point-max))。这可能看起来像这样:

(defun my-visit-timestamped-file ()
  (interactive)
  (let* ((the-date (format-time-string "%Y%m%d-%H%M.org"))
         (the-buffer (find-file-noselect (expand-file-name the-date "/some/path/"))))
    (with-current-buffer the-buffer
      (goto-char (point-min)))
    the-buffer))

@jpkotta 的回答为我指明了正确的方向。 错误消失了,但捕获缓冲区的内容总是粘贴到我当前正在编辑的缓冲区中。

在 org-mode 邮件列表的旧线程中,我找到了问题的答案。函数应该是:

(defun my-visit-timestamped-file ()
  "Visit a new file named by the current timestamp"
  (interactive)
  (let* (
        (curr-date-stamp (format-time-string "%Y%m%d-%H%M.org"))
        (file-name (expand-file-name curr-date-stamp "/some/path/")))
  (set-buffer (org-capture-target-buffer file-name))
  (goto-char (point-max))))

Link 到邮件列表线程:https://lists.gnu.org/archive/html/emacs-orgmode/2013-11/msg00676.html