Skip to content

Commit d7f35e9

Browse files
author
Michal Niewrzal
committed
Support document formatting felixfbecker#8
1 parent d1b9b33 commit d7f35e9

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/LanguageServer.php

+2
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ public function initialize(string $rootPath, int $processId, ClientCapabilities
7474
$serverCapabilities->textDocumentSync = TextDocumentSyncKind::FULL;
7575
// Support "Find all symbols"
7676
$serverCapabilities->documentSymbolProvider = true;
77+
// Support "Format Code"
78+
$serverCapabilities->documentFormattingProvider = true;
7779
return new InitializeResult($serverCapabilities);
7880
}
7981

src/Server/TextDocument.php

+25-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
namespace LanguageServer\Server;
44

5-
use PhpParser\{Error, Comment, Node, ParserFactory, NodeTraverser, Lexer};
5+
use PhpParser\{Error, Comment, Node, ParserFactory, NodeTraverser, Lexer, PrettyPrinter\Standard as PrettyPrinterStandard};
66
use PhpParser\NodeVisitor\NameResolver;
77
use LanguageServer\{LanguageClient, ColumnCalculator, SymbolFinder};
88
use LanguageServer\Protocol\{
@@ -12,7 +12,9 @@
1212
Diagnostic,
1313
DiagnosticSeverity,
1414
Range,
15-
Position
15+
Position,
16+
FormattingOptions,
17+
TextEdit
1618
};
1719

1820
/**
@@ -124,4 +126,25 @@ private function updateAst(string $uri, string $content)
124126
$this->asts[$uri] = $stmts;
125127
}
126128
}
129+
130+
/**
131+
* The document formatting request is sent from the server to the client to format a whole document.
132+
*
133+
* @param TextDocumentIdentifier $textDocument The document to format
134+
* @param FormattingOptions $options The format options
135+
* @return TextEdit[]
136+
*/
137+
public function formatting(TextDocumentIdentifier $textDocument, FormattingOptions $options)
138+
{
139+
$nodes = $this->asts[$textDocument->uri];
140+
if (empty($nodes)){
141+
return [];
142+
}
143+
$prettyPrinter = new PrettyPrinterStandard();
144+
$edit = new TextEdit();
145+
$edit->range = new Range(new Position(0, 0), new Position(PHP_INT_MAX, PHP_INT_MAX));
146+
$edit->newText = $prettyPrinter->prettyPrintFile($this->asts[$textDocument->uri]);
147+
return [$edit];
148+
}
149+
127150
}

0 commit comments

Comments
 (0)