gleam-community / ansi

ANSI colours, formatting, and control codes
Apache License 2.0
24 stars 0 forks source link

Add function for removing ansi control characters from a string #4

Closed JohnBjrk closed 10 months ago

JohnBjrk commented 1 year ago

It would be useful to have a function that removes all ansi control characters from a given string.

There are (at least two) use-cases for something like this:

  1. If you have a string that have already been styled and need to provide it to some consumer that don't support ansi (a file, over the network, terminal without ansi-support).
  2. If you have a string that have already beed styled and need to calculate the length in terms of visible characters.

Here is an example implementation (which probably doesn't cover all valid ansi control characters) that takes the rather inefficient approach of scanning the the characters of the string dropping everything between and "m". I probably possible to use a regexp to achieve the same thing in a more efficient way.

pub fn strip_style(text) {
  let #(new_text, _) =
    text
    |> string.to_graphemes()
    |> list.fold(
      #("", False),
      fn(acc, char) {
        let #(str, removing) = acc
        let bit_char = bit_string.from_string(char)
        case bit_char, removing {
          <<0x1b>>, _ -> #(str, True)
          <<0x6d>>, True -> #(str, False)
          _, True -> #(str, True)
          _, False -> #(str <> char, False)
        }
      },
    )
  new_text
}