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](../../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.

The ‘rubyLsp.formatter` setting specifies which formatter to use. If set to `auto` then it behaves as follows:

  • It will use RuboCop if it is part of the bundle.

  • If RuboCop is not available, and ‘syntax_tree` is a direct dependency, it will use that.

  • Otherwise, no formatting will be applied.

# Example

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

Defined Under Namespace

Classes: Error, InvalidFormatter

Class Attribute Summary collapse

Class Method Summary collapse

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, formatter: "auto") ⇒ Formatting

Returns a new instance of Formatting.



57
58
59
60
61
62
# File 'lib/ruby_lsp/requests/formatting.rb', line 57

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

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

Class Attribute Details

.formattersObject (readonly)

Returns the value of attribute formatters.



38
39
40
# File 'lib/ruby_lsp/requests/formatting.rb', line 38

def formatters
  @formatters
end

Class Method Details

.register_formatter(identifier, instance) ⇒ Object



41
42
43
# File 'lib/ruby_lsp/requests/formatting.rb', line 41

def register_formatter(identifier, instance)
  @formatters[identifier] = instance
end

Instance Method Details

#runObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/ruby_lsp/requests/formatting.rb', line 65

def run
  return if @formatter == "none"

  # Don't try to format files outside the current working directory
  path = @uri.to_standardized_path
  return unless path.nil? || path.start_with?(T.must(WORKSPACE_URI.to_standardized_path))

  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