Elisp: Add “alt” Attribute to Image Tags

By Xah Lee. Date: . Last updated: .



For all HTML image tags of the form:

<img src="my_cat.png" alt="" width="832" height="513">

Add a value to the “alt” attribute. The value should be the image file name, without file extension, and LOW LINE char _ converted to space. The result should be like this:

<img src="my_cat.png" alt="my cat" width="832" height="513">



List and Mark Files in Subdirectories


Now, mark the files you want, by Alt+x dired-mark-files-regexp% m】. Then give the pattern \.html. This marks all HTML files.

Dired Query Replace by Regexp

To do regexp replace on dired marked files, Alt+x dired-do-query-replace-regexp. [see Emacs: Find Replace Text in Directory]

The Search Pattern



This regex captures the file name, the width and height.

[see Emacs: Regex Tutorial]

Using Elisp Expression for Replacement String



 "<img src=\""
 (match-string 1)
 "\" alt=\""
 "\" width=\""
 (match-string 2)
 "\" height=\""
 (match-string 3)


Finally, we call dired-do-query-replace-regexpQ】 in the dired buffer. [see Emacs: Find Replace Text in Directory]


Advantage of Interactive Regex Replace on Multiple Files



See also: Elisp: Find Replace Multiple String Pairs

Function as Replacement String

  1. Call Function in Replacement String
  2. Add “alt” Attribute to Image Tags
  3. Replace String Based on File Name
  4. HTML Entities → Unicode Char
  5. Char → Unicode Name + Char

Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp