def insert_ansi(string, ansi_stack = [])
      return string if ansi_stack.empty?
      return string if string.empty?

      new_stack = []
      output          = string.dup
      length          = string.size
      matched_reset   = false
      ansi_reset      = Strings::ANSI::RESET

      # Reversed so that string index don't count ansi
      ansi_stack.reverse_each do |ansi|
        if ansi[0] =~ /#{Regexp.quote(ansi_reset)}/
          matched_reset = true
          output.insert(ansi[1], ansi_reset)
          next
        elsif !matched_reset # ansi without reset
          matched_reset = false
          new_stack << ansi # keep the ansi
          next if ansi[1] == length
          output.insert(-1, ansi_reset) # add reset at the end
        end

        output.insert(ansi[1], ansi[0])
      end

      ansi_stack.replace(new_stack)

      output
    end
def insert_ansi(string, ansi_stack = [])
      return string if ansi_stack.empty?
      return string if string.empty?

      new_stack = []
      output          = string.dup
      length          = string.size
      matched_reset   = false
      ansi_reset      = Strings::ANSI::RESET

      # Reversed so that string index don't count ansi
      ansi_stack.reverse_each do |ansi|
        if ansi[0] =~ /#{Regexp.quote(ansi_reset)}/
          matched_reset = true
          output.insert(ansi[1], ansi_reset)
          next
        elsif !matched_reset # ansi without reset
          matched_reset = false
          new_stack << ansi # keep the ansi
          next if ansi[1] == length
          output.insert(-1, ansi_reset) # add reset at the end
        end

        output.insert(ansi[1], ansi[0])
      end

      ansi_stack.replace(new_stack)

      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 [String] string
   the string to insert ANSI codes into

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

 @return [String]

 @api private