lib/ansi_formatter.rb in markdown_exec-2.3.0 vs lib/ansi_formatter.rb in markdown_exec-2.4.0

- old
+ new

@@ -1,10 +1,12 @@ #!/usr/bin/env ruby # frozen_string_literal: true # encoding=utf-8 +require_relative 'ansi_string' + class AnsiFormatter def initialize(options = {}) @options = options end @@ -16,34 +18,38 @@ highlight: [], line_prefix: ' ', line_postfix: '', detail_sep: '' ) - (data&.map do |item| + data&.map do |item| scan_and_process_multiple_substrings(item, highlight, plain_color_sym, highlight_color_sym).join - end || []) + end || [] end # Function to scan a string and process its segments based on multiple substrings # @param str [String] The string to scan. # @param substrings [Array<String>] The substrings to match in the string. # @param plain_sym [Symbol] The symbol for non-matching segments. # @param color_sym [Symbol] The symbol for matching segments. # @return [Array<String>] The processed segments. - def scan_and_process_multiple_substrings(str, substrings, plain_sym, color_sym) - return string_send_color(str, plain_sym) if substrings.empty? || substrings.any?(&:empty?) + def scan_and_process_multiple_substrings(str, substrings, plain_sym, + color_sym) + return string_send_color(str, + plain_sym) if substrings.empty? || substrings.any?(&:empty?) substring_patterns = substrings.map do |value| [value, Regexp.new(value, Regexp::IGNORECASE)] end results = [] remaining_str = str.dup while remaining_str.length.positive? - match_indices = substring_patterns.map { |_, pattern| remaining_str.index(pattern) }.compact + match_indices = substring_patterns.map do |_, pattern| + remaining_str.index(pattern) + end.compact earliest_match = match_indices.min if earliest_match # Process non-matching segment before the earliest match, if any unless earliest_match.zero? @@ -110,8 +116,8 @@ # @param color_sym [Symbol] The symbol representing the color method. # @param default [String] Default color method to use if color_sym is not found in @options. # @return [String] The string with the applied color method. def string_send_color(string, color_sym, default: 'plain') color_method = @options.fetch(color_sym, default).to_sym - string.to_s.send(color_method) + AnsiString.new(string.to_s).send(color_method) end end