Class: RubyLsp::Requests::Formatting
- Inherits:
-
BaseRequest
- Object
- SyntaxTree::Visitor
- BaseRequest
- RubyLsp::Requests::Formatting
- Extended by:
- T::Sig
- 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.
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
-
.formatters ⇒ Object
readonly
Returns the value of attribute formatters.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(document, formatter: "auto") ⇒ Formatting
constructor
A new instance of Formatting.
- #run ⇒ Object
Methods inherited from BaseRequest
Methods included from Support::Common
#create_code_lens, #full_constant_name, #range_from_syntax_tree_node, #visible?
Constructor Details
permalink #initialize(document, formatter: "auto") ⇒ Formatting
Returns a new instance of Formatting.
58 59 60 61 62 63 |
# File 'lib/ruby_lsp/requests/formatting.rb', line 58 def initialize(document, formatter: "auto") super(document) @uri = T.let(document.uri, String) @formatter = formatter end |
Class Attribute Details
permalink .formatters ⇒ Object (readonly)
Returns the value of attribute formatters.
43 44 45 |
# File 'lib/ruby_lsp/requests/formatting.rb', line 43 def formatters @formatters end |
Class Method Details
permalink .register_formatter(identifier, instance) ⇒ Object
[View source]
46 47 48 |
# File 'lib/ruby_lsp/requests/formatting.rb', line 46 def register_formatter(identifier, instance) @formatters[identifier] = instance end |
Instance Method Details
permalink #run ⇒ Object
[View source]
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 66 def run return if @formatter == "none" # 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 |