Language Server Protocol 的 textDocument/didClose 通知:文档关闭同步机制全解析
Language Server Protocol 的 textDocument/didClose 通知:文档关闭同步机制全解析
导读
textDocument/didClose 是 Language Server Protocol(LSP)文本同步(Text Document Synchronization)机制中"关闭"环节的基石通知:当客户端(编辑器/IDE)关闭某个文本文档时,它必须通过该通知告知语言服务器放弃对文档内容的管理权,使文档的"主副本"(master/truth)回到 URI 指向的位置(如磁盘文件)。本文基于本仓库 3.17 版规范文档 展开,结合 完整规范、元模型 与 Notebook 同步扩展,深入讲解该通知的消息结构、语义约束、能力协商、与 didOpen/didChange 的配合,以及实现语言服务器与客户端时需要遵循的实战要点。读完本文,你将能准确实现与调试文档关闭生命周期,避免"脏同步"引发的各类状态错误。
一、didClose 在文本同步机制中的定位
LSP 的文本同步(Text Document Synchronization)是语言服务器与客户端之间建立"内容共识"的机制。根据 规范第 484 行起的章节,客户端对 textDocument/didOpen、textDocument/didChange 和 textDocument/didClose 三个通知的支持是强制性的(mandatory),客户端不能选择不支持;服务器则必须要么三个全部实现、要么全部不实现。三者共同组成一个完整的内容管理闭环:
| 通知 | 方向 | 作用 |
|---|---|---|
textDocument/didOpen |
客户端 → 服务器 | 宣告客户端接管文档内容(master 在客户端) |
textDocument/didChange |
客户端 → 服务器 | 同步文档变更(全量或增量) |
textDocument/didClose |
客户端 → 服务器 | 宣告关闭文档,内容主副本回到 URI 指向处 |
在 didChange 的版本同步示例 中可以看到典型序列:文档版本 v5 发生变更后客户端先发送 textDocument/didChange 同步到服务器,再基于该版本发起 textDocument/completion 请求;版本 v6 再次变更则再次同步。而 didClose 则是这条同步链路的"终点"——它告诉服务器:从现在起,我不再维护这份内容了。
二、通知消息定义:方法、参数与注册选项
2.1 消息元信息
依据 didClose.md,该通知的定义要点如下:
- 方法(method):
textDocument/didClose - 消息方向:客户端 → 服务器(Client → Server,单向通知,无需服务器应答)
- 参数(params):
DidCloseTextDocumentParams - 注册选项(Registration Options):
TextDocumentRegistrationOptions
在 metaModel.json 中,该通知以 clientToServer 方向、TextDocumentRegistrationOptions 注册选项的形式被建模,与元数据中的 didOpen、didChange、didSave 等同步通知并列,可作为自动生成 SDK 或校验客户端/服务器实现的权威依据。
2.2 DidCloseTextDocumentParams 结构
参数类型定义非常精简,只包含一个字段:
interface DidCloseTextDocumentParams {
/**
* The document that was closed.
*/
textDocument: TextDocumentIdentifier;
}
与 didOpen 的参数(携带完整的 TextDocumentItem,包含语言 ID 和文档内容)不同,didClose 不携带文档内容、也不携带语言 ID,仅携带一个 TextDocumentIdentifier:
interface TextDocumentIdentifier {
/**
* The text document's URI.
*/
uri: DocumentUri;
}
也就是说,关闭通知只告诉服务器"哪个 URI 的文档关闭了",服务器据此清理内部为该文档保留的状态。一个完整的关闭通知 JSON 示例:
{
"jsonrpc": "2.0",
"method": "textDocument/didClose",
"params": {
"textDocument": {
"uri": "file:///home/user/projects/demo/src/main.ts"
}
}
}
该结构在 metaModel.json 的 DidCloseTextDocumentParams 定义 中得到印证:唯一属性 textDocument 的类型引用为 TextDocumentIdentifier,文档注释为 "The parameters sent in a close text document notification"。
三、语义细节:close 到底意味着什么
规范对 didClose 语义给出了四点非常关键、容易被忽略的约束:
-
内容主副本回到 URI 指向的位置:收到关闭通知后,文档的 master(真实内容来源)重新存在于 URI 所指之处——若 URI 是
file://文件地址,则内容主副本回到磁盘上。在此之前(didOpen之后)主副本一直在客户端,服务器不得尝试通过该 URI 直接读取文件内容(参见 didOpen.md 中 "the server must not try to read the document's content using the document's Uri")。 -
关闭与编辑器是否可见无关:收到关闭通知并不表示文档之前在编辑器中打开过(例如"内存中管理但从未显示在编辑面板"的文档也会走 open/close)。open/close 语义上只关乎"内容是否由客户端管理",与 UI 展示无关。
-
关闭必须有前置打开:一条
didClose通知必须要求此前发送过对应的didOpen通知。反过来,didOpen 规范 也要求 open 不能在没有对应 close 的情况下对同一文档重复发送——"open 与 close 必须保持平衡,特定 textDocument 的最大 open 计数为 1"。 -
服务器服务能力与文档开闭无关:服务器能否响应请求(如 hover、completion)不取决于文档当前是打开还是关闭状态。这为服务器缓存已关闭文档的语义信息留出了空间——例如关闭文档后仍可基于内存中的索引回答问题,或直接从磁盘重新读取内容。
从实现角度看,服务器收到 didClose 后通常会:清理该文档的内存缓存(如解析树、诊断结果、语义令牌)、释放增量同步的补丁序列,并在需要时保留可供磁盘读取的索引结构。这些属于实现自由,协议本身不强制清理策略。
四、能力协商:谁能收发 didClose
4.1 客户端能力
didClose 归属通用文本同步能力,其客户端能力(Client Capability)定义在 规范第 488 行:
- 属性路径(可选):
textDocument.synchronization.dynamicRegistration - 属性类型:
boolean - 含义:文本文档同步是否支持动态注册(即初始化之后通过
client/registerCapability动态注册textDocument/didClose处理器)
4.2 服务器能力
服务器能力对应 textDocumentSync 属性,类型为 TextDocumentSyncKind | TextDocumentSyncOptions:
export namespace TextDocumentSyncKind {
/**
* Documents should not be synced at all.
*/
export const None = 0;
/**
* Documents are synced by always sending the full content
* of the document.
*/
export const Full = 1;
/**
* Documents are synced by sending the full content on open.
* After that only incremental updates to the document are
* sent.
*/
export const Incremental = 2;
}
export type TextDocumentSyncKind = 0 | 1 | 2;
export interface TextDocumentSyncOptions {
/**
* Open and close notifications are sent to the server. If omitted open
* close notifications should not be sent.
*/
openClose?: boolean;
/**
* Change notifications are sent to the server. See
* TextDocumentSyncKind.None, TextDocumentSyncKind.Full and
* TextDocumentSyncKind.Incremental. If omitted it defaults to
* TextDocumentSyncKind.None.
*/
change?: TextDocumentSyncKind;
}
这里有一个直接影响 didClose 的关键开关:openClose 字段。若服务器在 TextDocumentSyncOptions 中省略或置为 false,客户端不应发送 open/close 通知;若置为 true,则客户端需要为每个打开的文档发送 didOpen,并在关闭时发送 didClose。change 字段则控制 didChange 的同步粒度(None=0 不同步、Full=1 全量、Incremental=2 增量)。
一个典型的服务器声明示例:
{
"capabilities": {
"textDocumentSync": {
"openClose": true,
"change": 2
}
}
}
该声明意味着:客户端将发送 didOpen/didClose,且变更采用增量同步。关于服务器完整能力对象(含 willSave、willSaveWaitUntil、save 等扩展字段)的定义见 规范第 588 行。
4.3 注册选项 TextDocumentRegistrationOptions
didClose 的注册选项为 TextDocumentRegistrationOptions,它通过 documentSelector 限定该同步处理器适用于哪些文档(例如按语言 ID 过滤)。这意味着:即使服务器在 initialize 中声明了同步能力,具体到某类文档是否启用 didClose 仍可由 documentSelector 精确控制;动态注册场景下(客户端声明 dynamicRegistration: true)更是如此。
五、didClose 的典型实战场景
5.1 语言 ID 变更:close 后再 open
这是规范 didOpen.md 明确给出的一个场景:若某文档的语言 ID 发生变化(例如从 JavaScript 切换为 TypeScript),客户端需要:
- 先发送
textDocument/didClose; - 再发送携带新语言 ID 的
textDocument/didOpen(前提是服务器同样支持新语言 ID)。
由于 didClose 参数不携带语言 ID,服务器无法从关闭通知本身感知语言切换,只能通过"close + 新 open"的序列推导出语言变更,并据此重建文档的语言相关状态。
5.2 与 didOpen/didChange 的完整生命周期序列
一个正常文档从打开到关闭的完整同步序列如下:
1. textDocument/didOpen (携带 TextDocumentItem:uri + languageId + version + text)
2. textDocument/didChange (用户输入 → 同步 v5,全量或增量)
3. textDocument/didChange (用户继续输入 → 同步 v6)
4. textDocument/hover (服务器基于已同步状态响应请求)
5. textDocument/didClose (用户关闭文档 → 内容主副本回到磁盘)
任何"孤儿"状态都违反协议约束:没有前置 didOpen 的 didClose、同一 URI 的重复 open(未先 close)、或 open 后从未 close。客户端应保证每一条 didClose 都能与之前的 didOpen 一一配对。
5.3 服务器端处理伪代码
依据规范语义,服务器端一个合规的 didClose 处理器大致如下:
onDidCloseTextDocument((params: DidCloseTextDocumentParams) => {
const uri = params.textDocument.uri;
// 1. 校验:该文档此前必须已 open(若未 open,属客户端协议违规,可记录日志)
if (!openDocuments.has(uri)) {
logger.warn(`didClose for non-open document: ${uri}`);
return;
}
// 2. 清理客户端管理的文档状态(内存内容、增量补丁、诊断结果)
openDocuments.delete(uri);
pendingDiagnostics.delete(uri);
// 3. 可选择性触发对磁盘版本的重新索引或分析(协议不强制)
// 注意:服务器服务能力与文档开闭状态无关,仍可继续响应其请求
});
5.4 Notebook 文档的关闭(3.17 新增)
didClose 的语义在 Notebook 场景下得到了扩展。自 3.17 起,Notebook 文档同步 定义了配套的 notebookDocument/didClose 通知:
- 方法:
notebookDocument/didClose - 前置条件:仅当服务器在
notebookDocumentSync能力中请求notebook同步模式时,客户端才会发送
export interface DidCloseNotebookDocumentParams {
/**
* The notebook document that got closed.
*/
notebookDocument: NotebookDocumentIdentifier;
/**
* The text documents that represent the content
* of a notebook cell that got closed.
*/
cellTextDocuments: TextDocumentIdentifier[];
}
注意其参数结构与 textDocument/didClose 不同:它不仅携带 notebookDocument(仅含 uri 的 NotebookDocumentIdentifier),还携带被关闭的 cellTextDocuments 数组——因为 Notebook 关闭时其单元格对应的文本文档也会一并关闭。而 Notebook 的 open 通知(didOpenNotebookDocumentParams)中则包含 didOpen?: TextDocumentItem[] 与 didClose?: TextDocumentIdentifier[],用于在一次 open 中同时声明单元格文档的打开与关闭状态。
六、边界与常见误区
-
误把 didClose 当作"文档可丢弃"信号:规范明确指出服务器满足请求的能力与文档开闭无关。关闭后服务器仍可能收到针对该文档的请求(例如引用搜索命中一个已关闭的符号),此时服务器应从磁盘或索引读取内容,而不是返回"文档未打开"错误。
-
误以为 didClose 表示文档在编辑器中可见过:open/close 只与"内容由谁管理"有关。没有 UI 展示的文档同样遵循 open/close 生命周期。
-
忘记 open/close 平衡约束:同一 URI 的 open 计数上限为 1,重复 open 必须穿插 close;反之亦然。客户端实现中常用
Map<uri, DocumentState>做配对校验。 -
能力声明不一致:若服务器声明
openClose: true却未处理didClose,或声明openClose缺失而客户端仍发送 open/close,都会造成同步状态混乱。协议要求 open/close/change 三者整体实现或整体不实现,实现时务必成套处理。
七、仓库证据与进一步阅读
- 3.17 didClose 规范原文:通知语义、参数定义
- 3.18 didClose 规范原文:3.18 版本同一通知的定义(语义保持一致)
- 3.17 完整规范 · Text Document Synchronization:能力协商、
TextDocumentSyncKind、TextDocumentSyncOptions - 3.17 didOpen 规范:open 语义、语言 ID 变更时的 close/open 序列
- 3.17 didChange 规范:版本同步示例与状态一致性要求
- TextDocumentIdentifier 类型:
uri: DocumentUri - Text Documents 总述:位置编码(3.17 起支持 UTF-16/UTF-8 协商)与 EOL 约定
- 3.17 元模型 metaModel.json:
textDocument/didClose与DidCloseTextDocumentParams的结构化建模 - 3.17 Notebook 同步:
notebookDocument/didClose与单元格文档关闭
实现语言服务器或客户端时,可将上述规范文档与 metaModel.json 对照使用:元模型是生成类型化 SDK(如 metaModel.ts)的单一事实来源,能有效保证 didClose 等消息在代码层面的参数结构与规范完全一致。
结语
textDocument/didClose 虽然只有一个 textDocument 字段、看似简单,却是 LSP 内容管理闭环中不可缺失的一环。正确理解"内容主副本归属"的切换、"open/close 必须平衡"的约束、能力协商中 openClose 开关的作用,以及语言 ID 变更时"close 后重 open"的流程,是构建健壮语言服务器与客户端的基础。结合本文给出的元模型证据、Notebook 扩展和典型实现伪代码,你可以在自己的 LSP 实现中准确落地这一通知,并借助 dynamicRegistration 与 documentSelector 精细控制其生效范围。