Class: RubyLsp::Requests::Formatting

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

Overview

![Formatting symbol demo](../../misc/formatting.gif)

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.

If RuboCop is not available, the request will fall back to SyntaxTree.

# Example

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

Defined Under Namespace

Classes: Error, InvalidFormatter

Instance Method Summary collapse

Methods inherited from BaseRequest

#full_constant_name, #locate, #range_from_syntax_tree_node, #visible?, #visit_all

Constructor Details

#initialize(uri, document, formatter: "auto") ⇒ Formatting

Returns a new instance of Formatting.



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

def initialize(uri, document, formatter: "auto")
  super(document)

  @uri = uri
  @formatter = T.let(
    if formatter == "auto"
      defined?(Support::RuboCopFormattingRunner) ? "rubocop" : "syntax_tree"
    else
      formatter
    end,
    String,
  )
end

Instance Method Details

#runObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ruby_lsp/requests/formatting.rb', line 45

def run
  # Don't try to format files outside the current working directory
  return unless @uri.sub("file://", "").start_with?(Dir.pwd)

  return if @document.syntax_error?

  formatted_text = formatted_file
  return unless formatted_text

  size = @document.source.size
  return if formatted_text.size == size && formatted_text == @document.source

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