Class: RubyLsp::Requests::CodeActions

Inherits:
BaseRequest
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/ruby_lsp/requests/code_actions.rb

Overview

![Code actions demo](../../code_actions.gif)

The [code actions](microsoft.github.io/language-server-protocol/specification#textDocument_codeAction) request informs the editor of RuboCop quick fixes that can be applied. These are accessible by hovering over a specific diagnostic.

# Example

“‘ruby def say_hello puts “Hello” # –> code action: quick fix indentation end “`

Instance Method Summary collapse

Methods inherited from BaseRequest

#visit_all

Methods included from Support::Common

#create_code_lens, #markdown_from_index_entries, #range_from_location, #range_from_node, #visible?

Constructor Details

#initialize(document, range, context) ⇒ CodeActions

Returns a new instance of CodeActions.



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

def initialize(document, range, context)
  super(document)

  @uri = T.let(document.uri, URI::Generic)
  @range = range
  @context = context
end

Instance Method Details

#runObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ruby_lsp/requests/code_actions.rb', line 38

def run
  diagnostics = @context[:diagnostics]

  code_actions = diagnostics.filter_map do |diagnostic|
    code_action = diagnostic.dig(:data, :code_action)
    next if code_action.nil?

    # We want to return only code actions that are within range or that do not have any edits, such as refactor
    # code actions
    range = code_action.dig(:edit, :documentChanges, 0, :edits, 0, :range)
    code_action if diagnostic.dig(:data, :correctable) && cover?(range)
  end

  # Only add refactor actions if there's a non empty selection in the editor
  code_actions << refactor_code_action(@range, @uri) unless @range.dig(:start) == @range.dig(:end)
  code_actions
end