Class: TypeProf::LSP::Text

Inherits:
Object
  • Object
show all
Defined in:
lib/typeprof/lsp/text.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, text, version) ⇒ Text

Returns a new instance of Text.



3
4
5
6
7
# File 'lib/typeprof/lsp/text.rb', line 3

def initialize(path, text, version)
  @path = path
  @lines = Text.split(text)
  @version = version
end

Instance Attribute Details

#linesObject (readonly)

Returns the value of attribute lines.



9
10
11
# File 'lib/typeprof/lsp/text.rb', line 9

def lines
  @lines
end

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/typeprof/lsp/text.rb', line 9

def path
  @path
end

#versionObject (readonly)

Returns the value of attribute version.



9
10
11
# File 'lib/typeprof/lsp/text.rb', line 9

def version
  @version
end

Class Method Details

.split(str) ⇒ Object



11
12
13
14
15
# File 'lib/typeprof/lsp/text.rb', line 11

def self.split(str)
  lines = str.lines
  lines << "" if lines.empty? || lines.last.include?("\n")
  lines
end

Instance Method Details

#apply_changes(changes, version) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/typeprof/lsp/text.rb', line 21

def apply_changes(changes, version)
  changes.each do |change|
    change => {
      range: {
          start: { line: start_row, character: start_col },
          end:   { line: end_row  , character: end_col   }
      },
      text: new_text,
    }

    new_text = Text.split(new_text)

    prefix = @lines[start_row][0...start_col]
    suffix = @lines[end_row][end_col...]
    if new_text.size == 1
      new_text[0] = prefix + new_text[0] + suffix
    else
      new_text[0] = prefix + new_text[0]
      new_text[-1] = new_text[-1] + suffix
    end
    @lines[start_row .. end_row] = new_text
  end

  validate

  @version = version
end

#modify_for_completion(changes, pos) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/typeprof/lsp/text.rb', line 54

def modify_for_completion(changes, pos)
  pos => { line: row, character: col }
  if col >= 2 && @lines[row][col - 1] == "." && (col == 1 || @lines[row][col - 2] != ".")
    @lines[row][col - 1] = " "
    yield string, ".", { line: row, character: col - 2}
    @lines[row][col - 1] = "."
  elsif col >= 3 && @lines[row][col - 2, 2] == "::"
    @lines[row][col - 2, 2] = "  "
    yield string, "::", { line: row, character: col - 3 }
    @lines[row][col - 2, 2] = "::"
  else
    yield string, nil, { line: row, character: col }
  end
end

#stringObject



17
18
19
# File 'lib/typeprof/lsp/text.rb', line 17

def string
  @lines.join
end

#validateObject



49
50
51
52
# File 'lib/typeprof/lsp/text.rb', line 49

def validate
  raise unless @lines[0..-2].all? {|s| s.count("\n") == 1 && s.end_with?("\n") }
  raise unless @lines[-1].count("\n") == 0
end