From 700264d23bcdb8143631f9e5791b845ad71fd6b8 Mon Sep 17 00:00:00 2001 From: brettkolodny Date: Sat, 6 Jan 2024 13:33:46 -0500 Subject: [PATCH] feat: add strip function --- src/gleam_community/ansi.gleam | 41 ++++++++++++++++++++++++++++ test/gleam_community_ansi_test.gleam | 22 +++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/gleam_community/ansi.gleam b/src/gleam_community/ansi.gleam index 0e2ddfe..3dc7305 100644 --- a/src/gleam_community/ansi.gleam +++ b/src/gleam_community/ansi.gleam @@ -52,6 +52,8 @@ //// - [`bg_hex`](#bg_hex) //// - [`bg_colour`](#bg_colour) //// - [`bg_color`](#bg_color) +//// - **Utilities** +//// - [`strip`](#strip) //// //// --- //// @@ -96,6 +98,7 @@ import gleam/int import gleam/list import gleam/string +import gleam/regex import gleam_community/colour.{type Colour} as gc_colour // CONSTS --------------------------------------------------------------------- @@ -2318,6 +2321,44 @@ pub fn bg_colour(text: String, colour: Colour) -> String { bg_hex(text, hex_colour) } +/// Strips the ansi control characters from the text. +/// +///
+/// Example: +/// +/// ```gleam +/// import gleam_community/ansi +/// +/// fn example() { +/// let bold_lucy = ansi.bold("lucy") +/// // => "\x1B[1mlucy\x1B[22m" +/// ansi.strip(bold_lucy) +/// // => "lucy" +/// } +/// ``` +/// +/// In this example, the text "lucy" is boldened by `ansi.bold` and then converted back to the original +/// string with `ansi.strip`. +///
+/// +///
+/// +/// Spot a typo? Open an issue! +/// +/// +/// Back to top ↑ +/// +///
+/// +pub fn strip(text: String) -> String { + let regex_options = regex.Options(False, True) + let assert Ok(r) = regex.compile("(?:\\[(?:\\d+;?)+m)+", with: regex_options) + + r + |> regex.split(text) + |> string.join("") +} + /// This is an alias for [`bg_colour`](#bg_colour) for those who prefer the American English /// spelling. /// diff --git a/test/gleam_community_ansi_test.gleam b/test/gleam_community_ansi_test.gleam index bbba382..920ed9b 100644 --- a/test/gleam_community_ansi_test.gleam +++ b/test/gleam_community_ansi_test.gleam @@ -292,3 +292,25 @@ pub fn bg_colour_test() { |> ansi.bg_colour(colour.pink) |> should.equal(ansi.bg_pink("foo bar")) } + +pub fn strip_test() { + "foo bar" + |> ansi.hex(0x292A2B) + |> ansi.strip() + |> should.equal("foo bar") + + "foo bar" + |> ansi.bg_pink() + |> ansi.pink() + |> ansi.strip() + |> should.equal("foo bar") + + "foo bar" + |> ansi.hex(0x292A2B) + |> ansi.dim() + |> ansi.underline() + |> ansi.bg_pink() + |> ansi.inverse() + |> ansi.strip() + |> should.equal("foo bar") +}