@@ -612,14 +612,14 @@ julia> println(raw"\\\\x \\\\\\"")
612
612
macro raw_str (s); s; end
613
613
614
614
"""
615
- escape_raw_string(s::AbstractString)
616
- escape_raw_string(io, s::AbstractString)
615
+ escape_raw_string(s::AbstractString, delim='"') -> AbstractString
616
+ escape_raw_string(io, s::AbstractString, delim='"' )
617
617
618
618
Escape a string in the manner used for parsing raw string literals.
619
- For each double-quote (`"`) character in input string `s`, this
620
- function counts the number _n_ of preceding backslash (`\\ `) characters,
621
- and then increases there the number of backslashes from _n_ to 2_n_+1
622
- (even for _n_ = 0). It also doubles a sequence of backslashes at the end
619
+ For each double-quote (`"`) character in input string `s` (or `delim` if
620
+ specified), this function counts the number _n_ of preceding backslash (`\\ `)
621
+ characters, and then increases there the number of backslashes from _n_ to
622
+ 2_n_+1 (even for _n_ = 0). It also doubles a sequence of backslashes at the end
623
623
of the string.
624
624
625
625
This escaping convention is used in raw strings and other non-standard
@@ -629,36 +629,41 @@ command-line string into the argv[] array.)
629
629
630
630
See also [`escape_string`](@ref).
631
631
"""
632
- function escape_raw_string (io, str:: AbstractString )
632
+ function escape_raw_string (io:: IO , str:: AbstractString , delim:: Char = ' "' )
633
+ total = 0
633
634
escapes = 0
634
635
for c in str
635
636
if c == ' \\ '
636
637
escapes += 1
637
638
else
638
- if c == ' " '
639
+ if c == delim
639
640
# if one or more backslashes are followed by
640
641
# a double quote then escape all backslashes
641
642
# and the double quote
642
- escapes = escapes * 2 + 1
643
- end
644
- while escapes > 0
645
- write (io, ' \\ ' )
646
- escapes -= 1
643
+ escapes += 1
644
+ total += escapes
645
+ while escapes > 0
646
+ write (io, ' \\ ' )
647
+ escapes -= 1
648
+ end
647
649
end
648
650
escapes = 0
649
- write (io, c)
650
651
end
652
+ write (io, c)
651
653
end
652
654
# also escape any trailing backslashes,
653
655
# so they do not affect the closing quote
656
+ total += escapes
654
657
while escapes > 0
655
- write (io, ' \\ ' )
656
658
write (io, ' \\ ' )
657
659
escapes -= 1
658
660
end
661
+ total
662
+ end
663
+ function escape_raw_string (str:: AbstractString , delim:: Char = ' "' )
664
+ total = escape_raw_string (devnull , str, delim) # check whether the string even needs to be copied and how much to allocate for it
665
+ return total == 0 ? str : sprint (escape_raw_string, str, delim; sizehint = sizeof (str) + total)
659
666
end
660
- escape_raw_string (str:: AbstractString ) = sprint (escape_raw_string, str;
661
- sizehint = lastindex (str) + 2 )
662
667
663
668
# # multiline strings ##
664
669
0 commit comments