From 8ffaf5a34181aa1b2e82717d485ac846d6089e11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 14 May 2025 09:39:31 +0200 Subject: [PATCH 1/2] Add String.lines/1 --- lib/elixir/lib/string.ex | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/lib/elixir/lib/string.ex b/lib/elixir/lib/string.ex index 626e7d259b..fc375a1ac8 100644 --- a/lib/elixir/lib/string.ex +++ b/lib/elixir/lib/string.ex @@ -574,6 +574,38 @@ defmodule String do end end + @doc ~S""" + Returns the list of lines in a string, preserving their line endings. + + If you would like the lines without their line endings, use + `String.split(string, ["\r\n", "\n"])`. + + ## Examples + + iex> String.lines("foo\r\nbar\r\nbaz") + ["foo\r\n", "bar\r\n", "baz"] + + iex> String.lines("foo\nbar\nbaz") + ["foo\n", "bar\n", "baz"] + + iex> String.lines("") + [""] + + """ + @doc since: "1.19.0" + def lines(string) do + lines(string, <<>>) + end + + def lines(<>, acc), + do: [<> | lines(rest, <<>>)] + + def lines(<>, acc), + do: lines(rest, <>) + + def lines(<<>>, acc), + do: [acc] + @doc """ Returns an enumerable that splits a string on demand. From 17e41d020959ce2cb7a1ca7450e1a1e52b08ea0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 14 May 2025 09:42:16 +0200 Subject: [PATCH 2/2] Private --- lib/elixir/lib/string.ex | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/elixir/lib/string.ex b/lib/elixir/lib/string.ex index fc375a1ac8..fd9ddd6d5b 100644 --- a/lib/elixir/lib/string.ex +++ b/lib/elixir/lib/string.ex @@ -597,13 +597,13 @@ defmodule String do lines(string, <<>>) end - def lines(<>, acc), + defp lines(<>, acc), do: [<> | lines(rest, <<>>)] - def lines(<>, acc), + defp lines(<>, acc), do: lines(rest, <>) - def lines(<<>>, acc), + defp lines(<<>>, acc), do: [acc] @doc """