Emacs: HTML. Image Path to Img Tag

By Xah Lee. Date: . Last updated: .

Emacs lisp command that changes a image path into a HTML image link.

Problem

You have this under cursor:

/home/xah/web/cat.jpg

you want it to be this:

<img src="cat.jpg" alt="cat" width="600" height="400" />

Solution

Get Image Dimensions

Image Path to HTML Image Link

WARNING: the code here is not maintained. it only shows you how to write it.

latest code at Emacs: Xah HTML Mode ๐Ÿ“ฆ

(defun my-html-image-linkify ()
  "Replace image file path under cursor to HTML img inline link.
Example:
 img/my_cats.jpg
become

 <img src=\"img/my_cats.jpg\" alt=\"my cats\" width=\"470\" height=\"456\" />

If `univers-argument' is called before, don't width and height attribute.

Returns the string used in the alt attribute.

URL `http://xahlee.info/emacs/emacs/elisp_image_tag.html'
Version: 2024-11-20"
  (interactive)
  (let (xp1 xp2 ximgPath xhrefValue xaltText ximgWH xwidth xheight)
    (save-excursion
      ;; get image file path begin end pos
      (let (xp0)
        (setq xp0 (point))
        ;; chars that are likely to be delimiters of full path, e.g. space, tabs, brackets.
        (skip-chars-backward "^ ย \"\t\n'|()[]{}<>ใ€”ใ€•โ€œโ€ใ€ˆใ€‰ใ€Šใ€‹ใ€ใ€‘ใ€–ใ€—ใ€˜ใ€™ยซยปโ€นโ€บยทใ€‚\\`")
        (setq xp1 (point))
        (goto-char xp0)
        (skip-chars-forward "^ ย \"\t\n'|()[]{}<>ใ€”ใ€•โ€œโ€ใ€ˆใ€‰ใ€Šใ€‹ใ€ใ€‘ใ€–ใ€—ใ€˜ใ€™ยซยปโ€นโ€บยทใ€‚\\'")
        (setq xp2 (point))
        (goto-char xp0)))
    (setq ximgPath (buffer-substring-no-properties xp1 xp2))
    (when (not (file-exists-p ximgPath))
      (user-error "file not exist at %s"  ximgPath))
    (setq xhrefValue
          (file-relative-name
           ximgPath
           (file-name-directory (or (buffer-file-name) default-directory))))
    (setq xaltText
          (replace-regexp-in-string
           "_" " "
           (replace-regexp-in-string
            "\\.[A-Za-z]\\{3,4\\}$" "" (file-name-nondirectory ximgPath) t t) t t))
    (if current-prefix-arg
        (progn
          (delete-region xp1 xp2)
          (insert
           (concat
            "<img src=\""
            xhrefValue
            "\"" " " "alt=\"" xaltText "\"" " />")))
      (progn
        (setq ximgWH (xah-get-image-dimensions ximgPath))
        (setq xwidth (number-to-string (elt ximgWH 0)))
        (setq xheight (number-to-string (elt ximgWH 1)))

        (delete-region xp1 xp2)
        (insert
         (if (or (equal xwidth "0") (equal xheight "0"))
             (concat
              "<img src=\""
              xhrefValue
              "\"" " " "alt=\"" xaltText "\"" " />")
           (concat
            "<img src=\""
            xhrefValue
            "\"" " " "alt=\"" xaltText "\""
            " width=\"" xwidth "\""
            " height=\"" xheight "\" />")))))
    xaltText
    ))