2015-08-08 Concatenation with indentation

Quite recently, I was coding two (independent) Emacs projects involving generating XML files. I found the xmlgen Emacs library, learned to use it (well, it’s trivial: basically, it defines a mapping from the list structure to XML, and lets specify both tags and attributes in a natural way), and dropped it. The reason was that I wanted my XML files to be human-readable, and xmlgen did not pretty-print them at all. (There is a pretty-printer of XML (in fact, SGML) files in Emacs, but I didn’t like it: it sprinkled my file with newlines in places I didn’t want them.)

Since the files I’m generating are quite simple, I decided to use format a few times and call it a day. Well, simple or not, it was a bit awkward, especially with indentation. So I thought that I could write a small function, which – given a list of strings and the amount of indentation – would format them accordingly. And so here it is, just in case someone needs it.

(defun concat-lines-with-indentation (indent &rest lines)
  "Given the amount of indentation and some strings (LINES),
concatenate them, prepending INDENT spaces to each line."
  (apply #'concat (let ((indent-string (make-string indent 32)))
                    (mapcar (lambda (line)
                              (concat indent-string
                                      (unless (eq (elt line (1- (length line))) ?\n)

There aren’t very many terribly interesting things about this code – it’s fairly standard, but it turned out to be helpful (at least for me). (What I miss in the above code – because of my use-case – is the ability to mix strings and list of strings in the lines argument, but I was just a bit too lazy to code that.)

CategoryEnglish, CategoryBlog, CategoryEmacs