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
25 def initialize(string, start_line_number = 1)
26   super(string)
27   @start_line_number = start_line_number || 1
28   @previous_pos = 0
29   @previous_line_number = @start_line_number
30 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
66 def current_line_number
67   # Not using string[@previous_pos..best_pos].count('\n') because it is slower
68   strscan = ::StringScanner.new(string)
69   strscan.pos = @previous_pos
70   old_pos = pos + 1
71   @previous_line_number += 1 while strscan.skip_until(/\n/) && strscan.pos <= old_pos
72 
73   @previous_pos = (eos? ? pos : pos + 1)
74   @previous_line_number
75 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
36 def pos=(pos)
37   if self.pos > pos
38     @previous_line_number = @start_line_number
39     @previous_pos = 0
40   end
41   super
42 end
revert_pos(data) click to toggle source

Revert the position to one saved by save_pos.

   # File lib/kramdown/utils/string_scanner.rb
55 def revert_pos(data)
56   self.pos = data[0]
57   @previous_pos, @previous_line_number = data[1], data[2]
58 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
50 def save_pos
51   [pos, @previous_pos, @previous_line_number]
52 end