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

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

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

2 Answers 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."
    (goto-char (point-max))
    (while (re-search-backward "#\\+END_SRC" nil t)
      (let ((reg-end (point))
        (re-search-backward "#\\+BEGIN_SRC" nil t)
        (setq reg-beg (1+ (line-end-position)))
        (delete-region reg-beg reg-end)))))
  • Works very well! Thanks for sharing! :D Jul 3, 2019 at 21:52

I use code like this to do that.

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

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

(defun scimax-ob-clear-all-results ()
  "Clear all results in the buffer."
    (goto-char (point-min))
    (while (org-babel-next-src-block)
  • 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. Jul 3, 2019 at 21:52
  • 3
    Indeed, I misread the first question! I updated my answer with a similar approach to remove the contents. Jul 3, 2019 at 22:12
  • Thanks for the update, the code reads well! Jul 4, 2019 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, 2019 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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