formatcommon-lispstring-formattingclisp

Mysterious newline appears in Common Lisp format directive


I'm running into an odd issue with Common Lisp's format directive that only shows itself in GNU CLISP, which leads me to wonder if it's a bug in the implementation.

Consider the following code

(defun f (s args)
  (format nil "~A~{~A~%~}" s args))

The function f produces a string consisting of the s argument, followed by each argument, where each argument (but not the header) is followed by a newline. So, for instance, I would expect

(format t "~A" (f "foo" '("arg1" "arg2")))

to produce

fooarg1
arg2

which it does, correctly. Now, consider the following calls

(format t "~A" (f "a" ()))
(format t "~A" (f "b" ()))
(format t "~A" (f "c" '("d")))

Given that the only newlines I ever print out are following elements from the second argument of f, and the first two calls pass an empty list for the second f argument, I expect to see no newlines until the very end, i.e. I expect this to print

abcd

It does exactly this in SBCL. However, in GNU CLISP, I get

ab
cd

Note the newline between b and c.

Changing the code to

(format t "~S" (f "a" ()))
(format t "~S" (f "b" ()))
(format t "~S" (f "c" '("d")))

shows the following, even less illuminating, results

"a""b"
"cd
"

So the newline between b and c is not part of either of the strings. Why is CLISP deciding to print a newline in between these format statements? And how can I prevent it from doing so?


Solution

  • This is a feature of GNU CLISP. See the documentation of *pprint-first-newline*.

    If you want a different output than that, bind either *print-pretty* or *pprint-first-newline* to nil during your format invocation.