Class: Solargraph::Source::Change

Inherits:
Object
  • Object
show all
Includes:
EncodingFixes
Defined in:
lib/solargraph/source/change.rb

Overview

A change to be applied to text.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from EncodingFixes

normalize

Constructor Details

#initialize(range, new_text) ⇒ Change

Returns a new instance of Change.

Parameters:

  • range (Range)

    The starting and ending positions of the change. If nil, the original text will be overwritten.

  • new_text (String)

    The text to be changed.



19
20
21
22
# File 'lib/solargraph/source/change.rb', line 19

def initialize range, new_text
  @range = range
  @new_text = new_text
end

Instance Attribute Details

#new_textString (readonly)

Returns:

  • (String)


14
15
16
# File 'lib/solargraph/source/change.rb', line 14

def new_text
  @new_text
end

#rangeRange (readonly)

Returns:



11
12
13
# File 'lib/solargraph/source/change.rb', line 11

def range
  @range
end

Instance Method Details

#repair(text) ⇒ String

Repair an update by replacing the new text with similarly formatted whitespace.

Parameters:

  • text (String)

    The text to be changed.

Returns:

  • (String)

    The updated text.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/solargraph/source/change.rb', line 55

def repair text
  fixed = new_text.gsub(/[^\s]/, ' ')
  if range.nil?
    fixed
  else
    result = commit text, fixed
    off = Position.to_offset(text, range.start)
    match = result[0, off].match(/[\.:]+\z/)
    if match
      result = result[0, off].sub(/#{match[0]}\z/, ' ' * match[0].length) + result[off..-1]
    end
    result
  end
end

#write(text, nullable = false) ⇒ String

Write the change to the specified text.

Parameters:

  • text (String)

    The text to be changed.

  • nullable (Boolean) (defaults to: false)

    If true, minor changes that could generate syntax errors will be repaired.

Returns:

  • (String)

    The updated text.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/solargraph/source/change.rb', line 30

def write text, nullable = false
  if nullable and !range.nil? and new_text.match(/[\.\[\{\(@\$:]$/)
    [':', '@'].each do |dupable|
      next unless new_text == dupable
      offset = Position.to_offset(text, range.start)
      if text[offset - 1] == dupable
        p = Position.from_offset(text, offset - 1)
        r = Change.new(Range.new(p, range.start), ' ')
        text = r.write(text)
      end
      break
    end
    commit text, "#{new_text[0..-2]} "
  elsif range.nil?
    new_text
  else
    commit text, new_text
  end
end