language-server-protocol 文档精读:textDocument/didChange 文档变更通知与客户端-服务端同步机制

原创2026-10-05 10:31:581,723 阅读
文章标签:开发工具

language-server-protocol 文档精读:textDocument/didChange 文档变更通知与客户端-服务端同步机制

导读

textDocument/didChange 是语言服务器协议(LSP)中客户端向服务端同步文本内容变更的核心通知,也是所有语言特性(如补全、悬停、签名帮助)能够基于最新文档状态给出可靠结果的先决条件。本文以本仓库 _specifications/lsp/3.17/ 目录下的规范文档为主线,结合 3.17 版全量规范与 metaModel 机器可读定义,系统讲解该通知的语义、参数结构、三种同步模式、注册选项以及版本演进,帮助你在实现语言服务器或编辑器客户端时正确落地文档同步逻辑。

通知的语义与所有权前提

根据规范,textDocument/didChange 是一个由客户端发往服务端的通知(Notification,:arrow_right: 方向),用于告知服务端某个文本内容发生了变化。其核心约束是:

在客户端修改文本之前,必须先通过 textDocument/didOpen 通知"认领"该文档内容的所有权;打开状态下客户端是文档内容的唯一管理者,服务端不得通过文档 Uri 直接读取磁盘内容。

这一点与 textDocument/didOpen、textDocument/didClose 形成了完整的生命周期闭环。规范(didOpen.md)进一步强调:open 与 close 通知必须成对出现、保持平衡,同一文档的最大打开计数为 1;并且服务端能否处理请求与文档是否处于打开状态相互独立。同样,收到 didClose 后文档的"主版本(master)"重新回到 Uri 指向的位置(例如文件 Uri 对应的磁盘内容),相关内容见 didClose.md。

值得注意的历史事实是:在协议 2.0 版本中,该通知的参数结构发生了改变,加入了规范的版本号字段,这直接催生了下文 VersionedTextDocumentIdentifier 的引入。

同步优先原则:请求之前必须先同步

规范明确给出了一条黄金规则:

在向服务端请求信息(例如 textDocument/completion 或 textDocument/signatureHelp)之前,客户端必须确保文档状态已与服务端同步,以保证结果的可靠性。

也就是说,文档状态同步(通过 didChange)与语言特性请求(基于该状态计算)之间存在严格的先后次序。规范用一个典型的三行场景表说明了连续输入时的正确行为:

Document Version User Input Client Behavior Request
5 document change one sync document v5 to the server textDocument/didChange
5 - request from the server, based on document v5 textDocument/completion
6 document change two sync document v6 to the server textDocument/didChange

从表中可以提炼出两个实现要点:先同步、后请求;每次同步时带上本次变更后的最新版本号,服务端据此判断自己维护的快照是否为最新,从而决定语言特性的计算结果是否可信。

同步能力声明:TextDocumentSyncKind 与 TextDocumentSyncOptions

textDocument/didChange 的客户端能力与服务端能力均指向"文本同步"这一统一定义。3.17 版全量规范(specification.md)给出了完整的 TextDocumentSyncKind 枚举:

/**
 * Defines how the host (editor) should sync document changes to the language
 * server.
 */
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;

三种模式的含义如下:

  • None (0):完全不做文档同步。规范指出,客户端对该能力的支持是强制性的,除非客户端展示的文档为只读,否则服务端可能收到针对"内容由客户端管理"的文档的请求,从而产生错误结果。
  • Full (1):每次变更都发送文档的完整内容。实现简单,但对大文件或频繁输入场景开销较大。
  • Incremental (2):打开时发送一次完整内容,之后仅发送增量更新(即变更事件),是编辑器场景下最常用的模式。

服务端通过 initialize 响应中的 textDocumentSync 属性声明同步能力,其类型为 TextDocumentSyncKind | TextDocumentSyncOptions,其中 TextDocumentSyncOptions(完整定义见 specification.md)包含:

  • openClose?: boolean:是否发送 open/close 通知;
  • change?: TextDocumentSyncKind:变更通知的同步模式,缺省为 None;
  • willSave?、willSaveWaitUntil?、save?: boolean | SaveOptions:保存相关的通知配置。

客户端能力则通过 textDocument.synchronization.dynamicRegistration(布尔值)声明是否支持同步相关能力的动态注册。

注册选项:TextDocumentChangeRegistrationOptions

当服务端声明了同步能力且客户端支持动态注册时,客户端可通过 client/registerCapability 为 textDocument/didChange 注册处理器,此时需要携带如下注册选项:

/**
 * Describe options to be used when registering for text document change events.
 */
export interface TextDocumentChangeRegistrationOptions
	extends TextDocumentRegistrationOptions {
	/**
	 * How documents are synced to the server. See TextDocumentSyncKind.Full
	 * and TextDocumentSyncKind.Incremental.
	 */
	syncKind: TextDocumentSyncKind;
}

该接口继承 TextDocumentRegistrationOptions(文档过滤器,用于限定匹配哪些文档),并新增必填字段 syncKind,指定该注册项对应的同步模式。这一结构与 metaModel.json 中的机器可读描述完全一致,后者可作为自动生成 SDK 与校验实现的依据。

通知参数:DidChangeTextDocumentParams

textDocument/didChange 的方法名为 textDocument/didChange,其参数类型为 DidChangeTextDocumentParams:

interface DidChangeTextDocumentParams {
	/**
	 * The document that did change. The version number points
	 * to the version after all provided content changes have
	 * been applied.
	 */
	textDocument: VersionedTextDocumentIdentifier;

	/**
	 * The actual content changes. The content changes describe single state
	 * changes to the document. So if there are two content changes c1 (at
	 * array index 0) and c2 (at array index 1) for a document in state S then
	 * c1 moves the document from S to S' and c2 from S' to S''. So c1 is
	 * computed on the state S and c2 is computed on the state S'.
	 *
	 * To mirror the content of a document using change events use the following
	 * approach:
	 * - start with the same initial content
	 * - apply the 'textDocument/didChange' notifications in the order you
	 *   receive them.
	 * - apply the `TextDocumentContentChangeEvent`s in a single notification
	 *   in the order you receive them.
	 */
	contentChanges: TextDocumentContentChangeEvent[];
}

两个字段需要重点理解:

textDocument: VersionedTextDocumentIdentifier —— 标识发生变化的文档,其版本号指向"所有变更应用完成之后"的版本。VersionedTextDocumentIdentifier 继承自 TextDocumentIdentifier(uri 字段),并增加 version: integer(见 versionedTextDocumentIdentifier.md):每次变更(包括撤销/重做)后版本号递增,且不要求连续。由于一个通知内可能携带多个变更事件,因此版本号反映的是整批变更后的最终状态。

contentChanges: TextDocumentContentChangeEvent[] —— 实际的内容变更数组。规范特别强调:数组中的每个事件描述一次独立的状态转移。若文档处于状态 S,则 c1 使文档从 S 变为 S',c2 使文档从 S' 变为 S''——也就是说,后一个事件是相对于前一个事件应用后的状态计算的,而非相对于原始状态。要可靠地镜像文档内容,实现者必须:

  1. 以相同的初始内容开始;
  2. 按接收顺序依次应用每个 textDocument/didChange 通知;
  3. 对单个通知内的 TextDocumentContentChangeEvent 数组,同样按接收顺序依次应用。

变更事件:TextDocumentContentChangeEvent 的两种形态

TextDocumentContentChangeEvent 是一个联合类型,同一时刻只取其一:

/**
 * An event describing a change to a text document. If only a text is provided
 * it is considered to be the full content of the document.
 */
export type TextDocumentContentChangeEvent = {
	/**
	 * The range of the document that changed.
	 */
	range: Range;

	/**
	 * The optional length of the range that got replaced.
	 *
	 * @deprecated use range instead.
	 */
	rangeLength?: uinteger;

	/**
	 * The new text for the provided range.
	 */
	text: string;
} | {
	/**
	 * The new text of the whole document.
	 */
	text: string;
};

形态一:部分变更(带 range)。用于增量同步模式。事件描述文档中某个范围被新文本替换:

  • range: Range:发生变更的范围。Range 由零基的 start/end 两个 Position 组成,end 位置是排他的;若要表示包含行尾换行符的整行,应将 end 设为下一行的起始位置({ line: n+1, character: 0 }),详见 range.md。这里的 range 基于的是"应用该事件之前"的文档状态。
  • rangeLength?: uinteger:被替换范围的长度,规范明确标注 @deprecated,请改用 range。
  • text: string:替换进该范围的新文本(可为空字符串,表示删除)。

形态二:整文档变更(仅 text)。用于完整同步模式。事件只携带 text 字段,此时它被视为文档的全部新内容,服务端应以整个文档替换此前的内容。

结合 metaModel 的结构印证

本仓库的 metaModel.json 是 3.17 协议的机器可读元模型,其中与本文相关的条目可作为权威印证:

  • DidChangeTextDocumentParams(metaModel.json):textDocument 引用 VersionedTextDocumentIdentifier,contentChanges 为 TextDocumentContentChangeEvent[];
  • TextDocumentChangeRegistrationOptions(metaModel.json):继承 TextDocumentRegistrationOptions,新增 syncKind 引用 TextDocumentSyncKind;
  • TextDocumentContentChangeEvent(metaModel.json):or 类型的联合体,两个 literal 分支分别对应"range + rangeLength + text"与"纯 text"两种形态。

同时,textDocument/didChange 通知本身也在元模型的方法列表中登记(method 字段 textDocument/didChange),确认其请求方向为 client→server 的通知类型。

版本演进:3.18/3.19 对变更事件的重构

对比仓库中的后续版本可以发现,TextDocumentContentChangeEvent 在 3.18(didChange.md)与 3.19(didChange.md)中被重构为具名联合:

export type TextDocumentContentChangeEvent = TextDocumentContentChangePartial |
	TextDocumentContentChangeWholeDocument;

export type TextDocumentContentChangePartial = {
	range: Range;
	rangeLength?: uinteger; // @deprecated use range instead.
	text: string;
};

export type TextDocumentContentChangeWholeDocument = {
	text: string;
};

这一重构把两种形态拆分为具名的 TextDocumentContentChangePartial 与 TextDocumentContentChangeWholeDocument 类型,语义更加清晰,便于代码生成与静态分析,但通知的方法名、参数结构(DidChangeTextDocumentParams)以及同步模式(TextDocumentSyncKind)在三个版本间保持稳定。

实践建议小结

  1. 服务端实现:在 initialize 响应中通过 textDocumentSync.change 声明 Full(1) 或 Incremental(2);收到 didChange 时按"通知顺序 + 事件顺序"严格应用变更,并始终用 VersionedTextDocumentIdentifier.version 更新内部快照版本。
  2. 客户端实现:确保 open/change/close 通知成对且平衡;每次用户输入后、发起任何语言特性请求前,先发送带最新版本的 didChange;增量模式下,range 必须基于事件应用前的状态计算。
  3. 选择同步模式:编辑器场景优先 Incremental 以降低带宽与解析开销;对文档较小或实现从简的场景,Full 更易于调试;仅在文档只读时考虑 None。

以上所有 TypeScript 定义均可在仓库的 3.17 目录 与全量 specification.md 中找到原文,可作为实现与测试的权威参照。

登录后查看全文
language-server-protocol