Set default ess R session to the default Orgmode R session

UPDATE: for an updated version that even works with inline source code use Improved function to set default ess R session to the default Orgmode R session.

I write most of my R code on orgmode files which I then tangle or convert to R markdown (using ox-ravel). In orgmode we can specify the default R session globally, at the structure level, or at code block level (see properties). However, when you go to a edit buffer by pressing C-c ' on a code block this information is lost and, if there are multiple R sessions running (which I always seem to have), we need to specify which R session to use. This happens every single time we go to an edit buffer since once we return to orgmode it forgets our selection.

I tried searching in google for a solution without luck. I even tried to get chatgpt to write elisp code to fix this but kept generating bogus code using made up, undefined functions. Therefore, decided to spend some time writing my own solution and came up with the following.


(defvar tmprs nil)
(defun get-org-current-rsession()
  "When you are in an org file get the current R session based on global header, subtree, property or source code :session property whichever is relevant"
  (setq tmprs (cdr (assoc :session (nth 2 (org-babel-get-src-block-info t)))))
  )

(defun set-ess-R-process()
  "set the process to session stored in tmprs variable"
  (message "Setting R session to %s" (eval tmprs))
  (setq ess-local-process-name (process-name (get-buffer-process tmprs)))
  )


(advice-add 'org-edit-src-code :before #'get-org-current-rsession)
(advice-add 'org-edit-src-code :after #'set-ess-R-process)

The function get-org-current-rsession finds the current R session in the orgmode file for the code block we are working on. This R session may specified with a code block specific header argument, at the heading level with org-mode properties, or at the buffer level if we use the #+PROPERTY keyword.

The function set-ess-R-process associates this R session to the temporary edit buffer.

In order to execute these 2 function automatically I’m using advice-add to execute the first function when we run C-c ' and the second after we are in the edit buffer.

Now whenever I go to the edit buffer to edit some R code I can execute any line of code (for example, using C-c C-j) directly to the correct R session no matter how many R session I have running.

Fred Gruber
Fred Gruber
Senior Principal Scientist

My research interests include causal inference, Bayesian networks, causal discovery, machine learning.