If we have
* Header 1
Some contents.
Is there a way to programmatically kill the contents of Header 1
so that it remains like:
* Header 1
?
If we have
* Header 1
Some contents.
Is there a way to programmatically kill the contents of Header 1
so that it remains like:
* Header 1
?
There isn't a command for deleting the subtree (i.e., the head line and all its contents), but there is a command to mark
it. We can use that to get what you want:
(defun clear-subtree ()
(interactive)
(org-mark-subtree) ;; mark the current subtree
(forward-line) ;; move point forward, so the headline isn't in the region
(delete-region (region-beginning) (region-end)) ;; delete the rest
)
org-mark-subtree
puts point at the start of the current subtree (i.e., on the headline) and mark at the end.
– Tobias
Jan 25 '18 at 22:44
There are many ways of removing the contents of a headline. Taylor gave you already a straight-forward text editing method which is good and which you should perhaps accept as an answer.
But there is more. Orgmode has a well defined syntax and also routines for parsing and printing.
So one way to change the contents of your org buffer is:
org-element-parse-buffer
org-element-map
org-element-interpret-data
I give you an example for your special case of removing the content of Header 1
. The following code returns a string with the text of buffer test.org
modified with the contents of Header 1
removed.
(with-current-buffer "test.org"
(let* ((data (org-element-parse-buffer)))
(org-element-map data 'headline
(lambda (el)
(when (equal
(car-safe (org-element-property :title el))
"Header 1")
(setf (nthcdr 2 el) nil) ;; Here we remove the contents from this headline.
)))
(org-element-interpret-data data)))
Which method you should use strongly depends on the actual use-case.
It seems you can use org-map-entries
to do this as well:
#+BEGIN_SRC emacs-lisp :results none
(let ((MATCH t)
(SCOPE nil)
(SKIP nil)
(spacing nil))
(org-map-entries
(lambda ()
(let ((name (nth 4 (org-heading-components))))
(if (string= name "Header 1")
(save-restriction
(org-mark-subtree)
(forward-line)
(delete-region (region-beginning) (region-end))
))
)) MATCH SCOPE SKIP))
#+END_SRC
* Header 1
Content of header 1
* Header 2
Content of header 2
If you run the source code block with C-c C-c
, it will remove Content of header 1
under Header 1
.