pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/ansi/ansi.go (about)

     1  // Package ansi provides methods for working with ANSI/VT100 control sequences
     2  package ansi
     3  
     4  // ////////////////////////////////////////////////////////////////////////////////// //
     5  //                                                                                    //
     6  //                         Copyright (c) 2022 ESSENTIAL KAOS                          //
     7  //      Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>     //
     8  //                                                                                    //
     9  // ////////////////////////////////////////////////////////////////////////////////// //
    10  
    11  import (
    12  	"bytes"
    13  )
    14  
    15  // ////////////////////////////////////////////////////////////////////////////////// //
    16  
    17  // HasCodes returns true if given string contains ANSI/VT100 control sequences
    18  func HasCodes(s string) bool {
    19  	for _, r := range s {
    20  		if r == 0x1B {
    21  			return true
    22  		}
    23  	}
    24  
    25  	return false
    26  }
    27  
    28  // HasCodes returns true if given byte slice contains ANSI/VT100 control sequences
    29  func HasCodesBytes(b []byte) bool {
    30  	for _, r := range b {
    31  		if r == 0x1B {
    32  			return true
    33  		}
    34  	}
    35  
    36  	return false
    37  }
    38  
    39  // RemoveCodesBytes returns string without all ANSI/VT100 control sequences
    40  func RemoveCodes(s string) string {
    41  	if s == "" || !HasCodes(s) {
    42  		return s
    43  	}
    44  
    45  	return string(RemoveCodesBytes([]byte(s)))
    46  }
    47  
    48  // RemoveCodesBytes returns byte slice without all ANSI/VT100 control sequences
    49  func RemoveCodesBytes(b []byte) []byte {
    50  	if len(b) == 0 || !HasCodesBytes(b) {
    51  		return b
    52  	}
    53  
    54  	var buf bytes.Buffer
    55  	var skip bool
    56  
    57  	for _, r := range b {
    58  		if r == 0x1B {
    59  			skip = true
    60  			continue
    61  		}
    62  
    63  		if skip {
    64  			if r != 0x6D {
    65  				continue
    66  			}
    67  
    68  			skip = false
    69  			continue
    70  		}
    71  
    72  		buf.WriteByte(r)
    73  	}
    74  
    75  	return buf.Bytes()
    76  }
    77  
    78  // ////////////////////////////////////////////////////////////////////////////////// //