Class: Nasl::Context
- Inherits:
-
Object
- Object
- Nasl::Context
- Defined in:
- lib/nasl/context.rb
Instance Method Summary collapse
- #bol(point) ⇒ Object
- #col(point) ⇒ Object
- #context(inner, outer = nil, header = true, color = true) ⇒ Object
- #eol(point) ⇒ Object
-
#initialize(code, path) ⇒ Context
constructor
A new instance of Context.
- #row(point) ⇒ Object
Constructor Details
#initialize(code, path) ⇒ Context
Returns a new instance of Context.
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/nasl/context.rb', line 31 def initialize(code, path) @code = code @path = path # Find all of the newlines in the source code. i = 0 @newlines = @code.split(/\n/).map do |nl| i += 1 + nl.length end # Treat the start and end of the file as a newlines to simplify the bol # and eol functions. @newlines.unshift(0) @newlines.push(@code.length) # Storing the list of newlines in descending order makes the row and # column code nicer. @newlines.reverse! end |
Instance Method Details
#bol(point) ⇒ Object
51 52 53 |
# File 'lib/nasl/context.rb', line 51 def bol(point) @newlines.find { |nl| nl <= point } end |
#col(point) ⇒ Object
59 60 61 62 |
# File 'lib/nasl/context.rb', line 59 def col(point) # Columns use base zero indexing. point - bol(point) end |
#context(inner, outer = nil, header = true, color = true) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/nasl/context.rb', line 69 def context(inner, outer=nil, header=true, color=true) # If no outer region was provided, we will assume that the desired outer # is from the beginning of the line that the inner region starts on to the # end of the line that the inner region finishes on. outer = bol(inner.begin)..eol(inner.end) if outer.nil? # If the outer region argument was provided, but wasn't a Range, access # its region member. outer = outer.region unless outer.is_a? Range ctx = "" point = inner.begin # Create the location header. ctx << "Context for row #{row(point)}, column #{col(point)} in file #@path:\n" if header # Create the text to the left of the region. The only case where there is # no text to the left is at the start of the program. if outer.begin != inner.begin line = @code[outer.begin...inner.begin] line = line.color(:green) if color ctx << line end # Create the text in the region. line = @code[inner.begin...inner.end] line = line.color(:red) if color ctx << line # Create the text to the right of the region. line = @code[inner.end...outer.end].chomp line = line.color(:green) if color ctx << line ctx << "\n" end |
#eol(point) ⇒ Object
55 56 57 |
# File 'lib/nasl/context.rb', line 55 def eol(point) @code.index(/\n/, point) || @code.length end |
#row(point) ⇒ Object
64 65 66 67 |
# File 'lib/nasl/context.rb', line 64 def row(point) # Rows use base one indexing. @newlines.length - @newlines.index { |nl| nl <= point } end |