Skip to content

Commit

Permalink
feat: add strip function (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
brettkolodny authored Jan 6, 2024
1 parent 0d1603f commit 535edd0
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/gleam_community/ansi.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
//// - [`bg_hex`](#bg_hex)
//// - [`bg_colour`](#bg_colour)
//// - [`bg_color`](#bg_color)
//// - **Utilities**
//// - [`strip`](#strip)
////
//// ---
////
Expand Down Expand Up @@ -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 ---------------------------------------------------------------------
Expand Down Expand Up @@ -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.
///
/// <details>
/// <summary>Example:</summary>
///
/// ```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`.
/// </details>
///
/// <div style="position: relative;">
/// <a style="position: absolute; left: 0;" href="https://github.com/gleam-community/ansi/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// <a style="position: absolute; right: 0;" href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
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.
///
Expand Down
22 changes: 22 additions & 0 deletions test/gleam_community_ansi_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

0 comments on commit 535edd0

Please sign in to comment.