Kyle Meyer <k...@kyleam.com> writes:
> This came up somewhat recently, and there were a couple of suggestions: > https://orgmode.org/list/CA+pajW+jViTPE2cwTZ=thvzyhjrt000-bb6jk2nte4p9ufb...@mail.gmail.com/T/#u Thanks for the information! That was really helpful. I retrieved some information from that post and wrote the following function.I would really appreciate if someone could give me some feedback on this function. #+begin_src elisp (defun org-babel-get-block-as-string (name) "Get the content of a code block with name NAME as an string. This function also considers the code blocks stored in `org-babel-library-of-babel'." (interactive) (catch 'found ;; Let's first search the code block in the current buffer. (let ((position (org-babel-find-named-block name)) content) (if position (progn (setq content (save-excursion (goto-char position) ;; This function uses `org-babel-expand-src-block' ;; instead of `org-edit-src-code' so that the ;; value of the header arguments :prologue and the ;; :epilogue are included as the content of the ;; code block. (org-babel-expand-src-block))) (throw 'found content)))) ;; If the code block doesn't exist in the current buffer, then ;; let's search in `org-babel-library-of-babel'. (let ((library-block-data (alist-get (intern name) org-babel-library-of-babel)) content) (if library-block-data (progn (setq content (nth 1 library-block-data)) (throw 'found content)))) ; If the code block is not found, then an error is shown. Throwing ; an error is important since this makes code blocks which uses ; this function as the :epilogue and :prologue don't be evaluated ; in the scenario that a code block is not found. (error (format "The code block with name \"%s\" was not found" name)))) #+end_src * Minimal example Below, there is an example that shows how to use this function. We can use =printf= as it follows #+NAME: test-printf #+begin_src bash printf "%s\n" "printf-foo" printf "%s\n" "printf-bar" #+end_src #+RESULTS: test-printf #+begin_example printf-foo printf-bar #+end_example We can use =echo= as it follows #+NAME: test-echo #+begin_src bash echo echo-foo echo echo-bar #+end_src #+RESULTS: test-echo #+begin_example echo-foo echo-bar #+end_example We can use both of them as it follows #+HEADER: :prologue (org-babel-get-block-as-string "test-printf") #+HEADER: :epilogue (org-babel-get-block-as-string "test-echo") #+begin_src bash echo a #+end_src #+RESULTS: #+begin_example printf-foo printf-bar a echo-foo echo-bar #+end_example -- Greetings, Rodrigo Morales. IRC: rdrg109 (freenode)