2

I use org-toggle-inline-images to directly view linked images in org-mode files. Unfortunately, depending on resolution, format and size, images often are too wide for the window (especially in portrait mode) and thus only partly visible.

Is there a way to automatically downscale an image to fit the window width?

2

Try setting org-image-actual-width to the width you would like it, usually a number like 600 is a reasonable choice. I don’t know of an way way to make it dynamic so it adjusts to the actual window width.

To get something more dynamic that only resizes things bigger than the window width, you need to advise a function.

Here is one way to think about it. We try to get the width of the image, and when it is bigger than the current window we use the actual window size in the preview. When it is smaller than the window, we use the actual size. And if you use attr_org to set the image size, we use that instead. We use an :around advice to basically replace the built in call to org--create-inline-image call. It is only lightly tested with file links.

(defun get-image-width (fname)
  "Returns the min of image width and window width, unless :width
is defined in an attr_org line."
  (let* ((link (save-match-data (org-element-context)))
     (paragraph (let ((e link))
              (while (and (setq e (org-element-property
                       :parent e))
                  (not (eq (org-element-type e)
                       'paragraph))))
              e))
     (attr_org (org-element-property :attr_org paragraph))
     (pwidth (plist-get
          (org-export-read-attribute :attr_org  paragraph) :width))
     (width (when pwidth (string-to-number pwidth))) 
     open
     img-buf)

    (unless width
      (setq open (find-buffer-visiting fname)
        img-buf (or open (find-file-noselect fname))
        width (min (window-width nil :pixels)
               (car (image-size (with-current-buffer img-buf (image-get-display-property)) :pixels))))

      (unless open (kill-buffer img-buf)))
    width))

(defun around-image-display (orig-fun file width)
  (apply orig-fun (list file (get-image-width file))))

(advice-add 'org--create-inline-image :around #'around-image-display)
2
  • The problem with org-image-actual-width is that the same width is set for all images (in my case screenshots of varying size) regardless of whether they are large or small. – Timm Jul 10 at 22:51
  • 1
    You can always set widths individually with the attr_org attribute. Use the following construct right before the image link: #+attr_org: :width 600px – nohans Jul 11 at 13:12

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.