Skip to content

Commit 7f1fe47

Browse files
authored
Add Code.Fragment.lines/1 (#14493)
1 parent 56fb419 commit 7f1fe47

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

lib/elixir/lib/code/fragment.ex

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,39 @@ defmodule Code.Fragment do
1111

1212
@type position :: {line :: pos_integer(), column :: pos_integer()}
1313

14+
@doc ~S"""
15+
Returns the list of lines in the given string, preserving their line endings.
16+
17+
Only the line endings recognized by the Elixir compiler are
18+
considered, namely `\r\n` and `\n`. If you would like the retrieve
19+
lines without their line endings, use `String.split(string, ["\r\n", "\n"])`.
20+
21+
## Examples
22+
23+
iex> Code.Fragment.lines("foo\r\nbar\r\nbaz")
24+
["foo\r\n", "bar\r\n", "baz"]
25+
26+
iex> Code.Fragment.lines("foo\nbar\nbaz")
27+
["foo\n", "bar\n", "baz"]
28+
29+
iex> Code.Fragment.lines("")
30+
[""]
31+
32+
"""
33+
@doc since: "1.19.0"
34+
def lines(string) do
35+
lines(string, <<>>)
36+
end
37+
38+
defp lines(<<?\n, rest::binary>>, acc),
39+
do: [<<acc::binary, ?\n>> | lines(rest, <<>>)]
40+
41+
defp lines(<<char, rest::binary>>, acc),
42+
do: lines(rest, <<acc::binary, char>>)
43+
44+
defp lines(<<>>, acc),
45+
do: [acc]
46+
1447
@doc """
1548
Receives a string and returns the cursor context.
1649

0 commit comments

Comments
 (0)