Skip to content

Instantly share code, notes, and snippets.

@Fuco1
Created October 30, 2016 13:12
Show Gist options
  • Save Fuco1/e86fb5e0a5bb71ceafccedb5ca22fcfb to your computer and use it in GitHub Desktop.
Save Fuco1/e86fb5e0a5bb71ceafccedb5ca22fcfb to your computer and use it in GitHub Desktop.
Archive subtrees under the same hierarchy as original in the archive files.
(defadvice org-archive-subtree (around fix-hierarchy activate)
(let* ((fix-archive-p (and (not current-prefix-arg)
(not (use-region-p))))
(afile (org-extract-archive-file (org-get-local-archive-location)))
(buffer (or (find-buffer-visiting afile) (find-file-noselect afile))))
ad-do-it
(when fix-archive-p
(with-current-buffer buffer
(goto-char (point-max))
(while (org-up-heading-safe))
(let* ((olpath (org-entry-get (point) "ARCHIVE_OLPATH"))
(path (and olpath (split-string olpath "/")))
(level 1)
tree-text)
(when olpath
(org-mark-subtree)
(setq tree-text (buffer-substring (region-beginning) (region-end)))
(let (this-command) (org-cut-subtree))
(goto-char (point-min))
(save-restriction
(widen)
(-each path
(lambda (heading)
(if (re-search-forward
(rx-to-string
`(: bol (repeat ,level "*") (1+ " ") ,heading)) nil t)
(org-narrow-to-subtree)
(goto-char (point-max))
(unless (looking-at "^")
(insert "\n"))
(insert (make-string level ?*)
" "
heading
"\n"))
(cl-incf level)))
(widen)
(org-end-of-subtree t t)
(org-paste-subtree level tree-text))))))))
@Thaodan
Copy link

Thaodan commented Jan 12, 2024

I put in the advice in a small emacs package that has a function to enable and disable the advice:
https://gitlab.com/Thaodan/emacs.d-lisp/-/blob/master/org-archive-subtree-hierarchy.el

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment