Class: RubyLsp::Requests::DocumentHighlight

Inherits:
BaseRequest
  • Object
show all
Extended by:
T::Sig
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 “‘

Constant Summary collapse

VarNodes =
T.type_alias do
  T.any(
    SyntaxTree::GVar,
    SyntaxTree::Ident,
    SyntaxTree::IVar,
    SyntaxTree::Const,
    SyntaxTree::CVar
  )
end

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.



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

def initialize(document, position)
  @highlights = T.let([], T::Array[LanguageServer::Protocol::Interface::DocumentHighlight])
  position = Document::Scanner.new(document.source).find_position(position)
  @target = T.let(find(document.tree, position), T.nilable(VarNodes))

  super(document)
end

Instance Method Details

#runObject



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

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

  visit(@document.tree)
  @highlights
end

#visit_var_field(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_field(node)
  if matches_target?(node.value)
    add_highlight(
      node.value,
      LanguageServer::Protocol::Constant::DocumentHighlightKind::WRITE
    )
  end

  super
end

#visit_var_ref(node) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/ruby_lsp/requests/document_highlight.rb', line 67

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

  super
end