langserver

package
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	HealthOK      = "ok"
	HealthWarning = "warning"
	HealthError   = "error"
)

The levels of a Health, as rust-analyzer's experimental/serverStatus names them.

View Source
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.

View Source
const (
	FamilyAny    = "any"
	FamilyFedora = "fedora"
	FamilyDebian = "debian"
	FamilyArch   = "arch"
	FamilySuse   = "suse"
)

The families of systems an InstallCommand is for.

View Source
const (
	EncodingUTF8  = "utf-8"
	EncodingUTF16 = "utf-16"
	EncodingUTF32 = "utf-32"
)

The names of the encodings, as the protocol spells them.

View Source
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

View Source
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

func CheckPath(env Env, text string) string

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 CompareVersions

func CompareVersions(a, b string) int

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

func DefaultVersion(output string) (string, bool)

DefaultVersion finds the first dotted number in the output: "rust-analyzer 1.78.0 (9b00956e5 2024-04-29)" gives "1.78.0".

func Family

func Family(osRelease string) string

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

func FindExecutable(name string, dirs []string) (string, bool)

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

func Fingerprint(v any, ok bool) string

Fingerprint is a text that is equal for equal values of a setting: its JSON, or "absent" for a setting nobody registered.

func FromProtocol

func FromProtocol(text string, p Position, encoding string) extension.Position

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

func HasMarker(dir string, markers []string) bool

HasMarker tells whether the folder holds a file or folder that matches one of the markers (names, globs allowed).

func IsExecutable

func IsExecutable(path string) bool

IsExecutable tells whether the path is a file (a link to one counts) that someone may run.

func ProvideContent

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

func RangeFromProtocol(text string, r Range, encoding string) extension.Range

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

func ResolveRoot(folder string, markers []string, home string) string

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

func SetNested(m map[string]any, path []string, v any)

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).

func StatusID

func StatusID(serverID string) string

StatusID is the id of the status bar item of a server: "status." and the id of the server.

func UTF16Column

func UTF16Column(text string, p extension.Position) int

UTF16Column is the column of the position in UTF-16 code units: the column Documents().Show takes (counted from 0 here, from 1 there).

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) 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

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

func (c Config) Subscribes() []string

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
}

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

func DefaultEnv(folder string, s *Settings) Env

DefaultEnv is the Env of this machine for a tab: the folder, the home folder, PATH, and the settings.

func (Env) Abs

func (e Env) Abs(tmpl string) string

Abs makes the absolute path of a template (Expand, and joined to the folder of the tab when it is relative), cleaned.

func (Env) Expand

func (e Env) Expand(tmpl string) string

Expand replaces ~, ${userHome}, ${workspaceFolder} and ${env:NAME} in a path template; a relative result is relative to the folder of the tab.

func (Env) Getenv

func (e Env) Getenv(name string) string

Getenv reads a variable of Emetos's environment (Environ when set, else os.Getenv): the environment variables a pack looks at (VIRTUAL_ENV) go through it, so that a test gives them.

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

func Find(p Program, env Env) (Found, error)

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

type Install struct {
	// Docs is the address of the instructions of the server, shown in the dialog How to Install.
	Docs string
	// Commands are the usual commands: one for each family of systems (FamilyFedora, FamilyDebian...), or for the language's own
	// installer (FamilyAny: cargo, npm, dotnet tool).
	Commands []InstallCommand
}

Install says how to get a program (SPEC §10.34: Emetos never installs a server, D47; it tells the user how).

func (Install) CommandFor

func (i Install) CommandFor(family string) (InstallCommand, bool)

CommandFor chooses the command for the system: the one for its family, else the one for every system, else the first. It reports false when there is no command.

type InstallCommand

type InstallCommand struct {
	// Family is the family of systems the command is for (the Family constants), FamilyAny for every system.
	Family string
	// Command is the command line, ready to paste in a terminal.
	Command string
}

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

func Resolve(ctx context.Context, cfg Config, env Env) (*Launch, error)

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 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

func WithOSRelease(text string) Option

WithOSRelease makes the controller read the family of the system from the text instead of from /etc/os-release.

type Position

type Position struct {
	Line      int `json:"line"`
	Character int `json:"character"`
}

Position is a position of the protocol: a zero-based line and a column in the units of the encoding.

func ToProtocol

func ToProtocol(text string, p extension.Position, encoding string) Position

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 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 Range

type Range struct {
	Start Position `json:"start"`
	End   Position `json:"end"`
}

Range is a range of the protocol.

func RangeToProtocol

func RangeToProtocol(text string, r extension.Range, encoding string) Range

RangeToProtocol converts a range of the API to the protocol's.

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

func NewSettings(get func(key string) (any, bool)) *Settings

NewSettings makes Settings over a function that reads a setting (extension.LaunchRequest.Setting).

func (*Settings) Bool

func (s *Settings) Bool(key string) bool

Bool is the value of a boolean setting, false when it is not one.

func (*Settings) Float

func (s *Settings) Float(key string) float64

Float is the value of a number setting, 0 when it is not one.

func (*Settings) Keys

func (s *Settings) Keys() []string

Keys are the keys that were read, sorted.

func (*Settings) Object

func (s *Settings) Object(key string) map[string]any

Object is the value of an object setting, nil when it is not one.

func (*Settings) Read

func (s *Settings) Read() map[string]string

Read lists what was read: each key with the Fingerprint of its value.

func (*Settings) String

func (s *Settings) String(key string) string

String is the value of a string setting, "" when it is not one. Surrounding spaces are removed.

func (*Settings) Strings

func (s *Settings) Strings(key string) []string

Strings is the value of an array of strings; other members and other types give nothing.

func (*Settings) Value

func (s *Settings) Value(key string) (any, bool)

Value is the value of the setting and whether there is such a setting. The key is remembered either way.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL