2

Say you have an org file with several code blocks like the one below:

#+BEGIN_SRC jupyter-python :session py :results silent :async yes
stuff
more stuff
even more stuff
#+END_SRC

Question: Is there any function that would clear the contents of all code blocks, while leaving the code block declaration in place?

2

I do not know whether there is an existing function to clear all org source blocks, but here is a quick example of how to do it.

CAVEAT: This example does not check for broken source code blocks; e.g., the code assumes there is a matching beginning/ending.

(defun org-clear-src-blocks ()
"Clear src code blocks."
(interactive)
  (save-excursion
    (goto-char (point-max))
    (while (re-search-backward "#\\+END_SRC" nil t)
      (let ((reg-end (point))
            reg-beg)
        (re-search-backward "#\\+BEGIN_SRC" nil t)
        (setq reg-beg (1+ (line-end-position)))
        (delete-region reg-beg reg-end)))))
3

I use code like this to do that.

(defun scimax-ob-clear-all-contents ()
  "Clear all src-block contents in the buffer."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (org-babel-next-src-block)
      (org-edit-special)
      (delete-region (point-min) (point-max))
      (org-edit-src-exit))))

If you just want to remove all the results, I use this.

(defun scimax-ob-clear-all-results ()
  "Clear all results in the buffer."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (org-babel-next-src-block)
      (org-babel-remove-result))))
  • Your code looks very neat! I'm sorry if I am confused but I think your code is removing the results part of the code block, while I was looking for something to remove the contents (the code) inside the code block. – Guilherme Salomé Jul 3 at 21:52
  • 3
    Indeed, I misread the first question! I updated my answer with a similar approach to remove the contents. – John Kitchin Jul 3 at 22:12
  • Thanks for the update, the code reads well! – Guilherme Salomé Jul 4 at 12:21
  • 1
    @JohnKitchin: That was a very sensible misreading! I've often wanted to clear all results but never have I wanted to clear all code blocks. Maybe it's the Ikea effect? Maybe I feel more attached to the code I wrote than to the results the computer calculated? – Omar Jul 5 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.