Is there a package to preview an image inserted in the html tag <img src="path-to-image"/> when hovering the tag with the mouse ?

1 Answer 1


I am not aware of any mode that provides this. However, after (quite some) 'investigation' it can easily be obtained using something like the following, which makes use of syntactic font lock because the filenames are (usually) given as strings:

(with-eval-after-load "sgml-mode"
  (defun sgml-font-lock-syntactic-face (state)
    "`font-lock-syntactic-face-function' for `sgml-mode'."

    ;; Show image tooltip on hover. From
    ;; `font-lock-fontify-syntactically-region' and
    ;; `font-lock-syntactic-face-function' we conclude that somehow `nth 3' of
    ;; the state corresponds to `strings'
    (when-let (url (and (nth 3 state) (thing-at-point 'filename)))
      (when (image-supported-file-p url)
        (setq url (string-trim url "file://"))
        (let ((img (create-image url
                                 (image-type url)))
              (bounds (thing-at-point-bounds-of-string-at-point)))
          (put-text-property (car bounds) (cdr bounds)
                             'help-echo (propertize url 'display img)))))

    ;; Don't use string face outside of tags.
    (cond ((and (nth 9 state) (nth 3 state)) font-lock-string-face)
          ((nth 4 state) font-lock-comment-face))))

By default the image shows in the minibuffer, but if you prefer to have in in the tooltip, then you just have to activate tooltip-mode.

However, the code is not compatible with goto-address-(prog-)mode, as the overlays added by that mode overrule the text-properties (in particular, it overrules the help-echo, which could be fixed from that mode by first checking if some help-echo has already been assigned). Otherwise, I guess the code is quite robust, but I am not sure about that. You might have to make some small adaptations, but then at least it shows the essential steps.

Note that on GNU/linux and OSX systems there might be a bug, so that you additionally have to use:

(setq x-gtk-use-system-tooltips nil)

Additionally, @John Kitchin mentions in 2016, that on OSX the image tooltip does not work when Emacs has been built with 'cocoa' support.

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.