Reputation: 10920
I would like to get this single-line string value:
"pineapple"
But in the source code, I would like to write the string across multiple lines:
"pine
apple"
However, the multi-line code above will return a string that includes a newline. Is there a way to stop a newline from being returned?
In other Lisps such as Scheme and Emacs Lisp, the newline can be suppressed by adding a backslash \
at the end of the line:
;; In Scheme and Emacs Lisp, this returns "pineapple":
"pine\
apple"
In Common Lisp, however, placing a backslash at the end of the line has no effect:
;; Common Lisp:
(string-equal "pine\
apple"
"pine
apple")
;; Returns: T
How do I write a single line string literal across multiple lines in the source code?
Upvotes: 3
Views: 2261
Reputation:
A good approach to doing this, I think, is to define a souped-up string reader which allows literal strings to have more possibilities. This is not very hard to do and I expect there are lots of them lurking in corners. One such that I happen to know quite well is stringtables. What this does is provide a system a modelled on the CL readtable (but, obviously, simpler) for literal strings. There can be special characters in strings which are something like equivalent to dispatching macro characters in the CL readtable (there is no equivalent of plain macro characters as this didn't seem useful). There is a default special character which is #\~
.
The system is rather general but it has a couple of utilities which let you use it in the simplest way. Here is an example of those.
First of all set up the readtable so that strings written as #" ..."
will be parsed using a stringtable (*stringtable*
is the stringtable used in the same way that *readtable*
is the readtable used):
> (setf *readtable* (make-stringtable-readtable :delimiter #\"))
#<readtable 402006239B>
Now configure *stringtable*
to have a newline-skipper and a couple of things which will warn on possible botched newline skips:
> (set-stringtable-newline-skipper :stringtable *stringtable*)
#<stringtable 421018687B>
And now we can test things:
> (read)
"this is an oordinary
string"
"this is an oordinary
string"
> (read)
#"this string is read
with a stringtable"
"this string is read
with a stringtable"
> (read)
#"this string has an ~
ignored newline"
"this string has an ignored newline"
> (read)
#"this string has a botched ~
ignored newline"
Warning: ~ followed by space: did you mean newline?
"this string has a botched
ignored newline"
Upvotes: 1
Reputation: 7568
Use ~Newline directive in format.
(string-equal (format nil "multi-~
line ~
pine~
apple")
"multi-line pineapple")
Upvotes: 7