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

#range_from_syntax_tree_node

Constructor Details

#initialize(document, position, trigger_character) ⇒ OnTypeFormatting

Returns a new instance of OnTypeFormatting.



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

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

  scanner = Document::Scanner.new(document.source)
  line_begin = position[:line] == 0 ? 0 : scanner.find_position({ line: position[:line] - 1, character: 0 })
  line_end = scanner.find_position(position)
  line = T.must(@document.source[line_begin..line_end])

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

Instance Method Details

#runObject



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

def run
  handle_comment_line

  return @edits unless @document.syntax_errors?

  case @trigger_character
  when "{"
    handle_curly_brace
  when "|"
    handle_pipe
  when "\n"
    handle_statement_end
  end

  @edits
end