1

I have this great piece of code to copy the contents of a code block:

(defun copy-org-babel-source-block-at-point ()
  (interactive)
  (kill-new (plist-get (cadr (org-element-at-point)) :value))
  )

How can I modify this to also include the actual block, with headers and all?

1 Answer 1

2

You could inspect the (org-element-at-point) using M-:, you would find it has a :begin and :end property.

Then you can copy the full region as follows:

(defun copy-org-babel-source-block-at-point ()
  (interactive)
  (let* ((e (org-element-at-point))
         (beg (org-element-property :begin e))
         (end (org-element-property :end e))
         (text (string-trim-right (buffer-substring beg end))))
    (kill-new text)))

As the :end is not (always/ever) on the #+END_SRC line, we trim the trailing whitespace before adding to the kill-ring.

1
  • 2
    You might want to check that point is inside a source block before you act: (when (eq (org-element-type element) 'src-block) ... )
    – Heikki
    Commented Feb 8, 2023 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.