class Nasl::Context

Public Class Methods

new(code, path) click to toggle source
# 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

Public Instance Methods

bol(point) click to toggle source
# File lib/nasl/context.rb, line 51
def bol(point)
  @newlines.find { |nl| nl <= point }
end
col(point) click to toggle source
# 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) click to toggle source
# 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 = Rainbow(line).color(:green) if color
    ctx << line
  end

  # Create the text in the region.
  line = @code[inner.begin...inner.end]
  line = Rainbow(line).color(:red) if color
  ctx << line

  # Create the text to the right of the region.
  line = @code[inner.end...outer.end].chomp
  line = Rainbow(line).color(:green) if color
  ctx << line

  ctx << "\n"
end
eol(point) click to toggle source
# File lib/nasl/context.rb, line 55
def eol(point)
  @code.index(/\n/, point) || @code.length
end
row(point) click to toggle source
# File lib/nasl/context.rb, line 64
def row(point)
  # Rows use base one indexing.
  @newlines.length - @newlines.index { |nl| nl <= point }
end