Class: RubyLsp::Requests::Formatting

Inherits:
RuboCopRequest show all
Defined in:
lib/ruby_lsp/requests/formatting.rb

Overview

The [formatting](microsoft.github.io/language-server-protocol/specification#textDocument_formatting) request uses RuboCop to fix auto-correctable offenses in the document. This requires enabling format on save and registering the ruby-lsp as the Ruby formatter.

# Example

“‘ruby def say_hello puts “Hello” # –> formatting: fixes the indentation on save end “`

Constant Summary collapse

RUBOCOP_FLAGS =
(COMMON_RUBOCOP_FLAGS + ["--autocorrect"]).freeze

Constants inherited from RuboCopRequest

RuboCopRequest::COMMON_RUBOCOP_FLAGS

Instance Attribute Summary

Attributes inherited from RuboCopRequest

#file, #text

Instance Method Summary collapse

Methods inherited from RuboCopRequest

run

Constructor Details

#initialize(uri, document) ⇒ Formatting

Returns a new instance of Formatting.



20
21
22
23
# File 'lib/ruby_lsp/requests/formatting.rb', line 20

def initialize(uri, document)
  super
  @formatted_text = nil
end

Instance Method Details

#runObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ruby_lsp/requests/formatting.rb', line 25

def run
  super

  @formatted_text = @options[:stdin] # Rubocop applies the corrections on stdin
  return unless @formatted_text

  [
    LanguageServer::Protocol::Interface::TextEdit.new(
      range: LanguageServer::Protocol::Interface::Range.new(
        start: LanguageServer::Protocol::Interface::Position.new(line: 0, character: 0),
        end: LanguageServer::Protocol::Interface::Position.new(
          line: text.size,
          character: text.size
        )
      ),
      new_text: @formatted_text
    ),
  ]
end