5

This is tangentially related to my previous question on dealing with asynchronous babel scripts. Currently I have to manually specify the name of the src block the babel function is in:

#+name: elisp-block-name
#+begin_src emacs-lisp :var src="elisp-block-name"
(format "My src-block is %s" src)
#+end_src

#+RESULTS: elisp-block-name
: My src-block is elisp-block-name

Obviously this is prone to error so it would be nice to generate it programmaticaly. Is there any environment/variables always passed to tangled block that indicates this or do I need to just call some elisp for my :var block?

8

You can use the org-babel-get-src-block-info function. I add a few examples to show that it indeed yields back the name of the block that is executing the code, even if called by other blocks.

I first define a block echoing its src block name

#+NAME: blockA
#+BEGIN_SRC emacs-lisp :results value
  (format "I am %s" (nth 4 (org-babel-get-src-block-info)))
#+END_SRC

#+RESULTS: blockA
: I am blockA

Now I use the org-sbe function to call blockA from within the lisp code of another block. The code running in blockA correctly identifies itself as blockA.

#+NAME: blockB
#+BEGIN_SRC emacs-lisp :results value
(org-sbe blockA)
#+END_SRC

#+RESULTS: blockB
: I am blockA

Org mode CALL syntax also yields the correct result...

#+CALL: blockB() :results value

#+RESULTS:
: I am blockA

... as does running the code in table formulas

#+NAME: tableA
| col1        | col2        |
|-------------+-------------|
| I am blockA | I am blockA |
#+TBLFM: @2$1='(org-sbe blockA)::@2$2='(org-sbe blockB)
3

I was not able to use org-babel-get-src-block-info to declare a variable from the header line. It did work using org-element-context however:

#+NAME: a-name
#+BEGIN_SRC emacs-lisp :var block-name=(org-element-property :name (org-element-context))
  block-name
#+END_SRC

#+RESULTS: a-name
: a-name

Calling that source code block from somewhere else results in the variable being set with the name from the new context:

#+NAME: another-name
#+CALL: a-name()

#+RESULTS: another-name
: another-name

If the code block is called without setting #+NAME:, the variable will be an empty string or nil.

#+CALL: a-name()

#+RESULTS:

This is different from the accepted answer but might be what some people are looking for.

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.