index rss mastodon twitter github linkedin email
Álvaro Ramírez
sponsor

Álvaro Ramírez

18 August 2022 dwim-shell-command with template prompts

Somewhat recently, I wanted to quickly create an empty/transparent png file. ImageMagick's convert has you covered here. Say you want a transparent 200x400 image, you can get it with:

convert -verbose -size 200x400 xc:none empty200x400.png

Great, I now know the one-liner for it. But because I'm in the mood of saving these as seamless command-line utils, I figured I should save the dwim-shell-command equivalent.

I wanted configurable image dimensions, so I used read-number together with format to create the templated command and fed it to dwim-shell-command-on-marked-files. Job done:

(defun dwim-shell-commands-make-transparent-png ()
  "Create a transparent png."
  (interactive)
  (let ((width (read-number "Width: " 200))
        (height (read-number "Height: " 200)))
    (dwim-shell-command-on-marked-files
     "Create transparent png"
     (format "convert -verbose -size %dx%d xc:none '<<empty%dx%d.png(u)>>'"
             width height width height)
     :utils "convert")))

The resulting dwim-shell-commands-make-transparent-png is fairly simple, but dwim-shell-command aims to remove friction so you're more inclined to save reusable commands. In this case, we can shift querying and formatting into the template.

<<Width:200>> can be interpreted as "ask the user for a value using the suggested prompt and default value."

query.png

With template queries in mind, dwim-shell-commands-make-transparent-png can be further reduced to essentially the interactive command boilerplate and the template itself:

(defun dwim-shell-commands-make-transparent-png ()
  "Create a transparent png."
  (interactive)
  (dwim-shell-command-on-marked-files
   "Create transparent png"
   "convert -verbose -size <<Width:200>>x<<Height:200>> xc:none '<<empty<<Width:200>>x<<Height:200>>.png(u)>>'"
   :utils "convert"))

empty.webp

Note: Any repeated queries (same prompt and default) are treated as equal. That is, ask the user once and replace everywhere. If you'd like to request separate values, change either prompt or the default value.