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 3 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.ex
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,39 @@ defmodule Code do
unrequire_files(files)
end

@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"])`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels like the disclaimer about ending will narrow the use case for this quite a bit?
Perhaps we could add a trim: true option later to remove the ending, in which case it would make it more generally useful.
Which kind of use cases do we have in mind for this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use case is to fetch a range from a source file but preserving its original source code. I can add trim: true but trim typically means trimming more (spaces, tabs, etc). It is also something folks can do by doing another pass on the data.


## Examples

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

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

iex> Code.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 """
Appends a path to the Erlang VM code path list.

Expand Down
Loading