9

I often limit or unlimit the evaluation of specific code blocks in org-mode babel using :eval header argument.

Here's an example:

#+BEGIN_SRC emacs-lisp :results value scalar :eval no
(+ 1 1)
#+END_SRC

#+RESULTS:
: 2

I toggle the code blocks between :eval no and :eval n (or delete :eval no completely) by hand.

#+PROPERTY: eval no is convenient, but is not suited for each code block.

Are there any better ways to toggle the :eval status handy, like below?

C-c C-t     (org-todo)
Rotate the TODO state of the current item among
(unmarked) -> TODO -> DONE
6

I've come up with a relatively nice solution, which relies on the org-in-block-p function, which I'd recommend taking a look. Add the following code to you init.el file:

(defun org-toggle-src-eval-no ()
  "Will toggle ':eval no' on the src block begin line"

  (defun in-src-block-p ()
    "Returns t when the point is inside a source code block"
    (string= "src" (org-in-block-p '("src"))))

  (defun beginning-src ()
    "Find the beginning of the src block"
    (let ((case-fold-search t)) (search-backward "#+BEGIN_SRC")))

  (defun toggle-eval-no ()
    "Handles the toggling of ' :eval no'"
     (save-excursion
      (end-of-line)
      (let ((case-fold-search t)) (search-backward "#+BEGIN_SRC")
       (if (search-forward " :eval no" (line-end-position) "f")
           (replace-match "")
         (insert " :eval no")
         ))))

  (if (in-src-block-p) (toggle-eval-no)))

(defun add-org-toggle-src-key ()
  (local-set-key (kbd "C-c t") (lambda () (interactive) (org-toggle-src-eval-no))))

(add-hook 'org-mode-hook 'add-org-toggle-src-key)

This defines the function org-toggle-src-eval-no and it should do exactly what you want; anytime you're inside a code block, it will toggle the presence of :eval no. I have bound it to C-c t, but feel free to map it to whatever you'd like. Happy org-ing.

  • 1
    Amazing! It's really great! This is exactly what i wanted! I did not expect to get the solution so quickly. Meanwhile I noticed just one trivial thing. When I have 2 code blocks, if I C-c t at the beginning of a line of second #+BEGIN_SRC block, the first code block get toggled. Perhaps I should add (move-end-of-line nil) before both of (search-backward "#+BEGIN_SRC") ? – RUserPassingBy Jul 11 '15 at 7:32
  • 1
    Excellent point. I've updated my answer to include (end-of-line) before the search, which moves the point to the end of the #+BEGIN_SRC if you're before it (without limiting any other functionality). Let me know if you're still having problems. – GJStein Jul 11 '15 at 9:37
  • I thank you for your code! It's really great!! – RUserPassingBy Jul 11 '15 at 16:07

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.