Search code examples
lispevalstring-formattingelispquote

Apply format to flattened argument list without removing nil, or sublist elements


I have a format string with 11 "%s", eg

"%s %s %s %s %s %s %s %s %s %s %s "

and would like apply format to this string and the results of (syntax-ppss), which may look something like this, eg. a mix of numbers, nil, t, sublists, ie. various objects. The "%s" format should be able to print any object, per docs

(3 1163 1171 nil nil nil 0 nil nil (1144 1153 1163) nil)

I thought this would be easy, but the only thing I could come up was quoting every element of the list then eval it like,

(eval
 `(format "%s %s %s %s %s %s %s %s %s %s %s "
          ,@(mapcar (lambda (it) (list 'quote it)) (syntax-ppss))))

This seems overly complicated, I was hoping for a simpler solution, if there is one?


Solution

  • Instead of formatting the whole list result of syntax-ppss at once, you could use mapconcat to format each element of the list and join the formatted strings together with a separator space:

    (mapconcat (lambda (it) (format "%s" it)) (syntax-ppss) " ")
    

    The main difference between this and your original solution is there's no trailing space in this result. If you want to keep it, use an empty separator and put the space in the format string instead:

    (mapconcat (lambda (it) (format "%s " it)) (syntax-ppss) "")
    

    EDIT: If you'd prefer to keep the single format call, still another alternative is to apply the list result of syntax-ppss to be the arguments to format:

    (apply 'format "%s %s %s %s %s %s %s %s %s %s %s " (syntax-ppss))