用edit-indirect替换org-capture?

我的日志文件note.org用这么个格式:

* [2022-01-21 周五]
test1
* [2022-01-29 周六]
test2
* [2022-01-28 周五]
** test

用org-capture自动生成日期,写个模板不够,还要配个函数:

(org-capture-templates
   '(("j" "Write journal" plain (file+function my/journal-file my/journal-goto-today)
      nil :empty-lines-after 1)))

(defun my/journal-goto-today ()
    (let ((heading (format-time-string "* [%Y-%m-%d %a]")))
      (goto-char (point-max))
      (unless (re-search-backward (regexp-quote heading) nil t)
        (goto-char (point-max))
        (or (bolp) (insert "\n"))
        (insert heading "\n")) ;; TODO 取消时,不要改变原文件 (C-c C-k)
      (org-end-of-subtree)))

我都会写函数了,为啥还要学它的模板?然后尝试用edit-indirect实现capture效果:

(defun my/daily-capture ()
  (interactive)
  (with-current-buffer (find-file-noselect "d:/notes.org")
    (let ((mode-func major-mode)
          (heading (format-time-string "* [%Y-%m-%d %a]")))
      (goto-char (point-max))
      (if (re-search-backward (regexp-quote heading) nil t)
          (with-current-buffer (edit-indirect-region (point) (+ (length heading) (point)) t)
            (funcall mode-func))
        (insert "\n")
        (with-current-buffer (edit-indirect-region (1- (point-max)) (point-max) t)
          (funcall mode-func)
          (insert "\n" heading))))
    (add-hook 'edit-indirect-after-commit-functions (lambda (&rest _) (save-buffer)))))

相比org-capture,这个实现:

  1. C-c C-k取消时,不改变原文件(org-capture的实现,原文件里插入了日期,一个空heading)
  2. 在capture buffer里,可以显示当前一级heading,编辑期间有用的提示
  3. 不限于org-mode,可以用于任何文件格式
  4. 代码量也差不多嘛

如果上面代码太多太啰嗦,可以看这个简单实现,capture内容往任意文件末尾追加:

(defun my/append-capture ()
  (interactive)
  (with-current-buffer (find-file-noselect "d:/note.org")
    (let ((mode-func major-mode))
      (insert "\n")
      (with-current-buffer (edit-indirect-region (point-max) (point-max) t)
        (funcall mode-func)))
    (add-hook 'edit-indirect-after-commit-functions (lambda (&rest _) (save-buffer)))))

上面函数写得仓促,还有待改进,道友们看看这用法是否顺手,欢迎分享新思路

1 个赞

org caputre 模板插入日期用%U就可以了

不仅仅是插入日期,先判断是否已有,有则取用,没有才插入,就需要写代码了

datetree不行吗?

          ("j" "Journal in journal.org" entry ; 记录日志, 日期在前,org自动按年-月-日方式组织
                 (file+olp+datetree +org-capture-journal-file)
                 "* %U %? \n")