def insert_ansi(ansi_stack, string)
      return string if ansi_stack.empty?
      to_remove = 0
      reset_index = -1
      output = string.dup
      resetting = false
      ansi_stack.reverse_each do |state|
        if state[0] =~ /#{Regexp.quote(RESET)}/
          resetting = true
          reset_index = state[1]
          to_remove += 2
          next
        elsif !resetting
          reset_index = -1
          resetting = false
        end

        color, color_index = *state
        output.insert(reset_index, RESET).insert(color_index, color)
      end
      ansi_stack.pop(to_remove) # remove used states
      output
    end
def insert_ansi(ansi_stack, string)
      return string if ansi_stack.empty?
      to_remove = 0
      reset_index = -1
      output = string.dup
      resetting = false
      ansi_stack.reverse_each do |state|
        if state[0] =~ /#{Regexp.quote(RESET)}/
          resetting = true
          reset_index = state[1]
          to_remove += 2
          next
        elsif !resetting
          reset_index = -1
          resetting = false
        end

        color, color_index = *state
        output.insert(reset_index, RESET).insert(color_index, color)
      end
      ansi_stack.pop(to_remove) # remove used states
      output
    end
Insert ANSI code into string

 Check if there are any ANSI states, if present
 insert ANSI codes at given positions unwinding the stack.

 @param [Array[Array[String, Integer]]] ansi_stack
   the ANSI codes to apply

 @param [String] string
   the string to insert ANSI codes into

 @return [String]

 @api private