I am using a command which affects the entire buffer, replacing all the ocurrences of a given expression

(goto-char (point-min)) (replace-string "foo" "bar")

Is it possible to apply a command like this only to the ocurrences outside an org-babel source block? That is, only the first foo on this example text should be replaced by bar, but not the second one:

* Test
testing foo

#+begin_src lisp
(setq foo 3)

1 Answer 1


The following is a modification of replace string programmatically to avoid replacing inside source blocks:

#+begin_src elisp
    (goto-char (point-min))
    (while (re-search-forward "foo" nil t)
      (unless (org-in-src-block-p) (replace-match "bar"))))

You may use search-forward instead of re-search-forward which searches for regular expressions.

You may also use header arguments to pass the strings as variables.

  • I didn't know of the existence of org-in-src-block-p. Thanks! Jul 30, 2017 at 15:34

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.