views:

115

answers:

2

Basically, I'd like to do the following, only using Common Lisp instead of Python:

print("Hello world.\r\n")

I can do this, but it only outputs the #\newline character and skips #\return:

(format t "Hello world.~%")

I believe I could accomplish this using an outside argument, like this:

(format t "Hello world.~C~%" #\return)

But is seems awkward to me. Surely I can somehow embed #\return into the very format string, like I can #\newline?

Yeah ehh, I'm nitpicking.

Thanks for any help!

+2  A: 

First, in Common Lisp most characters, including return/newline, can be inserted directly into the string. The only character requiring escaping is the string delimiter.

There is also a library cl-interpol which provides a read macro to construct strings with more complex syntax, including special character escapes.

Ramarren
+4  A: 

\r is the character #\return in Common Lisp.

\n is the character #\linefeed in Common Lisp.

The following ends the string "Hello world." with return and linefeed.

(format t "Hello world.~C~C" #\return #\linefeed)

#\newline is whatever the platform uses as a line division. On Unix machines this is often the same as #\linefeed. On other platforms (Windows, Lisp Machines, ...) this could be different.

The FORMAT control ~% prints a newline (!).

So

(format t "Hello world.~%")

will print the newline that the operating system uses. CR or CRLF or LF. Depending on the platform this will be one or two characters.

So, on a Windows machine your

(format t "Hello world.~C~%" #\return)

might actually print: #\return #\return #\linefeed. Which is THREE characters and not two. Windows uses CRLF for newlines. Unix uses LF. Old Mac OS (prior to Mac OS X) and Lisp Machines used CR for newlines.

If you really want to print CRLF, you have to do it explicitly. For example with:

(defun crlf (&optional (stream *standard-output*))
  (write-char #\return stream)
  (write-char #\linefeed stream)
  (values))

FORMAT does not have special syntax for output of linefeed or carriage return characters.

Rainer Joswig
In SBCL 1.0.22, CLISP 2.47 and Clozure CL 1.3 on Windows: (aref (format nil "~%") 0) returns #\Newline.
Frank Shearar
@Frank Shearar: and what does (length (format nil "~%")) produce? And what does it produce when you write it to a file? How long is the file?
Rainer Joswig
@Rainer 1, 1 and 1 for the length. With (with-open-file (s #p"c:\\foo.txt" :direction :output :if-exists :supersede) (write-string (format nil "~%") s)), SBCL and CCL spat out a 1-byte file containing \#Newline. Clisp spat out a 1-byte file containing a #\Return!
Frank Shearar
@Frank Shearar: kind of funky, given that CRLF is the native line ending character sequence on Windows. Expect different results with some other Lisps (LispWorks, Allegro CL, Corman CL, ...). Btw., some implementations make it configurable - Allegro CL has some documentation about that...
Rainer Joswig