GNU TeXmacsUser manualReferenceAboutEnglish
The protocol in Scheme

The protocol is implemented by three modules of

progs/lsp

, which do not depend on the editor (the tests run them on fake servers): lsp-base for the data, lsp-client for the clients, lsp-documents for the documents, the diagnostics and the buffers.

1.Messages, texts and positions

Messages

In

lsp-base.scm

, a message is the Scheme tree (stree) of the JSON converter json->typed-tree (and back with typed-tree->json, both from

json.cpp

):

The typed variant of the converter keeps numbers apart from strings, which matters since the answer to a request carries the id of the request, which may be a number or a string. lsp-read and lsp-write convert between text and stree (lsp-read gives #f if the conversion fails; the converter accepts almost anything, so lsp-client-receive also rejects what is not an object). The constructors lsp-object, lsp-array, lsp-list->array, lsp-number, lsp-boolean, lsp-null build messages, and lsp-ref reads them: (lsp-ref msg "params" "items" 0) follows keys and indices and gives #f when one is missing. lsp-items, lsp-number-value, lsp-true? and lsp-null? complete them.

Texts and positions

A text is a list of lines, in the Cork encoding of TeXmacs documents: a source file is a document with one line per paragraph, so that lsp-lines gives the lines of a body (markup inside a line is converted with texmacs->verbatim). The server gets the text of the file, in UTF-8, as it is saved: lsp-lines->text joins lines converted with cork->sourcecode (not cork->utf8, which gives the typographic forms of some characters: a backquote as an opening quote, three dots as an ellipsis), and lsp-text->lines splits a text of a server and converts it as a file is loaded (source->cork: a tab is the character <#9> of a line, one UTF-16 unit for the server; see source files); so are the texts of the edits and of the completions. A buffer, though, is given to its server from a snapshot of its lines in C++ (code-snapshot-new, code-snapshot-change,

code_regions.cpp

), which gives the text and then the part of it which changed, without a Scheme list of its lines: for a long file, such lists at each pause of the typing filled the heap (lsp-document-text, of the link, gives the whole text of lines, for the documents without a snapshot). lsp-lines->text remains for the tests and the texts which are not buffers. (lsp-line lines i) gives a line of a list or of a vector ("" if there is none): a vector when many lines of a long file are looked for.

A position of the protocol is a line and a character, counted in UTF-16 units, the default encoding of the protocol (and the only one announced in the capabilities of the client): two units for the characters beyond U+FFFF. The editor counts offsets in the Cork string of the line. lsp-offset->character and lsp-character->offset convert between them (a character in the middle of a Cork character goes to its start, one beyond the end of the line to its end; in a line whose characters are all of one byte and one unit, without the < of the special characters of Cork, lsp-character->offset gives the character itself). Both are those of the core, code-utf16-column and code-utf16-offset (

code_lines.cpp

), and lsp-position and lsp-position->line+offset convert whole positions.

URIs

lsp-path->uri turns a system path into a file:// URI, encoding with %XX every byte which is not a letter, a digit or one of -._~/:; backslashes become slashes, and a drive letter is written in capitals. lsp-uri->path decodes, and removes the slash before a drive letter (file:///c:/x on Windows), which it writes in capitals too (c: and C: are the same drive, and servers write either: both directions give the same form). It also accepts file:/x, without the authority, as the same file as file:///x, and keeps a % which is not followed by two hexadecimal digits as it is.

2.Clients

The servers
lsp-client.scm

keeps a table from languages (the prog-language, which is also the name of the format) to lists of commands, filled with lsp-server-set!. lsp-server-command gives the first command whose program (its first word) is found: in the PATH, or as a file if it contains a slash or a backslash (a Windows path). lsp-server-known? tells whether a language has commands at all, installed or not.

The life of a client

A client is a hash table with its name (the command), its state, three procedures send, listen and stop, the counter of the requests, the handlers of the pending requests, a queue, the capabilities of the server, its root directory, a log and its open documents. lsp-client-make builds one on any procedures: the tests use procedures which record what is sent, and lsp-client-start uses those of the link (lsp-send, lsp-listen, lsp-stop), with a call back which passes to lsp-client-receive.

The states are:

new

The client has been made (lsp-client-make), and nothing has been sent yet.

initializing

The request initialize has been sent (lsp-client-initialize), with the root as rootUri and as the only workspace folder, and the capabilities of the client (client-capabilities): UTF-16 positions; didSave; diagnostics with versionSupport; hovers in plain text or markdown; completion without snippets; definitions, references, documentHighlight and callHierarchy; foldingRange with lineFoldingOnly; documentSymbol with hierarchicalDocumentSymbolSupport; semanticTokens (full requests, relative format, the standard token types); inlayHint; formatting and rangeFormatting; rename (without prepareSupport); signatureHelp with labelOffsetSupport; codeAction with code action literals (quick fixes, refactorings, sources); and, for the workspace, configuration, symbol, workspace folders, applyEdit, workspaceEdit with documentChanges and executeCommand; progress (workDoneProgress). The answers to the requests of the server are sent at once (a server may ask before it answers); every other message waits in the queue, where a didChange with the whole text of a document replaces those of the same document which wait (the queue of a server which is slow to start does not grow by a copy of the file at each pause). A server which has not answered after lsp-initialize-timeout (120 s) is killed by lsp-client-check-initialized, with a line in its log.

running

The answer has come: its capabilities are kept, initialized is sent and then the queue. An error answer to initialize kills the client. (lsp-client-capable? c name) tells whether the server has a capability (a …Provider): a capability which is absent, null or given as false counts as absent.

stopping

lsp-client-stop has sent shutdown (waited for at most 2 s) and exit; the server is given 1 s more to end, then it is killed.

dead

The server has ended, has been killed (lsp-client-kill), or could not be started (its log says why). The handlers of the requests which were not answered are called with an error (code -32099). If the server ended without being stopped, the hook lsp-client-ended is called, which the editor redefines to show a message.

Requests and notifications

(lsp-request c method params handler) sends a request with a new numeric id and returns that id; the handler is called with the result and the error of the answer, one of them #f. lsp-notify sends a notification, lsp-cancel forgets the handler of a request and sends $/cancelRequest; a request which still waits in the queue (the server is initializing) is removed from it instead, and never sent. lsp-wait listens until a condition holds or a delay has passed, and lsp-request-wait sends a request and waits for its answer, which is (result r), (error e) or (timeout) (the request is then cancelled).

What the servers send

lsp-client-handle sorts the messages: a message with a method and an id is a request of the server, with a method only a notification, with an id only the answer to one of our requests. An answer with "error": null is no error, and an answer whose id is null (an error of the server about a message which it could not read) goes to the log. The requests of the servers are answered by the procedures of lsp-server-request-set! (method \(\rightarrow\) procedure of the client and the parameters, whose value is the result; an unknown method gets the error -32601, a procedure which fails -32603). The notifications go to the procedures of lsp-notification-set!, several per method, each one under a key so that it can be redefined. By default TeXmacs answers workspace/configuration (null for each item), workspace/workspaceFolders, window/workDoneProgress/create, client/registerCapability, client/unregisterCapability and window/showMessageRequest, and logs window/logMessage and window/showMessage.

lsp-actions.scm

answers workspace/applyEdit: the edit is refused (applied false, failureReason the file has changed) when lsp-workspace-edit-stale? holds, that is when the version of one of its TextDocumentEdits differs from the version of the document which the client gave (lsp-document-version), or when the buffer of that document has changed since its text was given (lsp-document-sent-text).

The log of a client keeps its last 200 entries, each with a kind (error, stderr, log, message); lsp-client-log-changed is called at each change of the log or of the state, for the log page of the editor.

The clients of the languages and projects

The clients are kept in a table under their language and root. lsp-client-for returns the client of a language and root, and starts one if there is none; lsp-client-find returns the client only if it is alive (in the state new, initializing or running, see lsp-client-alive?) and never starts one. A client is kept in the table once its server has ended (stopped, crashed, or which could not start), and lsp-client-for then gives #f: a server is not started again until its entry is forgotten (lsp-client-forget, lsp-forget-all), which is what Restart server does. Otherwise a server which ends at once would be started again at each pause of the typing. lsp-client-entry gives the entry also when its server has ended (for its log).

lsp-stop-all stops all the running servers together: it sends shutdown to each one, exit to each one which answers, and kills those which have not ended after 2 s. Their entries are kept, so they are not started again.

3.Documents, diagnostics and buffers

Documents
lsp-documents.scm

keeps, per client, the open documents by URI, each with its version, its last text (or #f), its language id and, for the lines of a buffer, the snapshot of the lines which the server has (lsp-document-open-lines, lsp-document-change-lines). lsp-document-open sends textDocument/didOpen (or changes a document which is open already); lsp-document-change sends textDocument/didChange with a higher version, only if the text has changed and if the server wants changes (its textDocumentSync is not 0). If the server takes incremental changes (kind 2) and is running, only the part which differs is sent; otherwise (kind 1, a server which does not say, or one which is still initializing) the whole new text, a change without a range. lsp-text-change finds the part: the old and the new text have a common start and a common end (in bytes of UTF-8, compared by blocks of 4 KB first, then moved back to the boundaries of characters), and what lies between them in the old text is replaced by what lies between them in the new one, its range given as positions (line, UTF-16 units, the lines counted with string-search-forwards). Each change also calls the hook (lsp-document-lines-changed uri first last added), with the lines first to last of the old text which became added+1 lines (lsp-text-lines-change): the editor moves the diagnostics which it shows.

lsp-document-save sends textDocument/didSave if the server asks for it, with the text if it asks for includeText; a textDocumentSync which is a number (a kind of change alone) gets the saves too, without the text, as other clients do. lsp-document-close sends textDocument/didClose and forgets the diagnostics of the document. A server whose openClose is false gets neither didOpen nor didClose (its documents are still kept).

Diagnostics

The notification textDocument/publishDiagnostics replaces the diagnostics kept for its URI and calls the hook lsp-diagnostics-changed, unless it has a version older than the one of the document which the client has given: those diagnostics are for an older text, and the ones of the present text come after them, so they are ignored. The URIs are kept as TeXmacs writes them (uri-key: decoded and encoded again), since a server may write the same file otherwise (%c3%a9 for %C3%A9, %3A for :). lsp-forget-diagnostics forgets those of a document (and calls the hook): of a document which is closed, and of all the documents of a client which is dead (through lsp-client-status-changed), so that they do not stay underlined, also after a restart. lsp-diagnostics, lsp-diagnostic-severity (error, warning, info, hint; error by default), lsp-diagnostic-message (in Cork) and lsp-diagnostic-range (as line, offset, line, offset in given lines) read them.

Buffers

The rest of the module links buffers to servers. lsp-buffer-language gives the language of a buffer: its format if a server is known for it (cpp, c, python…), or else, for the current buffer in the mode prog, its prog-language. lsp-buffer-path gives its file (not for tmfs buffers), and lsp-project-root its project: the nearest directory, from the directory of the file up (at most 64 levels), which contains .git, compile_commands.json, compile_flags.txt, pyproject.toml, setup.py, package.json, Cargo.toml, go.mod, build.sbt or pom.xml, else the directory of the file. The root is asked for at each key, so it is kept per directory (lsp-forget-project-roots looks for them again). lsp-language-id gives the languageId of the protocol (typescript for the .ts files of the language javascript…).

lsp-buffer-client gives the client of a buffer and starts it if needed, lsp-buffer-client* only a live one which exists already (lsp-client-find); lsp-buffer-open, lsp-buffer-sync and lsp-buffer-close open, update and close the document of a buffer, from a snapshot of its lines (in a document, of each of its code blocks), and lsp-cursor-position gives the position of the cursor in the protocol. All of them take the current buffer by default.

The requests at the cursor read one line only, not all the lines of the buffer: lsp-buffer-line gives a line of the buffer in Cork, lsp-buffer-position the position of the protocol at a line and an offset of the buffer, and lsp-buffer-line+offset the line and the offset of a position. lsp-buffer-lines (all the lines, as a list) is left for the diagnostics which are shown, which take them as a vector.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".