New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support Escape Sequences in Multiline Strings #21327
Comments
Multiline strings are raw strings. Without any changes to the compiler something as simple as the following could be used instead, which I'd argue is plenty nice. import std/[enumerate, macros]
macro multiline(body: untyped): string =
var res = ""
for i, str in enumerate body:
if str.kind notin nnkStrLit..nnkTripleStrLit:
error("Expected a 'string'", str)
res.add str.strVal
if i < body.len - 1:
res.add "\n"
result = newLit res
const myString = multiline:
"Hello"
"World"
"\t hmmmm"
"Bleh"
echo myString |
I argued this long ago - I felt that it would be better for the compiler to support escape sequences in multiline strings, and ignore any unsupported ones (which might be supported by string prefix routines), but unfortunately I think that the time to change this has long since passed. |
@beef331's solution is excellent. |
The solution may be "excellent", but unfortunately it is not practical. I'm porting a software of mine to Nim, and I have long help messages that would be very ugly in the format above. I'm very impressed with Nim, it honestly feels like magic, but I was disappointed to learn that escape sequences in multiline strings are not supported. |
import macros
macro welldone(s: static[string]): string =
var
res = ""
i = 0
while i < s.high:
case s[i]
of '\\':
case s[i + 1]
of '\\': res.add '\\'
of '\"': res.add '\"'
of '\'': res.add '\''
of 'n': res.add '\n'
else: error "unknown escape sequence"
inc i
else: res.add s[i]
inc i
result = newLit res
echo welldone"""
\"\n\'\\
""" here is rudimentary macro, because i cant be bothered with implementing every other supported escape sequence, but you get the idea. |
Summary
As the title states, escape sequences are only supported in single-line strings, and since multi-line strings are only literals, escape sequences aren't supported.
Description
Escape sequences, like
\t
and\n
are only supported in single-line strings, and since multi-line strings are only literals, escape sequences aren't supported.Alternatives
No response
Examples
No response
Backwards Compatibility
No response
Links
No response
The text was updated successfully, but these errors were encountered: