Display `IMG:path` images in prompts
John Smith

John Smith commited on 2022-14 23:31:06
Showing 1 changed files, with 32 additions and 8 deletions.


Instances of `/IMG:([^ ]+)/` in prompts will now be omitted,
and the image at the specified path will be displayed.
... ...
@@ -35,6 +35,34 @@ local function clear()
35 35
     io.write("\x1bc")
36 36
 end
37 37
 
38
+--[[
39
+    display text with images, inserted with `IMG:path`
40
+    implementation may be platform-specific
41
+]]
42
+local function imgify(text)
43
+    -- adapted from https://stackoverflow.com/a/1579673
44
+    local PATTERN = "(.-)IMG:([^ ]+)"
45
+    -- Cygwin/Mintty
46
+    local DISPIMG = function(path)
47
+        if path and #path > 0 then
48
+            os.execute(string.format("showimg %s", path))
49
+        end
50
+    end
51
+    local le = 1
52
+    local s, e, pt, ip = text:find(PATTERN)
53
+    while s do
54
+        io.write(pt)
55
+        DISPIMG(ip)
56
+        le = e + 1
57
+        s, e, pt, ip = text:find(PATTERN, le)
58
+        io.write(pt or "")
59
+        DISPIMG(ip)
60
+    end
61
+    if le <= #text then
62
+        io.write(text:sub(le))
63
+    end
64
+end
65
+
38 66
 --[[
39 67
     check action based on first command-line argument;
40 68
     if nothing valid given, default to help
... ...
@@ -117,15 +145,11 @@ elseif action == "r" then
117 145
                 -- remove braces for display
118 146
                 local pst = pr.text:gsub("%{([^{}]+)%}", "%1")
119 147
                 local st = os.time()
120
-                io.write(string.format(
121
-                    "%s\n",
122
-                    pst:gsub("%%A", "___")
123
-                ))
148
+                imgify(pst:gsub("%%A", "___"))
149
+                io.write("\n")
124 150
                 io.read("l")
125
-                io.write(string.format(
126
-                    "%s\nAgain / Hard / Good / Easy / Correction ",
127
-                    pst:gsub("%%A", (pr.ans:gsub("%%", "%%%%")))
128
-                ))
151
+                imgify(pst:gsub("%%A", (pr.ans:gsub("%%", "%%%%"))))
152
+                io.write("\nAgain / Hard / Good / Easy / Correction ")
129 153
                 local resp = io.read("l")
130 154
                 local sc = succfromstr(resp)
131 155
                 if sc == -1 then
132 156