3

Suppose you're in org mode and working with source code.

Your point is currently inside a source block at some random position.

Is there an easy way to copy the body of source block (excluding #+begin_src <header args> and #+end_src)?

I was thinking of an automated, quick solution, like using a function.

The manual way for me to do this is to use mark-paragraph and then kill-ring-save.

But the latter unfortunately includes the last line of the source block, the #+end_src line.

I've played around with universal arguments -1 before mark-paragraph, but I couldn't manage to exclude the last line (#+end_src).

2
  • Welcome! What version of emacs and version of org-mode are you using? The answer(s) might change depending on the versions. Thanks!
    – Melioratus
    Jan 21 at 16:29
  • Please don't post an answer in the question. Post it as an answer. (You can accept your own answer.)
    – Drew
    Jan 21 at 21:36
2

You can get the body of the code block as a string by executing the following with point in the source block:

(plist-get (cadr (org-element-at-point)) :value)

You can also expand the body of a source block with C-c C-v C-v (bound to org-babel-expand-src-block) which creates a preview buffer with not only the source code but also the surrounding context (e.g. information coming from the headers of the source block).

1
  • 1
    Thank you. Your solution returns a string, not a region that I can pass to kill-ring-save, so I instead used kill-new, but it works just as good, IMHO. I added the answer below by replying to my question.
    – Paxsali
    Jan 22 at 9:16
1

SOLUTION:

(defun kill-src-block-at-point ()
  (interactive)
  (kill-new (plist-get (cadr (org-element-at-point)) :value))
  )
1
  • You should be able to accept your answer by now (just check the tick mark to the left of it). If there is a good answer, it's a good idea to accept it: it "closes" the question, allowing future visitors to see that the question has indeed been answered.
    – NickD
    Jan 26 at 14:26

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.