2016-11-19 format-spec

Last week I was coding something Emacs-y, and felt the need of a format-like function. It would get a string with embedded “control codes”, like %t% or %h, and then output a string with these “control codes” replaced by actual content. Writing something like that is not particularly difficult, but since I wanted to be able to also escape the percent sign by writing %%, I didn’t really feel like reinventing the wheel (and doing it elegantly and efficiently might be a tad tricky anyway). I asked a question on the help-gnu-emacs mailing list, and voilà! Here is the format-spec function. It accepts two arguments: a format-like string and a specification. The latter is an alist mapping characters to values. Here is an example:

(format-spec "%n %v %p %o."
		 '((?n . "A dog")
		   (?v . "jumps")
		   (?p . "over")
		   (?o . "the fence")))
(format-spec "%n %v %o." '((?n . 7) (?v . 8) (?o . 9)))

Notice that the values need not be strings – other objects are fine, assuming that they are printable as in (format "%s" ...). Also, you can put any width/precision and left-align specifiers (as you would in (format "%s" ...), which is called underneath by format-spec).

For the sake of completeness, let me also notice that if you want to put variables in the format-spec specification, you either need to use backquoting and unquoting or construct the specification list by the format-spec-make function (quod vide).

Once again, Emacs customizability shines – also when I want my code to be as customizable as Emacs’ own one.

CategoryBlog, CategoryEnglish, CategoryEmacs