Method: Doing::StringHighlight#highlight_search

Defined in:
lib/doing/string/highlight.rb

#highlight_search(search, distance: nil, negate: false, case_type: nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/doing/string/highlight.rb', line 31

def highlight_search(search, distance: nil, negate: false, case_type: nil)
  out = dup
  matching = Doing.setting('search.matching', 'pattern').normalize_matching
  distance ||= Doing.setting('search.distance', 3).to_i
  case_type ||= Doing.setting('search.case', 'smart').normalize_case

  if search.rx? || matching == :fuzzy
    rx = search.to_rx(distance: distance, case_type: case_type)
    out.gsub!(rx) { |m| m.bgyellow.black }
  else
    query = search.strip.to_phrase_query

    if query[:must].nil? && query[:must_not].nil?
      query[:must] = query[:should]
      query[:should] = []
    end
    qs = []
    qs.concat(query[:must]) if query[:must]
    qs.concat(query[:should]) if query[:should]
    qs.each do |s|
      rx = Regexp.new(s.wildcard_to_rx, ignore_case(s, case_type))
      out.gsub!(rx) do
        m = Regexp.last_match
        last = m.pre_match.last_color_code
        "#{m[0].bgyellow.black}#{last}"
      end
    end
  end
  out
end