Skip to content

Commit a96a554

Browse files
Fix formatting of unsaved files
Instead of loading the file from url, we load it from a snapshot which fixes an issue where files that weren't yet saved were formatted incorrectly.
1 parent d75c4ac commit a96a554

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Sources/SourceKit/sourcekitd/SwiftLanguageServer.swift

+8-4
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,11 @@ extension SwiftLanguageServer {
692692
req.reply(nil)
693693
return
694694
}
695+
guard let snapshot = self.documentManager.latestSnapshot(req.params.textDocument.uri) else {
696+
log("failed to find snapshot for url \(req.params.textDocument.uri)")
697+
req.reply(nil)
698+
return
699+
}
695700
let options = req.params.options
696701
self.queue.async {
697702
let configuration: SwiftFormatConfiguration.Configuration
@@ -709,14 +714,13 @@ extension SwiftLanguageServer {
709714

710715
let formatter = SwiftFormat.SwiftFormatter(configuration: configuration)
711716
do {
712-
let lines = try LineTable(String(contentsOf: file))
713-
guard let lastLine = lines.last else {
717+
guard let lastLine = snapshot.lineTable.last else {
714718
req.reply(nil)
715719
return
716720
}
717-
let lastPosition = Position(line: lines.count-1, utf16index: lastLine.utf16.count)
721+
let lastPosition = Position(line: snapshot.lineTable.count-1, utf16index: lastLine.utf16.count)
718722
var edit = TextEdit(range: Position(line: 0, utf16index: 0)..<lastPosition, newText: "")
719-
try formatter.format(contentsOf: file, to: &edit.newText)
723+
try formatter.format(source: snapshot.text, assumingFileURL: file, to: &edit.newText)
720724
req.reply([edit])
721725
} catch {
722726
log("failed to format document: \(error)", level: .error)

0 commit comments

Comments
 (0)