Class: RegexpExpression

Inherits:
Expression show all
Includes:
Highlight
Defined in:
lib/glark/match/re.rb

Overview

Applies a regular expression against a File.

Constant Summary

Constants included from Highlight

Highlight::RESET

Instance Attribute Summary collapse

Attributes inherited from Expression

#matches

Instance Method Summary collapse

Methods included from Highlight

#adorn

Methods inherited from Expression

#add_match, #end_position, #process, #reset_file, #start_position, #to_s

Constructor Details

#initialize(re, hlidx, text_colors = nil, extract_matches = false) ⇒ RegexpExpression

Returns a new instance of RegexpExpression.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/glark/match/re.rb', line 15

def initialize re, hlidx, text_colors = nil, extract_matches = false
  @re = re

  if @text_colors = text_colors
    @hlidx = if @text_colors.length > 0
               hlidx % @text_colors.length
             else
               0
             end 
  end    
  @extract_matches = extract_matches
  
  super()
end

Instance Attribute Details

#reObject (readonly)

Returns the value of attribute re.



13
14
15
# File 'lib/glark/match/re.rb', line 13

def re
  @re
end

Instance Method Details

#==(other) ⇒ Object



30
31
32
# File 'lib/glark/match/re.rb', line 30

def == other
  @re == other.re
end

#evaluate(line, lnum, file, formatter) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/glark/match/re.rb', line 46

def evaluate line, lnum, file, formatter
  md = match? line
  return false unless md

  if @extract_matches
    if md.kind_of? MatchData
      line.replace md[-1] + "\n"
    else
      warn "--not is incompatible with -v"
    end
  end
  
  @match_line_number = lnum

  if @text_colors && @text_colors.size > 0
    highlight_match lnum, file, formatter
  end
  
  add_match lnum
  true
end

#explain(level = 0) ⇒ Object



68
69
70
# File 'lib/glark/match/re.rb', line 68

def explain level = 0
  " " * level + to_s + "\n"
end

#highlight_match(lnum, file, formatter) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/glark/match/re.rb', line 72

def highlight_match lnum, file, formatter
  lnums = file.get_region lnum
  return unless lnums

  lnums.each do |ln|
    str = formatter.formatted[ln] || file.get_line(ln)
    formatter.formatted[ln] = str.gsub(@re) do |m|
      lastcapts = Regexp.last_match.captures
      # the index of the first non-nil capture:
      miidx = (0 ... lastcapts.length).find { |mi| lastcapts[mi] } || @hlidx
      adorn(@text_colors[miidx], m)
    end
  end
end

#inspectObject



34
35
36
# File 'lib/glark/match/re.rb', line 34

def inspect
  @re.inspect
end

#match?(line) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
# File 'lib/glark/match/re.rb', line 38

def match? line
  begin
    @re.match line
  rescue
    false
  end
end