Class: RubyLsp::Requests::DocumentHighlight

Inherits:
BaseRequest
  • Object
show all
Defined in:
lib/ruby_lsp/requests/document_highlight.rb

Overview

The [document highlight](microsoft.github.io/language-server-protocol/specification#textDocument_documentHighlight) informs the editor all relevant elements of the currently pointed item for highlighting. For example, when the cursor is on the ‘F` of the constant `FOO`, the editor should identify other occurences of `FOO` and highlight them.

For writable elements like constants or variables, their read/write occurrences should be highlighted differently. This is achieved by sending different “kind” attributes to the editor (2 for read and 3 for write).

# Example

“‘ruby FOO = 1 # should be highlighted as “write”

def foo

FOO # should be highlighted as "read"

end “‘

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseRequest

#range_from_syntax_tree_node

Constructor Details

#initialize(document, position) ⇒ DocumentHighlight

Returns a new instance of DocumentHighlight.



28
29
30
31
32
33
34
# File 'lib/ruby_lsp/requests/document_highlight.rb', line 28

def initialize(document, position)
  @highlights = []
  position = Document::Scanner.new(document.source).find_position(position)
  @target = find(document.tree, position)

  super(document)
end

Class Method Details

.run(document, position) ⇒ Object



24
25
26
# File 'lib/ruby_lsp/requests/document_highlight.rb', line 24

def self.run(document, position)
  new(document, position).run
end

Instance Method Details

#runObject



36
37
38
39
40
41
42
# File 'lib/ruby_lsp/requests/document_highlight.rb', line 36

def run
  # no @target means the target is not highlightable
  return [] unless @target

  visit(@document.tree)
  @highlights
end

#visit_var_field(node) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/ruby_lsp/requests/document_highlight.rb', line 44

def visit_var_field(node)
  if matches_target?(node.value)
    add_highlight(
      node.value,
      LanguageServer::Protocol::Constant::DocumentHighlightKind::WRITE
    )
  end

  super
end

#visit_var_ref(node) ⇒ Object



55
56
57
58
59
60
61
62
63
64
# File 'lib/ruby_lsp/requests/document_highlight.rb', line 55

def visit_var_ref(node)
  if matches_target?(node.value)
    add_highlight(
      node.value,
      LanguageServer::Protocol::Constant::DocumentHighlightKind::READ
    )
  end

  super
end