我相信这个功能是在 LSP 规范 3.15 中引入的:https ://microsoft.github.io/language-server-protocol/specifications/specification-3-15
我创建了以下类来帮助更新、创建和删除文件:
import { DocumentUri, OptionalVersionedTextDocumentIdentifier, Position, Range } from 'vscode-languageserver';
import { WorkspaceChange, ApplyWorkspaceEditResponse} from 'vscode-languageserver-protocol';
import { connection } from "../server";
export class WSUpdates{
private _wschanges: WorkspaceChange;
constructor(){
this._wschanges = new WorkspaceChange();
}
hasChanges(): boolean{
return (this._wschanges.edit.changes != undefined || this._wschanges.edit.documentChanges != undefined);
}
createFile(uri: DocumentUri, contents: string, overwrite: boolean){
this._wschanges.createFile(uri, {overwrite: overwrite});
const edit = this._wschanges.edit;
const change = this._wschanges.getTextEditChange(OptionalVersionedTextDocumentIdentifier.create(uri,null));
this.insertText(uri,contents,0,0);
}
renameFile(uri:DocumentUri, newUri: DocumentUri, overwrite: boolean){
this._wschanges.renameFile(uri, newUri, { overwrite: overwrite});
}
deleteFileFolder(uri:DocumentUri, recursive: boolean, ignoreIfNotExists: boolean){
this._wschanges.deleteFile(uri, { recursive: recursive, ignoreIfNotExists: ignoreIfNotExists});
}
insertText(uri: DocumentUri, contents: string, line: number, column: number){
const change = this._wschanges.getTextEditChange(OptionalVersionedTextDocumentIdentifier.create(uri, null));
change.insert(Position.create(line,column),contents);
}
replaceText(uri: DocumentUri, contents: string, startLine: number, startColumn: number, endLine: number, endColumn: number){
const change = this._wschanges.getTextEditChange(OptionalVersionedTextDocumentIdentifier.create(uri,null));
change.replace(
Range.create(Position.create(startLine, startColumn), Position.create(endLine, endColumn)),
contents
);
}
replaceAllText(uri: DocumentUri, contents: string){
this.replaceText(uri, contents, 0,0,Number.MAX_VALUE, Number.MAX_VALUE);
}
deleteText(uri: DocumentUri, contents: string, startLine: number, startColumn: number, endLine: number, endColumn: number){
const change = this._wschanges.getTextEditChange(OptionalVersionedTextDocumentIdentifier.create(uri,null));
change.delete(
Range.create(Position.create(startLine, startColumn), Position.create(endLine, endColumn))
);
}
async applyChanges(): Promise<ApplyWorkspaceEditResponse>{
return connection.workspace.applyEdit(this._wschanges.edit);
}
}
您可以从您的服务器代码中调用此类。例如
const wsu = new WSUpdates();
wsu.createFile('file.txt','Creating a new file\n');
const resp = await wsu.applyChanges();
if (!resp.applied){
console.log('Handle failure');
}
要记住的一件事是更改不能在相同文件上重叠。