I'd like to copy part of a buffer including all images. The code below copies the text but not the image. How do I copy images and how do I search for images in a buffer?

 (with-current-buffer (get-buffer-create "buf")
   (insert "-->")
   (put-image (find-image '((:type jpeg :file "~/foo.jpg")))
   (insert "<--")
   (buffer-substring (point-min) (point-max))))
  • put-image uses an overlay for displaying the image. You can use insert-image which uses the display text property of an inserted string . You can then get the string with its properties with buffer-substring. I'm still looking for how to insert a string in the buffer, including its display property.
    – JeanPierre
    Mar 11 '20 at 18:03
  • There's a function copy-overlay. But I do not know what to do with this copy. How do I insert it? Mar 11 '20 at 20:16

I think I found a solution. You need copy-overlay and move-overlay to copy an overlay to another buffer:

(defun my-copy-buf (buf)
  (let* ((beg (with-current-buffer buf (point-min)))
         (end (with-current-buffer buf (point-max)))
         (ovs (with-current-buffer buf (overlays-in beg end))))
      (insert-buffer-substring buf beg end))
    (dolist (ov ovs)
      (move-overlay (copy-overlay ov)
                    (1- (+ (point) (overlay-start ov)))
                    (1- (+ (point) (overlay-end ov)))

  (with-current-buffer (get-buffer-create "tmp-buffer")
    (insert "-->")
    (put-image (find-image '((:type jpeg :file "~/foo.jpg")))
    (insert "<--"))
  (my-copy-buf "tmp-buffer")

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.