@@ -25,6 +25,7 @@ bool LanguageService::Initialize()
2525 _handles[" textDocument/formatting" ] = DynamicBind (OnFormatting, vscode::DocumentFormattingParams);
2626 _handles[" textDocument/didClose" ] = DynamicBind (OnClose, vscode::DidCloseTextDocumentParams);
2727 _handles[" updateEditorConfig" ] = DynamicBind (OnEditorConfigUpdate, vscode::EditorConfigUpdateParams);
28+ _handles[" textDocument/rangeFormatting" ] = DynamicBind (OnRangeFormatting, vscode::DocumentRangeFormattingParams);
2829 return true ;
2930}
3031
@@ -44,6 +45,7 @@ std::shared_ptr<vscode::InitializeResult> LanguageService::OnInitialize(std::sha
4445 auto result = std::make_shared<vscode::InitializeResult>();
4546
4647 result->capabilities .documentFormattingProvider = true ;
48+ result->capabilities .documentRangeFormattingProvider = true ;
4749 result->capabilities .textDocumentSync .change = vscode::TextDocumentSyncKind::Full;
4850 result->capabilities .textDocumentSync .openClose = true ;
4951
@@ -52,7 +54,7 @@ std::shared_ptr<vscode::InitializeResult> LanguageService::OnInitialize(std::sha
5254 {
5355 LanguageClient::GetInstance ().UpdateOptions (configFile.workspace , configFile.path );
5456 }
55- result-> capabilities . codeActionProvider = true ;
57+
5658
5759 return result;
5860}
@@ -144,3 +146,41 @@ std::shared_ptr<vscode::Serializable> LanguageService::OnEditorConfigUpdate(
144146
145147 return nullptr ;
146148}
149+
150+ std::shared_ptr<vscode::Serializable> LanguageService::OnRangeFormatting (
151+ std::shared_ptr<vscode::DocumentRangeFormattingParams> param)
152+ {
153+ auto text = LanguageClient::GetInstance ().GetFile (param->textDocument .uri );
154+
155+ auto result = std::make_shared<vscode::DocumentFormattingResult>();
156+
157+ if (text.empty ())
158+ {
159+ result->hasError = true ;
160+ return result;
161+ }
162+
163+ auto options = LanguageClient::GetInstance ().GetOptions (param->textDocument .uri );
164+
165+ std::shared_ptr<LuaParser> parser = LuaParser::LoadFromBuffer (std::move (text));
166+ parser->BuildAstWithComment ();
167+
168+ if (parser->HasError ())
169+ {
170+ result->hasError = true ;
171+ return result;
172+ }
173+
174+ LuaFormatter formatter (parser, *options);
175+ formatter.BuildFormattedElement ();
176+
177+ auto & edit = result->edits .emplace_back ();
178+ LuaFormatRange formattedRange (param->range .start .line , param->range .end .line );
179+
180+ edit.newText = formatter.GetRangeFormattedText (formattedRange);
181+ edit.range = vscode::Range (
182+ vscode::Position (formattedRange.StartLine , 0 ),
183+ vscode::Position (formattedRange.EndLine + 1 , 0 )
184+ );
185+ return result;
186+ }
0 commit comments