Class: RubyLsp::Requests::OnTypeFormatting

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

Overview

![On type formatting demo](../../on_type_formatting.gif)

The [on type formatting](microsoft.github.io/language-server-protocol/specification#textDocument_onTypeFormatting) request formats code as the user is typing. For example, automatically adding ‘end` to class definitions.

# Example

“‘ruby class Foo # <– upon adding a line break, on type formatting is triggered

# <-- cursor ends up here

end # <– end is automatically added “‘

Constant Summary collapse

END_REGEXES =
T.let(
  [
    /(if|unless|for|while|class|module|until|def|case).*/,
    /.*\sdo/,
  ],
  T::Array[Regexp],
)

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, position, trigger_character) ⇒ OnTypeFormatting

Returns a new instance of OnTypeFormatting.



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

def initialize(document, position, trigger_character)
  super(document)

  @lines = T.let(@document.source.lines, T::Array[String])
  line = @lines[[position[:line] - 1, 0].max]

  @indentation = T.let(line ? find_indentation(line) : 0, Integer)
  @previous_line = T.let(line ? line.strip.chomp : "", String)
  @position = position
  @edits = T.let([], T::Array[Interface::TextEdit])
  @trigger_character = trigger_character
end

Instance Method Details

#runObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ruby_lsp/requests/on_type_formatting.rb', line 44

def run
  case @trigger_character
  when "{"
    handle_curly_brace if @document.syntax_error?
  when "|"
    handle_pipe if @document.syntax_error?
  when "\n"
    if (comment_match = @previous_line.match(/^#(\s*)/))
      handle_comment_line(T.must(comment_match[1]))
    elsif @document.syntax_error?
      handle_statement_end
    end
  end

  @edits
end