2020-05-03 Help in read-string

Last week I wrote about making Emacs ask for parameters for lp when printing from pdf-tools. The only thing missing was some kind of help for lp, which is far from intuitive.

I figured that it would be best if I could somehow make read-string display some help string when some key was pressed, even in the midst of editing in the minibuffer. (Preferably, the key would be C-h, which is Emacs’ default for “help”.)

And guess what? This is Emacs. Not only is such a feature possible, it is actually built-in! Emacs has a variable called help-form. It should contain a form evaluating to a string (in the simplest case, it may be just a string), which is then displayed when the “help key” is pressed. (“Help key” being also configurable in the help-char variable, the default being 8, meaning C-h. And just in case you wonder how to make f1 act as a help event – even though it is not really a “character” – you might want to check out the help-event-list variable. See the Help Functions node in the Elisp reference for more info.)

But wait, there’s more! The case of needing help in minibuffer is apparently quite common, so there is yet another feature involved. If you set the variable minibuffer-help-form and call some function reading user input from the minibuffer, help-form gets automatically rebound to its value.

So, this is what you might want to do to have C-h display help for your minibuffer input syntax:

(defun read-string-with-help (help &rest args)
  "Call `read-string' with `C-h' displaying HELP."
  (let ((minibuffer-help-form help))
    (apply #'read-string args)))

(defun demo-read-string-with-help ()
  (interactive)
  (message "%s" (read-string-with-help "this is help" "prompt: ")))

Now this is certainly not extremely aesthetic (the help is just shown in a temporary window, disappearing after pressing any key), but is perfectly functional.

CategoryEnglish, CategoryBlog, CategoryEmacs