Documentation
¶
Overview ¶
Package langserver is what the language packs share to find, start and show a language server (SPEC §10.34 "What every pack gets", D47): the finder (the path setting of the pack, the folders it names before and after PATH, a version check), the root of the project (the nearest folder with a marker such as Cargo.toml), the options the server starts with and the answers to workspace/configuration built from the settings and rebuilt when they change, the status bar item with its menu, the notification for a missing server (How to Install, Copy Install Command, Set Path...), and the settings of the pack that name its programs. extensions/golang keeps its own code (SPEC §10.17); the other packs describe their server with a Config and the pack's extension calls Attach.
The host runs the server (SPEC §9.12): the pack declares it in its manifest with Config.Spec, which has OwnUI, so that the host leaves the status item and the "not found" notification to this package, and gives the host a ServerLauncher with Attach, which finds the program at each start instead of the fixed Program and PathSetting of the spec. The launcher runs on a goroutine of the host; everything else in this package runs on the UI thread, as the extension API asks.
A pack uses it through langpack.Spec.Server:
langpack.New(langpack.Spec{ID: "emetos.rust", ..., Server: &langserver.Config{
ID: "rust-analyzer", Name: "rust-analyzer", Languages: []string{"rust"}, Category: "Rust",
Programs: []langserver.Program{{Name: "rust-analyzer", PathSetting: "rust-analyzer.server.path", After: []string{"~/.cargo/bin"}}},
RootMarkers: []string{"Cargo.toml"},
}})
Index ¶
- Constants
- Variables
- func CheckPath(env Env, text string) string
- func CheckProgram(ctx context.Context, p ProgramCheck) extension.RequirementResult
- func CompareVersions(a, b string) int
- func DefaultVersion(output string) (string, bool)
- func Family(osRelease string) string
- func FindExecutable(name string, dirs []string) (string, bool)
- func FindProjects(folder string, markers []string, opts ProjectOptions) []string
- func Fingerprint(v any, ok bool) string
- func FromProtocol(text string, p Position, encoding string) extension.Position
- func HasMarker(dir string, markers []string) bool
- func IsExecutable(path string) bool
- func ProvideContent(api extension.API, what string, p extension.ContentProvider) extension.ContentRegistration
- func QueryVersion(ctx context.Context, program string, vc VersionCheck, dir string, env []string) (string, error)
- func RangeFromProtocol(text string, r Range, encoding string) extension.Range
- func ReadOSRelease() string
- func ResolveRoot(folder string, markers []string, home string) string
- func SetNested(m map[string]any, path []string, v any)
- func StatusID(serverID string) string
- func UTF16Column(text string, p extension.Position) int
- type Config
- type Controller
- type Env
- type Found
- type Health
- type Install
- type InstallCommand
- type Launch
- type MenuEntry
- type Option
- type Position
- type Program
- type ProgramCheck
- type ProjectOptions
- type Range
- type Settings
- func (s *Settings) Bool(key string) bool
- func (s *Settings) Float(key string) float64
- func (s *Settings) Keys() []string
- func (s *Settings) Object(key string) map[string]any
- func (s *Settings) Read() map[string]string
- func (s *Settings) String(key string) string
- func (s *Settings) Strings(key string) []string
- func (s *Settings) Value(key string) (any, bool)
- type VersionCheck
Constants ¶
const ( HealthOK = "ok" HealthWarning = "warning" HealthError = "error" )
The levels of a Health, as rust-analyzer's experimental/serverStatus names them.
const ( // FromSetting: the path setting of the pack. FromBefore and FromAfter: a folder searched before and after PATH. FromPath: PATH. FromSetting = "setting" FromBefore = "before" FromPath = "PATH" FromAfter = "after" )
Where a program was found.
const ( FamilyAny = extension.FamilyAny FamilyFedora = extension.FamilyFedora FamilyDebian = extension.FamilyDebian FamilyArch = extension.FamilyArch FamilySuse = extension.FamilySuse FamilyMacOS = extension.FamilyMacOS )
The families of systems an InstallCommand is for.
const ( EncodingUTF8 = "utf-8" EncodingUTF16 = "utf-16" EncodingUTF32 = "utf-32" )
The names of the encodings, as the protocol spells them.
const InstructionsURL = "https://github.com/rm4n0s/emetos#languages"
InstructionsURL is the address of the section of the README that lists the language servers and how to install them; the dialog How to Install opens it (step 24b.10).
Variables ¶
var SkipFolders = []string{".git", ".hg", ".svn", "node_modules", "target", "bin", "obj", "build", "dist", "out", ".venv", "venv", "__pycache__", ".gradle", ".idea", ".vscode"}
SkipFolders are the folders FindProjects does not enter: they hold dependencies and build output, not projects.
Functions ¶
func CheckPath ¶
CheckPath tells why the text is not the path of a program a user may set, or "" when it is. An empty text is valid (it clears the setting).
func CheckProgram ¶
func CheckProgram(ctx context.Context, p ProgramCheck) extension.RequirementResult
CheckProgram is the check of a program requirement (SPEC §10.36): found with its path and version, missing, or unusable when it is older than the minimum. A version that cannot be read is not a failure, as for a server (Resolve); it is said in the detail.
func CompareVersions ¶
CompareVersions compares two versions by their numbers ("1.10" is newer than "1.9"): -1, 0 or 1. A part after the numbers ("-nightly") is ignored, a missing number is 0 ("1.2" equals "1.2.0").
func DefaultVersion ¶
DefaultVersion finds the first dotted number in the output: "rust-analyzer 1.78.0 (9b00956e5 2024-04-29)" gives "1.78.0".
func Family ¶
Family tells the family of the system from the text of /etc/os-release: its ID and ID_LIKE, "" when it is none of ours.
func FindExecutable ¶
FindExecutable looks for the file name in the folders, in order, and returns the first executable one.
func FindProjects ¶
func FindProjects(folder string, markers []string, opts ProjectOptions) []string
FindProjects lists the project roots at or below the folder: the folders that hold a marker, with the folder first when it is one, then the others by depth and name. A project's own subfolders are still looked at (a solution holds projects). It is how a pack lists the solutions or the workspaces to choose from.
func Fingerprint ¶
Fingerprint is a text that is equal for equal values of a setting: its JSON, or "absent" for a setting nobody registered.
func FromProtocol ¶
FromProtocol converts a position of the protocol in the text to the API's. A column past the end of the line is the end of the line.
func HasMarker ¶
HasMarker tells whether the folder holds a file or folder that matches one of the markers (names, globs allowed).
func IsExecutable ¶
IsExecutable tells whether the path is a file (a link to one counts) that someone may run.
func ProvideContent ¶
func ProvideContent(api extension.API, what string, p extension.ContentProvider) extension.ContentRegistration
ProvideContent registers the provider of the read-only documents of a pack (the class files of jdtls) and returns its registration. A scope that cannot show documents (a view of a client, a tab of an extension) is no failure of the pack and says nothing that is worth a warning, because the log is read by people who have no tab to show it in: the answer is nil, and it is logged at debug level. what names the documents in that line ("the class files of jdtls"). Any other failure is logged as a warning and also answers nil, so that a pack goes on without its read-only tabs.
func QueryVersion ¶
func QueryVersion(ctx context.Context, program string, vc VersionCheck, dir string, env []string) (string, error)
QueryVersion runs the program with the arguments of the check, in the folder and with the environment given (nil is Emetos's), in a process group of its own that is killed when ctx ends or after versionTimeout, and returns the version it printed. A program that could not be run fails with ServerVersionFailed; one that printed no version, with ServerVersionUnreadable.
func RangeFromProtocol ¶
RangeFromProtocol converts a range of the protocol to the API's.
func ReadOSRelease ¶
func ReadOSRelease() string
ReadOSRelease reads the file that names the system, "" when there is none.
func ResolveRoot ¶
ResolveRoot is the folder a server works on for the folder of a tab: the folder itself when it holds a marker, else the nearest folder above it that does. The climb stops after the folder that holds a .git (a repository is a boundary), before the home folder of the user and the root of the file system (a Cargo.toml or package.json there is not a project), and after twelve folders. Without markers, or when none is found, it is the folder.
func SetNested ¶
SetNested puts v at the path of keys in the nested maps of m, making the maps on the way: ["cargo", "features"] sets m["cargo"]["features"]. A path that would replace a value, or go through one that is not a map, is left out (a setting whose name is the start of another's cannot be both).
Types ¶
type Config ¶
type Config struct {
// ID is the id of the server in the manifest of the pack (rust-analyzer); Name the name shown to the user (the status item,
// the Output channel, the notifications).
ID, Name string
// Languages are the ids of the languages the server serves; the status item shows while an editor of one of them is in front.
Languages []string
// Category is the category of the commands of the pack in the command palette ("Rust"); the name of the pack when empty.
Category string
// Purpose says in a few words what the server gives (the language features of Rust), for the dialog How to Install.
Purpose string
// Programs are the programs that can be the server, the first by default: the pack with one server has one, the Python pack
// has basedpyright, pyright and pylsp. Select chooses among them. At least one is needed.
Programs []Program
// Select returns the index in Programs of the program to run now, from the settings (python.languageServer); the first when
// nil or when the index is out of range. The settings it reads are watched: a change restarts the server.
Select func(s *Settings) int
// Disabled returns the reason when the user turned the server off (python.languageServer is "none"), "" when it should run. A
// disabled server is not looked for: the start fails with ServerDisabled, the item shows "disabled" and nobody is told, because
// it is what the user asked. The settings it reads are watched like those of Select.
Disabled func(s *Settings) string
// RootMarkers are the names (globs allowed: *.sln) of the files that mark a project root: Cargo.toml, pom.xml. The server is
// started in the folder if it holds one, else in the nearest folder above it that does, as far as the repository or the
// user's home folder goes (ResolveRoot). Without markers it is started in the folder.
RootMarkers []string
// Customize is called at each start after the program was found and passed its version check; it sets the arguments, the
// environment, the initialization options and the answers to workspace/configuration of the launch from the settings it reads.
// The settings it reads are watched: a change restarts the server. An error leaves the server missing, with the error in
// the Output channel.
Customize func(l *Launch, env Env) error
// CustomizeContext is Customize for a pack that runs a program to decide (jdtls asks java for its version): it gets the context of
// the start, which ends with the tab and with a restart. Only one of the two is used, this one first.
CustomizeContext func(ctx context.Context, l *Launch, env Env) error
// TraceKey is the setting that traces the traffic with the server (rust-analyzer.trace.server): "<pack id>.<id>.trace.server"
// when empty (extension.LanguageServerSpec.TraceKey).
TraceKey string
// ConfigurationSection and WatchedFiles are those of extension.LanguageServerSpec.
ConfigurationSection string
WatchedFiles []string
// SettingsQuery is what Open Settings of the menu searches for (rust-analyzer); the name of the server when empty.
SettingsQuery string
// Menu are the entries the pack adds to the menu of the status item, after Restart, Show Output and Open Settings.
Menu []MenuEntry
}
Config describes the language server of a pack.
func (Config) Requirements ¶
func (c Config) Requirements() []extension.Requirement
Requirements are what the server needs from the system, for the manifest of the pack (SPEC §10.36): one requirement, the server, whose check is the search the launcher makes at each start (Resolve: the path setting, the folders before and after PATH, the version check), without Customize, which belongs to an activation. With Select the requirement follows the settings, as the launcher does, and names the program they chose; its Install and PathSetting are those of the first program, and a result for another program gives that program's. A Config that Attach would refuse gives none.
func (Config) SettingSpecs ¶
func (c Config) SettingSpecs() []extension.SettingSpec
SettingSpecs are the settings of the pack that name the programs: one string setting for each PathSetting, in the user's settings only (a folder's settings must not decide which program runs).
func (Config) Spec ¶
func (c Config) Spec() extension.LanguageServerSpec
Spec is the declaration of the server for the manifest of the pack: the host does not look for the program (Attach gives it a launcher), and leaves the status item and the notification for a missing program to this package.
func (Config) Subscribes ¶
Subscribes are the event topics the pack declares in its manifest for the status item.
type Controller ¶
type Controller struct {
// contains filtered or unexported fields
}
Controller is the part of a pack that follows its language server in one tab: it gives the host the launcher, shows the status item and its menu, tells the user when the server is missing, and restarts the server when a setting its start read changes. Everything but the launcher runs on the UI thread.
func Attach ¶
func Attach(ctx context.Context, api extension.API, cfg Config, opts ...Option) (*Controller, error)
Attach connects the server the pack declared (Config.Spec) to the tab: the launcher, the status item, the notification for a missing server, and the restart on a change of the settings. The manifest of the pack must declare the topics of Config.Subscribes and the server and settings of Config.Spec and Config.SettingSpecs; langpack does it for a Spec with a Server. It fails with ServerConfigInvalid for a Config without an id, a name, languages or a program.
func (*Controller) Found ¶
func (c *Controller) Found() Found
Found is where the server was found at the last start; the zero value before the first start or when it was not found.
func (*Controller) Refresh ¶
func (c *Controller) Refresh()
Refresh draws the status item again; a pack calls it when what its label shows changed.
func (*Controller) SetDetail ¶
func (c *Controller) SetDetail(text string)
SetDetail sets a line the tooltip of the status item shows after the state of the server ("Interpreter: /usr/bin/python3").
func (*Controller) SetHealth ¶
func (c *Controller) SetHealth(h Health)
SetHealth sets how the server is doing; a restart of the server forgets it.
func (*Controller) SetLabel ¶
func (c *Controller) SetLabel(text string)
SetLabel sets the text of the status item (the Python pack shows the interpreter); the name of the server when empty.
func (*Controller) State ¶
func (c *Controller) State() extension.ServerStatus
State is the last state of the server the host told.
func (*Controller) Version ¶
func (c *Controller) Version() string
Version is the version of the server that runs or started last, "" when it is not known.
type Env ¶
type Env struct {
// Folder is the folder of the tab, Home the home folder of the user and Path the value of PATH.
Folder, Home, Path string
// Environ reads a variable of Emetos's environment for ${env:NAME}; os.Getenv when nil.
Environ func(name string) string
// Settings reads the settings of the tab.
Settings *Settings
// State, when not nil, reads a value the extension keeps for the folder; the check of a requirement (SPEC §10.36) gives it, so that
// a hook of a Program that reads what the user chose (the Python interpreter) can do so without an activation. A running activation
// leaves it nil and reads its own state.
State func(key string) (json.RawMessage, bool)
}
Env is what the search for a program and the hooks of a Config know of the machine and the tab. Tests make their own.
func DefaultEnv ¶
DefaultEnv is the Env of this machine for a tab: the folder, the home folder, PATH, and the settings.
func (Env) Abs ¶
Abs makes the absolute path of a template (Expand, and joined to the folder of the tab when it is relative), cleaned.
type Found ¶
type Found struct {
// Path is the absolute path, Source where it was found (FromSetting, FromBefore, FromPath, FromAfter) and Dir the folder it was
// found in, for the places searched.
Path, Source string
}
Found is a program that was found.
func Find ¶
Find looks for the program: the setting of its path, then the folders of Dirs and Before, PATH, and the folders of After and Dirs (Program.Find replaces all this). A setting that is set is the only place looked at: a wrong one fails with ServerPathInvalid, so that the user is told, instead of running another program than the one named. A program that is nowhere fails with ServerNotFound, which lists the places looked at.
type Health ¶
type Health struct {
// Level is HealthOK (or empty), HealthWarning or HealthError; the item shows the icon of the level while the server runs and has no
// progress to show.
Level string
// Busy says that the server is working (it is not quiescent); the item spins.
Busy bool
// Message is a line of the tooltip ("Failed to load workspace").
Message string
}
Health is how a running server says it is doing, beyond its process being up (rust-analyzer's experimental/serverStatus): whether it is busy, and whether something is wrong with what it was asked to load.
type Install ¶
Install says how to get a program (SPEC §10.34: Emetos never installs a server, D47; it tells the user how). It is the extension contract's, which the requirements of SPEC §10.36 share.
type InstallCommand ¶
type InstallCommand = extension.InstallCommand
InstallCommand is a command that installs a program.
type Launch ¶
type Launch struct {
// Found is the program that was found, Version its version ("" when it could not be read) and Program the entry of
// Config.Programs it is.
Found Found
Version string
Program Program
// VersionErr says why the version could not be read; nil when it was or when the program has no way to tell.
VersionErr error
// Root is the folder the server works on (ResolveRoot of the folder of the tab).
Root string
// Command, when it is not empty, is the program that is run instead of Found.Path, which then stays what the status item shows as the
// server (typescript-language-server is a script that node runs: Command is node and Args start with the script).
Command string
// Args and Env are the arguments and the extra environment variables of the program; Args start as Program.Args.
Args, Env []string
// InitializationOptions are sent in initialize (nil for none).
InitializationOptions any
// Configuration are the answers to workspace/configuration, by section ("python": {...}); a section below one of them
// ("python.analysis") is answered from inside it. A section that is not in it is answered from the settings of the tab.
Configuration map[string]any
// Settings are sent to the server with workspace/didChangeConfiguration right after it initialized, before any document opens (nil
// sends nothing); typescript-language-server takes its per-language settings (format, inlay hints) only this way.
Settings any
// ClientExperimental is the "experimental" member of the client capabilities the server is initialized with (nil for none).
ClientExperimental map[string]any
}
Launch is a start of the server in the making: what Customize changes.
func Resolve ¶
Resolve decides what to run for the server now: it chooses the program (Config.Select), finds it (Find), checks its version (Program.Version), takes the root of the project (ResolveRoot) and lets Config.Customize set the rest from the settings. It runs programs, so it belongs on a goroutine, not on the UI thread; ctx ends the version check. Failures are ServerNotFound, ServerPathInvalid, ServerTooOld, ServerDisabled, ServerLaunchCancelled and ServerCustomizeFailed (an error of Customize that is not one of ours). A version that cannot be read is not a failure: Launch.Version is empty and Launch.VersionErr says why.
type MenuEntry ¶
type MenuEntry struct {
// Label is the text, a codicon may be written $(name); Description is shown after it.
Label, Description string
// Run is called, on the UI thread, when the entry is chosen.
Run func()
}
MenuEntry is an entry of the menu of the status item.
type Option ¶
type Option func(*Controller)
Option changes how Attach makes a Controller; the tests use them.
func WithOSRelease ¶
WithOSRelease makes the controller read the family of the system from the text instead of from /etc/os-release.
type Position ¶
Position is a position of the protocol: a zero-based line and a column in the units of the encoding.
func ToProtocol ¶
ToProtocol converts a position of the API in the text to the protocol's, counted in the encoding. A column past the end of the line is the end of the line, and a column inside a character is the start of it.
type Program ¶
type Program struct {
// Name is the name shown in messages ("basedpyright"); Exe is the name of the file looked for, Name when empty.
Name, Exe string
// Args are the arguments it is started with (--stdio).
Args []string
// PathSetting is the setting, written by the user, that holds the path of the program (rust-analyzer.server.path); the pack
// declares it with Config.SettingSpecs. A value with a slash is the path itself (a relative one is relative to the folder);
// one without is a name looked for like Exe. It is not searched further when it is set and wrong (ServerPathInvalid).
PathSetting string
// Before and After are folders searched before and after PATH, in order: "${workspaceFolder}/node_modules/.bin" before,
// "~/.cargo/bin" after. ~ and ${userHome} are the home folder, ${workspaceFolder} the folder of the tab, ${env:NAME} a
// variable of Emetos's environment.
Before, After []string
// Dirs gives more folders from the settings and the folder (the bin folder of the interpreter), searched before the Before
// folders and after the After folders respectively. It may be nil.
Dirs func(env Env) (before, after []string)
// PathDescription is the description of the path setting when the program is not "the path of the <Name> program" (jdtls is a
// folder). CheckPath, when it is not nil, replaces the check of what Set Path... is given (CheckPath of this package says a folder
// is wrong); it returns why the text is not valid, "" when it is.
PathDescription string
CheckPath func(env Env, text string) string
// Find replaces the whole search when it is not nil (jdtls is a folder with a launcher jar, not a program on PATH). It may
// call FindExecutable. Its error is returned as it is.
Find func(env Env) (Found, error)
// Version says how to ask the program for its version, and the oldest that is accepted.
Version VersionCheck
// Install says how to get the program.
Install Install
}
Program is a program that can be the language server, and where to look for it.
type ProgramCheck ¶
type ProgramCheck struct {
// Name is the name of the program in the details ("dlv").
Name string
// Find finds it: the path, or an error when it is not there. The error's message is the detail of a missing program when
// Missing is empty.
Find func() (string, error)
// Missing is the detail of a program that was not found; the message of Find's error when empty.
Missing string
// Version asks the program for its version (nil Args: it is not asked); its Min is the oldest accepted.
Version VersionCheck
// Folder is where the version is asked, Env the environment (nil is Emetos's).
Folder string
Env []string
}
ProgramCheck says how CheckProgram finds a program and asks for its version.
type ProjectOptions ¶
type ProjectOptions struct {
// Depth is how many levels below the folder are looked at: 3 when zero, and a negative number looks at the folder only.
Depth int
// Limit is the most projects listed; 200 when zero.
Limit int
// Skip are names of folders not entered, besides the usual ones (SkipFolders).
Skip []string
}
ProjectOptions bound FindProjects.
type Settings ¶
type Settings struct {
// contains filtered or unexported fields
}
Settings reads the settings of the tab for the hooks of a Config and remembers which it read, so that a change of one of them restarts the server (Controller). It is safe for use from any goroutine.
func NewSettings ¶
NewSettings makes Settings over a function that reads a setting (extension.LaunchRequest.Setting).
func (*Settings) String ¶
String is the value of a string setting, "" when it is not one. Surrounding spaces are removed.
type VersionCheck ¶
type VersionCheck struct {
// Args are the arguments that make the program print its version and exit (--version); nil for a program that has no way, which
// is then never asked.
Args []string
// Exe is the name of another file in the folder of the program found that is run instead of it (basedpyright-langserver has no
// --version, its sibling basedpyright has); empty runs the program itself. A sibling that is not there is a version that cannot
// be read, no failure.
Exe string
// Parse finds the version in what the program printed; DefaultVersion when nil.
Parse func(output string) (string, bool)
// Min is the oldest version accepted ("1.2"); a program that is older fails the start with ServerTooOld. Empty accepts any. A
// version that could not be read is not refused.
Min string
}
VersionCheck says how to ask a program for its version.