diff --git a/lib/elixir/lib/code/fragment.ex b/lib/elixir/lib/code/fragment.ex index 431951e3f13..255a3640cad 100644 --- a/lib/elixir/lib/code/fragment.ex +++ b/lib/elixir/lib/code/fragment.ex @@ -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(<>, acc), + do: [<> | lines(rest, <<>>)] + + defp lines(<>, acc), + do: lines(rest, <>) + + defp lines(<<>>, acc), + do: [acc] + @doc """ Receives a string and returns the cursor context.