![]() |
Language servers in the editor | ![]() |
This page describes
lsp-edit.scm
and
lsp-kbd.scm
, and the hooks of the editor which they use.
In a build with the servers (the glue routine lsp-start is defined),
init-texmacs.scm
declares (lazy-keyboard (lsp lsp-kbd) in-prog?) and (lazy-menu (lsp lsp-kbd) lsp-menu), and, when the preference lsp is not off, loads (lsp lsp-kbd) after an idle second, so that the source files are followed without a key or the menu being used first. lsp-kbd uses lsp-edit, which uses the other modules. The menu is linked as Tools\(\rightarrow\)Language servers in
tools-menu.scm
. When lsp-edit is loaded, a delayed command follows the buffers which were loaded before it.
The preference lsp (default on, read by lsp-on?) is toggled by Follow source files; setting it to off calls lsp-turn-off, which stops and forgets all the servers and removes the underlines in each buffer which has some; setting it to on again follows all the open buffers (follow-all).
Two hooks were added to the editor for the programs which follow the text of buffers; their default definitions, which do nothing, are in
cursor.scm
, next to notify-cursor-moved:
Called by edit_interface_rep::apply_changes (
edit_interface.cpp
) when env_change contains THE_TREE, with the name of the buffer of the editor as a string, after the typesetting. It is thus called once per batch of changes, not once per modification.
Called by remove_buffer in
new_buffer.cpp
before the views of the buffer are deleted, and by rename_buffer with the former name (File\(\rightarrow\)Save as).
lsp-edit redefines both (with former), as well as version-notify-saved (called after a buffer is saved, in
tm-files.scm
; the redefinition of
version-git.scm
passes it on) and notify-cursor-moved.
A table followed remembers, by buffer name, whether a server follows the buffer: the first time, follow? checks that the buffer has a file, a language (lsp-buffer-language) and an installed server (lsp-server-command). notify-buffer-changed calls lsp-follow-buffer, which puts a followed buffer in the table pending and schedules lsp-sync-pending once, with (delayed (:idle 300) …): the texts are given to the servers (lsp-buffer-sync, which opens the document the first time, and starts the server if needed) only when the user pauses. Since the loading of a buffer is a change of its tree, the same path opens the document of a file which has just been loaded.
version-notify-saved gives the text at once and then sends didSave (in a document, it looks for all its code blocks again, lsp-blocks-rescan); notify-buffer-closed sends didClose for a followed buffer and forgets it (a renamed buffer is followed under its new name at its next change). lsp-buffer-followed? tells whether the current buffer is followed (the table followed, without mode predicates).
In a document which is not a source file, with the preference lsp:code blocks on, the code blocks are followed (
lsp-blocks.scm
): the document is in followed, and lsp-buffer-sync of it gives the blocks to their servers as virtual files: each block one file, or, with lsp:join code blocks (the default), the blocks of a language one file, a unit, whose lines are a document of their own (lsp-unit-lines), made again from those of its blocks (lsp-unit-set-roots!) when it is given to the server or used at the cursor. The functions of the buffer without a buffer argument are those of the target, the code at the cursor: a source file, a block, or a unit (in
lsp-documents.scm
): lsp-target-root gives its lines, lsp-target-path the place in the document of an offset of one of them, lsp-target-lo the line and offset of a place (a line of a unit is a line of one of its blocks), lsp-target-key its file. The requests at the cursor go to the server of the target, and their answers come back to the places of the document; an edit of the virtual file of a unit is written back to its blocks (lsp-unit-write-back!), when it changes the number of the lines of one block only. A buffer is followed at the cursor (lsp-buffer-followed?) when it is a source file or the cursor is in one of its blocks.
lsp-diagnostics-changed marks the URI as stale, and shows the diagnostics at once if it is the one of the current buffer; otherwise they are shown when the cursor next moves in that buffer. lsp-show-diagnostics converts each diagnostic to the lines of the buffer as they are now (a vector of them; diagnostics beyond the last line are left out, an empty range is widened to one character, hints count as information), keeps them in the table shown, and sets (draw-diagnostics) three alternative selections of the editor, as the diagnostics of the source 'server of the core (code-set-diagnostics,
code-diagnostics.scm
, with the syntax errors of tree-sitter where no server follows the code): code-errors, code-warnings and code-infos, each a list of paths, start and end of each range, sorted in the order of the text (the editor looks for the visible ones by a binary search). lsp-hide-diagnostics cancels them.
Until the server publishes new ones, the diagnostics shown follow the lines: the redefined hook lsp-document-lines-changed (called at each didChange) moves those after the changed lines, drops those in them (an edit removes their underlines) and draws them again; F8 and the messages at the cursor use these positions.
edit_interface_rep::update_diagnostic_rects (
edit_interface.cpp
) reads the three alternative selections and computes the rectangles of their ranges (compute_selection), in the colors #e02020, #e09000 and #2080e0, into diagnostic_rects and diagnostic_colors (
edit_interface.hpp
). The ranges were computed by a program for an older text, so a range whose paths are no longer valid cursor positions of the document, or whose end is before its start, is dropped first (valid_cursor_path). Then, as for the spell errors, only about 100 ranges around the visible part are computed when there are many (find_alt_selection_index, a binary search which assumes the ranges in the order of the text and valid). apply_changes calls it when the tree, the environment, the extents, the selections or the spell errors have changed, or when the visible part has moved, but not when only the cursor moves.
edit_repaint.cpp
draws a line of 2 pixels at the bottom of each rectangle.
notify-cursor-moved calls lsp-cursor-moved in a followed buffer: it shows the stale diagnostics, and on the status bar the first line of the message of the diagnostic at the cursor (errors first), as Error: …, Warning: … or Note: …; the message is cleared when the cursor leaves it. lsp-next-diagnostic (the menu of the servers) goes to the start of the next (or previous) diagnostic of shown, and wraps around; F8 is code-next-diagnostic of the core, which goes through the diagnostics of all the sources of the buffer. In a document, the diagnostics of all its blocks are drawn, each at the place of its block (draw-diagnostics), again after each change of the document (a paragraph inserted above a block moves it).
The commands use the running client of the buffer (lsp-buffer-client*: synchronizing first would start a server), check that the server has the capability (definitionProvider, hoverProvider, completionProvider), give it the current text (lsp-buffer-sync) and send the request at lsp-cursor-position. The position is only defined when the cursor is in the text of a line, that is when the cursor path is the path of the buffer followed by a line and an offset; it is computed from that line only (lsp-buffer-position), and so is the word before the cursor.
kbd-variant (the action of ⇥) is redefined with (:require (and forwards? (lsp-completion-here?))): lsp-completion-here? holds in a followed buffer whose server completes, after a character of a word or after ., > or :. lsp-complete sends textDocument/completion asynchronously: at most one request is awaited (a new one cancels the former), and its handler applies the answer only if the buffer and the cursor path have not changed. The items are sorted by sortText, their texts (insertText, textEdit.newText or label) are kept if they extend the word before the cursor (at most 100), and the suffixes are given to custom-complete as (tuple prefix suffix …), which inserts the first and cycles through the others (
edit_complete.cpp
). After ., -> or :: the word is empty, and the prefix given to custom-complete is the character before the cursor (lsp-completion-tuple), since it must not be empty. Without completions, the completion of the editor (complete-try?) is tried.
lsp-hover waits (at most 5 s) for the answer to textDocument/hover, extracts its text (MarkupContent, MarkedString or an array of them), converts it from markdown (lsp-hover-document, with the converter markdown-snippet; the useful lines as verbatim if this gives nothing) and shows it with show-tooltip (
tooltip.scm
) in a preview-balloon, at the tree of the cursor, of type keyboard, as the previews of references. Without a window (headless?), the first lines go to the status bar instead.
The redefined mouse-event (without mode predicates, as notify-cursor-moved, see the pitfalls) notes each move in a followed buffer (unless the preference lsp:mouse hover is off); once the mouse has rested 600 ms (a delayed check which waits again while it moves), the point under it is turned into a cursor position by xy->path, a function of the editor (edit_interface_rep::xy_to_path in
edit_mouse.cpp
, as a click finds its position; none before the document is typeset). If it is on a word, the hover is asked without waiting, and shown at the line, in a balloon of type mouse (closed when the mouse leaves it), if the mouse is still on the same word when the answer comes.
The redefined keyboard-press (without mode predicates either) asks for textDocument/signatureHelp after a trigger character of the server (( and , by default), without waiting; a new request cancels the one which is awaited, and an answer is shown only if the cursor is still in the same buffer and on the same line (an answer may come late). lsp-signature-markup makes the label of the active signature, with the active parameter (a substring, or offsets) between guillemets, for the status bar, which a ) clears (the status bar shows text, not markup: a bold parameter looked as the others). The parts of the label (lsp-signature-parts: before the parameter, the parameter, after it) are kept for the focus bar, which shows the parameter in bold.
lsp-kbd.scm
adds lsp-focus-icons to focus-code-icons (of
prog-menu.scm
): lsp-focus-status gives the name of the server of the current buffer, its state (starting, ready, stopped, or none before it is started), its work and the numbers of errors and warnings shown. The focus bar is made again at each key, so the language and the project of a buffer are kept, and the command of a server once it is found in the PATH. The client calls lsp-client-status-changed when its state changes and when a $/progress notification comes (lsp-client-progress gives the text of the work, while it lasts); the editor then asks for an update of the menus, once for many changes (lsp-status-refresh), as for new diagnostics and signatures.
lsp-goto-definition takes the first Location or LocationLink of the answer and calls lsp-goto-location, which switches to the buffer of the file (or loads it) and moves the cursor to the start of the range.
lsp-navigate.scm
makes two pages, as the one of the diagnostics. lsp-references (⌘⇧U) asks for textDocument/references at the cursor, with includeDeclaration (lsp-request-at-cursor-with adds the context to the parameters of the cursor), groups the Locations by file (in the order of their first reference, then by position) and shows each one with its line: that of the buffer of the file if it is open, else of the file on disk. At most 2000 references are shown.
The outline (⌘⇧O, code-outline of the core, which lsp-outline calls) asks the provider lsp-outline-at-cursor, which asks for textDocument/documentSymbol; lsp-outline-entries turns the answer into lines (depth, kind, name, detail, position): nested DocumentSymbols in their order, or flat SymbolInformations sorted by position. The page is made again by the core (
code-navigate.scm
) after a pause in the changes of its buffer, as long as it is open.
lsp-find-symbol (⌘⇧P) asks for workspace/symbol with the name which it is given and lists at most 500 SymbolInformations or WorkspaceSymbols (a location without a range goes to the start of its file). lsp-call-hierarchy (⌘⇧H) asks for textDocument/prepareCallHierarchy at the cursor, then for the callHierarchy/incomingCalls and outgoingCalls of the first item: a caller goes to its first call (fromRanges), a callee to its definition (selectionRange).
When the cursor rests (notify-cursor-moved, then delayed with :idle 300), lsp-highlight-at-cursor sends the changes which wait (lsp-sync-pending), asks for textDocument/documentHighlight (the previous request is cancelled) and, if the cursor has not moved and the buffer has not changed (a count of the changes: an edit may leave the cursor in place), sets the alternative selection lsp-highlights, which
edit_interface.cpp
draws as the matches of a search (with alternate and brackets). The highlights are cleared when the cursor leaves them; an edit removes all the alternative selections, and notify-buffer-changed forgets them.
The folds are those of the core (the features of program code,
code-fold.scm
): a state of the hidden lines, which tree-sitter folds too.
lsp-fold.scm
is the provider of their blocks when a server follows the file: the textDocument/foldingRange of the server (lines only, lsp-folding-ranges-of; those around the cursor, lsp-fold-ranges, and all of them, lsp-all-fold-ranges, a block given twice with the same first line reduced to the larger one). It keeps the names of its former commands (lsp-fold, lsp-unfold, lsp-folds, lsp-line-folded?), which call the core.
lsp-decorate.scm
asks the server of the current buffer for textDocument/semanticTokens/full and textDocument/inlayHint (the whole file), 200 ms after the server has published diagnostics for it (it has seen the text then), if the buffer has at most 20000 lines and the preferences lsp:semantic colors and lsp:inlay hints are on. The changes which wait are sent first (lsp-sync-pending), so that the server answers for the text of the buffer, and the inlay hints are asked for up to the end of the last line (not beyond it, which a server may refuse). The answers are used only if the buffer still has the text they were asked for, and only if it is the buffer which is shown (the lines which change are typeset again). lsp-decode-tokens decodes the tokens (relative lines and starts, the types of the legend of the server); lsp-token-color gives colours to functions, methods, types, macros and enum members only (those of the preferences of the syntax for types, macros and numbers), the rest keeps the colours of the language of TeXmacs; lsp-line-decorations gives, line by line, the coloured pieces and the hints in Cork offsets.
lsp-apply-decorations gives them to the typesetter as the layers of the lines of the core (code-set-line-layers, see the features of program code), for the lines whose decorations change, and typesets those lines again (update-path; the whole buffer beyond 2000 lines). Its table decorated keeps, for each decorated line of a buffer, the tree of the line, its text then and its decorations. A line which has moved (lines were inserted or removed above it: its place now is that of its tree) and keeps its tree, its text and its decorations is not given again nor typeset again; a line which was edited (the same tree, another text) is given again. The lines which have no decorations any more, and those which were removed from the document, lose theirs. The layers are kept on the highlight observers of the lines (
code_lines.cpp
), which an edit of a line detaches: an edited line is typeset as usual until the next answer. concater_rep::typeset_prog_string (
concat_text.cpp
) calls typeset_layered_string for a line with layers: the pieces of a token with colours of their own are typeset apart, and the hints come before the tokens where they are, as grey text boxes with decorated paths (the cursor does not go into them), their spaces and paddings as empty boxes of the width of a space (printed spaces would be merged). The lines of a closed buffer, and all of them when the servers are turned off, lose their decorations.
lsp-client-ended is redefined to say on the status bar that the server has ended. lsp-restart stops the client of the buffer if it runs, forgets its entry, empties followed and the caches of the servers of the buffers, of their commands and of the projects (a project may have been made since, a server added), and synchronizes the buffer, which starts a new server; all the open buffers are then followed again (follow-all), so that the other files of the project reach the new server too. lsp-stop-servers calls lsp-stop-all; since the entries are kept, the servers stay stopped.
lsp-show-log opens the auxiliary buffer Language server (open-auxiliary) with the log of the client of the buffer (also of a server which has ended). The page follows the log: the redefined lsp-client-log-changed schedules lsp-log-refresh after a pause of 300 ms, which replaces the body of the page as long as it exists.
lsp-show-diagnostics-list opens the auxiliary buffer Diagnostics with a line per diagnostic of the file, an action which calls lsp-goto-position (a secure function); the redefined lsp-diagnostics-changed refreshes it after 300 ms, as the log. At most 1000 diagnostics are underlined.
lsp-actions.scm
applies the edits which the servers send: TextEdits (a range and its new text) for the formatting, WorkspaceEdits (the TextEdits of one or more files, as changes or documentChanges) for a rename and the quick fixes. lsp-apply-to-lines applies them to the Cork lines of a buffer in one pass (linear in the size of the file, also for the thousands of edits of a formatter): the edits are sorted by their start, edits with the same start in the order of the server (by their index: the sort of S7 is not stable), and the text between them is copied from a vector of the lines; a position beyond the text is clamped to its end, and an edit which overlaps the previous one (which a server should not send) starts where that one ended. lsp-set-lines then changes the document only where its lines differ (the common lines at its start and at its end are kept, the others compared in vectors), which keeps the markup of the other lines and the undo history short. A line which differs is replaced, so the cursor would leave it: its new place is computed by lsp-move-through-edits (the same before an edit, shifted after it, also on its line when the new text is longer, inside it the same while the new text is still there), and the cursor goes there. A file which is not open is loaded in a buffer.
lsp-format asks for textDocument/formatting (or rangeFormatting for the selection), lsp-rename (an interactive command) for textDocument/rename, after giving the servers the texts of all the buffers which have changed (lsp-sync-pending: the edits are made for the texts which the server has), and lsp-quick-fix for textDocument/codeAction at the cursor, with the diagnostics of its line: a single action is run at once, several are listed on the page Quick fixes, as actions which call lsp-run-fix. The page keeps the buffer and its text (fixes-buffer, fixes-text), since the ranges of the fixes are those of that text: a fix is applied only to its buffer, and refused with a message if that buffer has been closed or its text has changed since. An action may have an edit and a command (workspace/executeCommand), after which the server may ask for an edit itself (workspace/applyEdit, applied by lsp-apply-workspace-edit, which returns the number of files changed; the answer is applied false, with a failureReason, when a file could not be opened). Such an edit comes later than the answer to a request, and the buffer may have changed meanwhile: it is refused (applied false, with a message) when lsp-workspace-edit-stale? holds, that is when a TextDocumentEdit is for another version of its document than the one which the client gave, or when the buffer of that document has changed since its text was given to the server. Such an edit may also come while the editor waits for the answer to a format or a rename (lsp-request-wait dispatches the messages of the servers): the edits of the servers are counted (server-edits), and an answer which came after one is not applied (“the file has changed meanwhile”). The client declares these abilities in initialize (code action literals, label offsets of the parameters, applyEdit, document changes), else clangd proposes commands instead of edits.
lsp-kbd.scm
defines the mode in-lsp%, (lsp-followed?) within in-prog%: a buffer which a server follows, while the preference lsp is on (lsp-followed? uses lsp-buffer-followed?). Elsewhere ⇧F12 keeps its meaning (the slides). It binds, in the mode in-lsp?, the keys which only a server serves: ⇧F12 to lsp-hover, ⌘⇧F to lsp-format, ⌘⇧E to the rename, ⌘. to lsp-quick-fix, ⌘⇧M to lsp-show-diagnostics-list (F2, the key of renames in other editors, is taken), ⌘⇧U to lsp-references, ⌘⇧P to lsp-find-symbol (interactive) and ⌘⇧H to lsp-call-hierarchy, and defines lsp-menu. The keys of the features which tree-sitter gives too are those of all program code, in
prog-kbd.scm
: F12 (code-go-to-definition), ⌘⇧O (code-outline), F8 and ⇧F8 (code-next-diagnostic), ⌘( and ⌘) (the folds of the core); they ask the server first where one follows the code (the features of program code).
In a source file (footer-in-source? in
footer-menu.scm
: in-prog? and the initial mode is prog), the status bar shows the language only, without the fonts and colors of the document; code in a document keeps them. The font of source files is the preference editor:code font (Inconsolata by default, offered in
preferences-widgets.scm
): attach_subformat (
new_buffer.cpp
) sets it as prog-font in the initial environment of a source file which is opened, and notify-code-font (
tm-server.scm
) gives a new value to the open source files, which stay unmodified.
The files .c and .h have the format c, C source code, declared in
code-format.scm
with its converters, and the language c, whose keywords (C11 and C23), operators and numbers are in
c-lang.scm
. These files are in the plug-in code of the source tree,
src/plugins/code
: TeXmacs/plugins/code is the copy made by the build, which must not be edited. The server of the language c is clangd, as for cpp.