Skip to content

Add Code.Fragment.lines/1 #14493

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

Merged
merged 4 commits into from
May 28, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions lib/elixir/lib/code/fragment.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,39 @@ defmodule Code.Fragment do

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

@doc ~S"""
Returns the list of lines in the given string, preserving their line endings.

Only the line endings recognized by the Elixir compiler are
considered, namely `\r\n` and `\n`. If you would like the retrieve
lines without their line endings, use `String.split(string, ["\r\n", "\n"])`.

## Examples

iex> Code.Fragment.lines("foo\r\nbar\r\nbaz")
["foo\r\n", "bar\r\n", "baz"]

iex> Code.Fragment.lines("foo\nbar\nbaz")
["foo\n", "bar\n", "baz"]

iex> Code.Fragment.lines("")
[""]

"""
@doc since: "1.19.0"
def lines(string) do
lines(string, <<>>)
end

defp lines(<<?\n, rest::binary>>, acc),
do: [<<acc::binary, ?\n>> | lines(rest, <<>>)]

defp lines(<<char, rest::binary>>, acc),
do: lines(rest, <<acc::binary, char>>)

defp lines(<<>>, acc),
do: [acc]

@doc """
Receives a string and returns the cursor context.

Expand Down
Loading