You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is a very common issue developers run into especially on cross platform. When we handle a string which we don't created ourselves it might have a different line ending as expected. On Windows it can be a \n instead of \r\n and on Linux vice versa. On Linux its a bit easier as the workaround can be a simple string.Replace("\r\n", "\n") while on Windows we have to use Regex (because "\r\n".Replace("\n", "\r\n") obviously does something else than we are looking for) and if we don't want to go down the line by reading char by char ourselves. In order to eliminate the issue on all platforms there should be a single API.
Name and place of the API are free to change.
Proposed API
namespaceSystem{publicsealedclassString{//// Normalizes all line endings to the line ending on which platforms it runs// publicstringNormalizeLineEndings(thisstrings){
#if !PLATFORM_UNIX//Replace all line endings with \r\n
#else
//Replace all line endings with \n
#endif
}}}
Would it also be a possible scenario for someone to normalise the line ending to something that isn't Environment.NewLine? e.g. mixed \r\n and \n to all \n on Windows, non-Console environments.
publicsealedclassstring{// if lineEnding == null, use Environment.NewLine; otherwise use provided lineEnding as a replacementpublicstaticstringNormalizeLineEndings(stringinput,string?lineEnding=null);}
Ooh.... That's.... Interesting. Never thought about allowing something that isn't CR, LF or CRLF. Doesn't sound too bad, but I suppose the folks will figure out during the API reviews.
A string.NormalizeLineEndings API could be built atop the span-based API fairly easily. It would also be a fairly straightforward implementation: O(n * l) in the worst case, where n is the length of the input string and l is the length of the newline replacement string.
publicclassString{publicstringNormalizeLineEndings(string?lineEnding=null);}publicstaticclassMemoryExtensions{// mimics the existing methods 'EnumerateRunes'publicSystem.Text.SpanLineEnumeratorEnumerateLines(thisReadOnlySpan<char>span);publicSystem.Text.SpanLineEnumeratorEnumerateLines(thisSpan<char>span);}namespaceSystem.Text{// mimics the existing type 'SpanRuneEnumerator'publicrefstructSpanLineEnumerator{publicReadOnlySpan<char>Current;publicSpanLineEnumeratorGetEnumerator();publicboolMoveNext();}}
Behaviors & usage
NormalizeLineEndings searches for occurrences of Unicode newline characters, replacing such occurrences with the value of the lineEnding parameter. If lineEnding is nullptr, defaults to Environment.NewLine (the newline sequence for the current platform).
Open question: should we call the replacement string parameter replacement instead of lineEnding? There's no requirement for this parameter to itself represent a valid newline sequence.
Examples:
strings=GetString();// may contain a mix of CR, LF, CRLF, LS, PS, etc.// Normalize line endings to Environment.Newline (all calls below are identical)stringnormalized=s.NormalizeLineEndings();stringnormalized=s.NormalizeLineEndings(null);stringnormalized=s.NormalizeLineEndings(Environment.NewLine);// Normalize line endings to <CR><LF>, regardless of the current platformstringnormalized=s.NormalizeLineEndings("\r\n");// Normalize line endings to <LS>, regardless of the current platformstringnormalized=s.NormalizeLineEndings("\u2028");// Remove all line endings by normalizing them to [empty]stringnormalized=s.NormalizeLineEndings("");
During span-based enumeration, the Current property will refer back to a substring within the original provided string. The enumerator does not give newlines at the beginning or the end of the input string any special consideration, which may result in empty spans being seen during enumeration.
Examples:
ReadOnlySpan<char>span="Hello\nworld!\r\n";foreach(varlineinspan.EnumerateLines()){// On the first loop, line := span[0..5] ("Hello")// On the second loop, line := span[6..12] ("world!")// On the third loop, line := span[14..14] ("")// Loop then terminates}
Discussion
This API is useful for #50044 and other scenarios where text intended for user display may be transmitted across the wire, where the host system must account for any newline differences between itself and the remote system.
The Unicode Standard, §5.8, Recommendation R4, provides that any Unicode-compliant readline routine should recognize the following newline sequences: <CR>, <LF>, <CR><LF>, <NEL>, <FF>, <LS>, and <PS>. Our enumeration routine spans this entire list, and we will replace all such subsequences with the specified replacement string.
This proposed API is not intended for advanced text processing scenarios, such as a rich text editor that cares about the difference between line separators and paragraph separators. This API is not intended for protocol parsers which must restrict their operations to a subset of known line break characters. For instance, if a protocol mandates that only <CR>, <LF>, and <CR><LF> may be used for line breaks, a parser which wants to maintain compliance with the protocol specification should not rely on this API. This also means that the behavior of NormalizeLineEndings and EnumerateLines may differ from TextReader.ReadLine, which understands only <CR>, <LF>, and <CR><LF> by default.
Reacted by Martin Costello, Heath Stewart, Sergio Pedri and David Rettenbacher
Activity
Dotnet-GitSync-Bot commentedon Aug 4, 2020
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.
GrabYourPitchforks commentedon Aug 5, 2020
Seems reasonable. Wonder if we should do this on
StringBuilderas well.Behavior would be to find isolated
\r, isolated\n, and grouped\r\nand replace them all withEnvironment.NewLine.Gnbrkm41 commentedon Aug 5, 2020
Would it also be a possible scenario for someone to normalise the line ending to something that isn't
Environment.NewLine? e.g. mixed\r\nand\nto all\non Windows, non-Console environments.GrabYourPitchforks commentedon Aug 5, 2020
@Gnbrkm41 You mean something like below?
Gnbrkm41 commentedon Aug 5, 2020
Ooh.... That's.... Interesting. Never thought about allowing something that isn't CR, LF or CRLF. Doesn't sound too bad, but I suppose the folks will figure out during the API reviews.
GrabYourPitchforks commentedon Mar 31, 2021
Been thinking about this a little bit more. We already have an enumeration API over
stringinstances:It might also be useful to have an enumeration API over
ROS<char>instances:A
string.NormalizeLineEndingsAPI could be built atop the span-based API fairly easily. It would also be a fairly straightforward implementation: O(n * l) in the worst case, where n is the length of the input string and l is the length of the newline replacement string.GrabYourPitchforks commentedon Mar 31, 2021
API proposal
Behaviors & usage
NormalizeLineEndings searches for occurrences of Unicode newline characters, replacing such occurrences with the value of the lineEnding parameter. If lineEnding is nullptr, defaults to Environment.NewLine (the newline sequence for the current platform).
Examples:
During span-based enumeration, the Current property will refer back to a substring within the original provided string. The enumerator does not give newlines at the beginning or the end of the input string any special consideration, which may result in empty spans being seen during enumeration.
Examples:
Discussion
This API is useful for #50044 and other scenarios where text intended for user display may be transmitted across the wire, where the host system must account for any newline differences between itself and the remote system.
The Unicode Standard, §5.8, Recommendation R4, provides that any Unicode-compliant readline routine should recognize the following newline sequences:
<CR>,<LF>,<CR><LF>,<NEL>,<FF>,<LS>, and<PS>. Our enumeration routine spans this entire list, and we will replace all such subsequences with the specified replacement string.This proposed API is not intended for advanced text processing scenarios, such as a rich text editor that cares about the difference between line separators and paragraph separators. This API is not intended for protocol parsers which must restrict their operations to a subset of known line break characters. For instance, if a protocol mandates that only
<CR>,<LF>, and<CR><LF>may be used for line breaks, a parser which wants to maintain compliance with the protocol specification should not rely on this API. This also means that the behavior ofNormalizeLineEndingsandEnumerateLinesmay differ fromTextReader.ReadLine, which understands only<CR>,<LF>, and<CR><LF>by default.GrabYourPitchforks commentedon Mar 31, 2021
I incorporated some feedback from subject matter experts and marked this API ready for review.
bartonjs commentedon May 21, 2021
Video
replacementTextinstead oflineEndingin the ReplaceLineEndings method.