class Kramdown::Utils::StringScanner

This patched StringScanner adds line number information for current scan position and a start_line_number override for nested StringScanners.

Attributes

start_line_number[R]

The start line number. Used for nested StringScanners that scan a sub-string of the source document. The kramdown parser uses this, e.g., for span level parsers.

Public Class Methods

new(string, start_line_number = 1) click to toggle source

Takes the start line number as optional second argument.

Note: The original second argument is no longer used so this should be safe.

Calls superclass method
   # File lib/kramdown/utils/string_scanner.rb
26 def initialize(string, start_line_number = 1)
27   super(string)
28   @start_line_number = start_line_number || 1
29   @previous_pos = 0
30   @previous_line_number = @start_line_number
31 end

Public Instance Methods

current_line_number() click to toggle source

Returns the line number for current charpos.

NOTE: Requires that all line endings are normalized to 'n'

NOTE: Normally we'd have to add one to the count of newlines to get the correct line number. However we add the one indirectly by using a one-based start_line_number.

   # File lib/kramdown/utils/string_scanner.rb
67 def current_line_number
68   # Not using string[@previous_pos..best_pos].count('\n') because it is slower
69   strscan = ::StringScanner.new(string)
70   strscan.pos = @previous_pos
71   old_pos = pos + 1
72   @previous_line_number += 1 while strscan.skip_until(/\n/) && strscan.pos <= old_pos
73 
74   @previous_pos = (eos? ? pos : pos + 1)
75   @previous_line_number
76 end
pos=(pos) click to toggle source

Sets the byte position of the scan pointer.

Note: This also resets some internal variables, so always use pos= when setting the position and don't use any other method for that!

Calls superclass method
   # File lib/kramdown/utils/string_scanner.rb
37 def pos=(pos)
38   if self.pos > pos
39     @previous_line_number = @start_line_number
40     @previous_pos = 0
41   end
42   super
43 end
revert_pos(data) click to toggle source

Revert the position to one saved by save_pos.

   # File lib/kramdown/utils/string_scanner.rb
56 def revert_pos(data)
57   self.pos = data[0]
58   @previous_pos, @previous_line_number = data[1], data[2]
59 end
save_pos() click to toggle source

Return information needed to revert the byte position of the string scanner in a performant way.

The returned data can be fed to revert_pos to revert the position to the saved one.

Note: Just saving pos won't be enough.

   # File lib/kramdown/utils/string_scanner.rb
51 def save_pos
52   [pos, @previous_pos, @previous_line_number]
53 end