UP | HOME

+emacs+删除掉空的agenda-block

[2025-01-05 周日 19:54]

在使用org-agenda-custom-commands时,有时会创建agenda-block。如果你是用的org-ql-block,那么在未query到结果时会为空;但如果你用的org-agenda,则可能会因为一些原因留有空的block。

根据reddit的一个帖子,以下函数可以在某个block有小于2行不以空格开头时,删除掉这个block。
(标题为一行,分割线上的空格为一行)

(defun org-agenda-delete-empty-blocks ()
  "Remove empty agenda blocks.
  A block is identified as empty if there are fewer than 2
  non-empty lines in the block (excluding the line with
  `org-agenda-block-separator' characters)."
  (when org-agenda-compact-blocks
    (user-error "Cannot delete empty compact blocks"))
  (setq buffer-read-only nil)
  (save-excursion
    (goto-char (point-min))
    (let* ((blank-line-re "^\\s-*$")
           (content-line-count (if (looking-at-p blank-line-re) 0 1))
           (start-pos (point))
           (block-re (format "%c\\{10,\\}" org-agenda-block-separator)))
      (while (and (not (eobp)) (forward-line))
        (cond
         ((looking-at-p block-re)
          (when (< content-line-count 2)
            (delete-region start-pos (1+ (pos-bol))))
          (setq start-pos (point))
          (forward-line)
          (setq content-line-count (if (looking-at-p blank-line-re) 0 1)))
         ((not (looking-at-p blank-line-re))
          (setq content-line-count (1+ content-line-count)))))
      (when (< content-line-count 2)
        (delete-region start-pos (point-max)))
      ;; 上面这个函数是针对agenda-block在最下方写的,会让agenda中更改todo状态后的文本消失。
      (goto-char (point-min))
      ;; The above strategy can leave a separator line at the beginning
      ;; of the buffer.
      (when (looking-at-p block-re)
        (delete-region (point) (1+ (pos-eol))))))
  (setq buffer-read-only t))
(add-hook 'org-agenda-finalize-hook #'org-agenda-delete-empty-blocks)

当然,我们也可以自定义 blank-line-re 的值,用来匹配其他文本内容。

▲ 编辑于 [2025-01-06 周一 09:54] | © Published by Emacs 31.0.50 (Org mode 9.7.19) on [2025-01-08 周三 23:29] | RSS