@jupyterlab/lsp 4.0.0-alpha.19 → 4.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/manager.ts ADDED
@@ -0,0 +1,336 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { PageConfig, URLExt } from '@jupyterlab/coreutils';
5
+ import { ServerConnection } from '@jupyterlab/services';
6
+ import { ISignal, Signal } from '@lumino/signaling';
7
+
8
+ import {
9
+ ILanguageServerManager,
10
+ TLanguageServerConfigurations,
11
+ TLanguageServerId,
12
+ TSessionMap,
13
+ TSpecsMap
14
+ } from './tokens';
15
+ import { ServerSpecProperties } from './schema';
16
+ import { PromiseDelegate } from '@lumino/coreutils';
17
+
18
+ export class LanguageServerManager implements ILanguageServerManager {
19
+ constructor(options: ILanguageServerManager.IOptions) {
20
+ this._settings = options.settings || ServerConnection.makeSettings();
21
+ this._baseUrl = options.baseUrl || PageConfig.getBaseUrl();
22
+ this._retries = options.retries || 2;
23
+ this._retriesInterval = options.retriesInterval || 10000;
24
+ this._statusCode = -1;
25
+ this._configuration = {};
26
+
27
+ this.fetchSessions().catch(e => console.log(e));
28
+ }
29
+
30
+ /**
31
+ * Check if the manager is enabled or disabled
32
+ */
33
+ get isEnabled(): boolean {
34
+ return this._enabled;
35
+ }
36
+ /**
37
+ * Check if the manager is disposed.
38
+ */
39
+ get isDisposed(): boolean {
40
+ return this._isDisposed;
41
+ }
42
+
43
+ /**
44
+ * Get the language server specs.
45
+ */
46
+ get specs(): TSpecsMap {
47
+ return this._specs;
48
+ }
49
+
50
+ /**
51
+ * Get the status end point.
52
+ */
53
+ get statusUrl(): string {
54
+ return URLExt.join(this._baseUrl, ILanguageServerManager.URL_NS, 'status');
55
+ }
56
+
57
+ /**
58
+ * Signal emitted when a language server session is changed
59
+ */
60
+ get sessionsChanged(): ISignal<ILanguageServerManager, void> {
61
+ return this._sessionsChanged;
62
+ }
63
+
64
+ /**
65
+ * Get the map of language server sessions.
66
+ */
67
+ get sessions(): TSessionMap {
68
+ return this._sessions;
69
+ }
70
+
71
+ /**
72
+ * A promise resolved when this server manager is ready.
73
+ */
74
+ get ready(): Promise<void> {
75
+ return this._ready.promise;
76
+ }
77
+
78
+ /**
79
+ * Get the status code of server's responses.
80
+ */
81
+ get statusCode(): number {
82
+ return this._statusCode;
83
+ }
84
+
85
+ /**
86
+ * Enable the language server services
87
+ */
88
+ async enable(): Promise<void> {
89
+ this._enabled = true;
90
+ await this.fetchSessions();
91
+ }
92
+
93
+ /**
94
+ * Disable the language server services
95
+ */
96
+ disable(): void {
97
+ this._enabled = false;
98
+ this._sessions = new Map();
99
+ this._sessionsChanged.emit(void 0);
100
+ }
101
+
102
+ /**
103
+ * Dispose the manager.
104
+ */
105
+ dispose(): void {
106
+ if (this._isDisposed) {
107
+ return;
108
+ }
109
+ this._isDisposed = true;
110
+
111
+ Signal.clearData(this);
112
+ }
113
+
114
+ /**
115
+ * Update the language server configuration.
116
+ */
117
+ setConfiguration(configuration: TLanguageServerConfigurations): void {
118
+ this._configuration = configuration;
119
+ }
120
+
121
+ /**
122
+ * Get matching language server for input language option.
123
+ */
124
+ getMatchingServers(
125
+ options: ILanguageServerManager.IGetServerIdOptions
126
+ ): TLanguageServerId[] {
127
+ if (!options.language) {
128
+ console.error(
129
+ 'Cannot match server by language: language not available; ensure that kernel and specs provide language and MIME type'
130
+ );
131
+ return [];
132
+ }
133
+
134
+ const matchingSessionsKeys: TLanguageServerId[] = [];
135
+
136
+ for (const [key, session] of this._sessions.entries()) {
137
+ if (this.isMatchingSpec(options, session.spec)) {
138
+ matchingSessionsKeys.push(key);
139
+ }
140
+ }
141
+
142
+ return matchingSessionsKeys.sort(this.compareRanks.bind(this));
143
+ }
144
+
145
+ /**
146
+ * Get matching language server spec for input language option.
147
+ */
148
+ getMatchingSpecs(
149
+ options: ILanguageServerManager.IGetServerIdOptions
150
+ ): TSpecsMap {
151
+ const result: TSpecsMap = new Map();
152
+
153
+ for (const [key, specification] of this._specs.entries()) {
154
+ if (this.isMatchingSpec(options, specification)) {
155
+ result.set(key, specification);
156
+ }
157
+ }
158
+ return result;
159
+ }
160
+
161
+ /**
162
+ * Fetch the server session list from the status endpoint. The server
163
+ * manager is ready once this method finishes.
164
+ */
165
+ async fetchSessions(): Promise<void> {
166
+ if (!this._enabled) {
167
+ return;
168
+ }
169
+ let response = await ServerConnection.makeRequest(
170
+ this.statusUrl,
171
+ { method: 'GET' },
172
+ this._settings
173
+ );
174
+
175
+ this._statusCode = response.status;
176
+ if (!response.ok) {
177
+ if (this._retries > 0) {
178
+ this._retries -= 1;
179
+ setTimeout(this.fetchSessions.bind(this), this._retriesInterval);
180
+ } else {
181
+ this._ready.resolve(undefined);
182
+ console.log('Missing jupyter_lsp server extension, skipping.');
183
+ }
184
+ return;
185
+ }
186
+
187
+ let sessions: { [key: string]: any };
188
+
189
+ try {
190
+ const data = await response.json();
191
+ sessions = data.sessions;
192
+ try {
193
+ this.version = data.version;
194
+ this._specs = new Map(Object.entries(data.specs)) as TSpecsMap;
195
+ } catch (err) {
196
+ console.warn(err);
197
+ }
198
+ } catch (err) {
199
+ console.warn(err);
200
+ this._ready.resolve(undefined);
201
+ return;
202
+ }
203
+
204
+ for (let key of Object.keys(sessions)) {
205
+ let id: TLanguageServerId = key as TLanguageServerId;
206
+ if (this._sessions.has(id)) {
207
+ Object.assign(this._sessions.get(id)!, sessions[key]);
208
+ } else {
209
+ this._sessions.set(id, sessions[key]);
210
+ }
211
+ }
212
+
213
+ const oldKeys = this._sessions.keys();
214
+
215
+ for (const oldKey in oldKeys) {
216
+ if (!sessions[oldKey]) {
217
+ let oldId = oldKey as TLanguageServerId;
218
+ this._sessions.delete(oldId);
219
+ }
220
+ }
221
+ this._sessionsChanged.emit(void 0);
222
+ this._ready.resolve(undefined);
223
+ }
224
+
225
+ /**
226
+ * Version number of sever session.
227
+ */
228
+ protected version: number;
229
+
230
+ /**
231
+ * Check if input language option maths the language server spec.
232
+ */
233
+ protected isMatchingSpec(
234
+ options: ILanguageServerManager.IGetServerIdOptions,
235
+ spec: ServerSpecProperties
236
+ ): boolean {
237
+ // most things speak language
238
+ // if language is not known, it is guessed based on MIME type earlier
239
+ // so some language should be available by now (which can be not so obvious, e.g. "plain" for txt documents)
240
+ const lowerCaseLanguage = options.language!.toLocaleLowerCase();
241
+ return spec.languages!.some(
242
+ (language: string) => language.toLocaleLowerCase() == lowerCaseLanguage
243
+ );
244
+ }
245
+
246
+ /**
247
+ * Helper function to warn a message only once.
248
+ */
249
+ protected warnOnce(arg: string): void {
250
+ if (!this._warningsEmitted.has(arg)) {
251
+ this._warningsEmitted.add(arg);
252
+ console.warn(arg);
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Compare the rank of two servers with the same language.
258
+ */
259
+ protected compareRanks(a: TLanguageServerId, b: TLanguageServerId): number {
260
+ const DEFAULT_RANK = 50;
261
+ const aRank = this._configuration[a]?.rank ?? DEFAULT_RANK;
262
+ const bRank = this._configuration[b]?.rank ?? DEFAULT_RANK;
263
+ if (aRank == bRank) {
264
+ this.warnOnce(
265
+ `Two matching servers: ${a} and ${b} have the same rank; choose which one to use by changing the rank in Advanced Settings Editor`
266
+ );
267
+ return a.localeCompare(b);
268
+ }
269
+ // higher rank = higher in the list (descending order)
270
+ return bRank - aRank;
271
+ }
272
+
273
+ /**
274
+ * map of language server sessions.
275
+ */
276
+ private _sessions: TSessionMap = new Map();
277
+
278
+ /**
279
+ * Map of language server specs.
280
+ */
281
+ private _specs: TSpecsMap = new Map();
282
+
283
+ /**
284
+ * Server connection setting.
285
+ */
286
+ private _settings: ServerConnection.ISettings;
287
+
288
+ /**
289
+ * Base URL to connect to the language server handler.
290
+ */
291
+ private _baseUrl: string;
292
+
293
+ /**
294
+ * Status code of server response
295
+ */
296
+ private _statusCode: number;
297
+
298
+ /**
299
+ * Number of connection retry, default to 2.
300
+ */
301
+ private _retries: number;
302
+
303
+ /**
304
+ * Interval between each retry, default to 10s.
305
+ */
306
+ private _retriesInterval: number;
307
+
308
+ /**
309
+ * Language server configuration.
310
+ */
311
+ private _configuration: TLanguageServerConfigurations;
312
+
313
+ /**
314
+ * Set of emitted warning message, message in this set will not be warned again.
315
+ */
316
+ private _warningsEmitted = new Set<string>();
317
+
318
+ /**
319
+ * A promise resolved when this server manager is ready.
320
+ */
321
+ private _ready = new PromiseDelegate<void>();
322
+
323
+ /**
324
+ * Signal emitted when a language server session is changed
325
+ */
326
+ private _sessionsChanged: Signal<ILanguageServerManager, void> = new Signal(
327
+ this
328
+ );
329
+
330
+ private _isDisposed = false;
331
+
332
+ /**
333
+ * Check if the manager is enabled or disabled
334
+ */
335
+ private _enabled = true;
336
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,62 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ /* eslint-disable */
5
+
6
+ /**
7
+ * This file was automatically generated by json-schema-to-typescript.
8
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
9
+ * and run jlpm build:schema to regenerate this file.
10
+ */
11
+
12
+ /**
13
+ * Enable or disable the language server services.
14
+ */
15
+ export type Activate = 'off' | 'on';
16
+ /**
17
+ * When multiple servers match specific document/language, the server with the highest rank will be used
18
+ */
19
+ export type RankOfTheServer = number;
20
+ /**
21
+ * Whether to ask server to send logs with execution trace (for debugging). Accepted values are: "off", "messages", "verbose". Servers are allowed to ignore this request.
22
+ */
23
+ export type AskServersToSendTraceNotifications = 'off' | 'messages' | 'verbose';
24
+ /**
25
+ * Enable or disable the logging feature of the language servers.
26
+ */
27
+ export type LogCommunication = boolean;
28
+
29
+ /**
30
+ * Language Server Protocol settings.
31
+ */
32
+ export interface LanguageServersExperimental {
33
+ activate?: Activate;
34
+ languageServers?: LanguageServer;
35
+ setTrace?: AskServersToSendTraceNotifications;
36
+ logAllCommunication?: LogCommunication;
37
+ [k: string]: any;
38
+ }
39
+ /**
40
+ * Language-server specific configuration, keyed by implementation
41
+ */
42
+ export interface LanguageServer {
43
+ [k: string]: LanguageServer1;
44
+ }
45
+ /**
46
+ * This interface was referenced by `LanguageServer`'s JSON-Schema definition
47
+ * via the `patternProperty` ".*".
48
+ *
49
+ * This interface was referenced by `LanguageServersExperimental`'s JSON-Schema
50
+ * via the `definition` "languageServer".
51
+ */
52
+ export interface LanguageServer1 {
53
+ configuration?: LanguageServerConfigurations;
54
+ rank?: RankOfTheServer;
55
+ [k: string]: any;
56
+ }
57
+ /**
58
+ * Configuration to be sent to language server over LSP when initialized: see the specific language server's documentation for more
59
+ */
60
+ export interface LanguageServerConfigurations {
61
+ [k: string]: any;
62
+ }
@@ -0,0 +1,126 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { CodeEditor } from '@jupyterlab/codeeditor';
5
+ import type * as lsp from 'vscode-languageserver-protocol';
6
+
7
+ /**
8
+ * CM5 position interface.
9
+ *
10
+ * TODO: Migrate to offset-only mode once `CodeEditor.IPosition`
11
+ * is migrated.
12
+ */
13
+ export interface IPosition {
14
+ /**
15
+ * Line number
16
+ */
17
+ line: number;
18
+
19
+ /**
20
+ * Position of character in line
21
+ */
22
+ ch: number;
23
+ }
24
+
25
+ /**
26
+ * is_* attributes are there only to enforce strict interface type checking
27
+ */
28
+ export interface ISourcePosition extends IPosition {
29
+ isSource: true;
30
+ }
31
+
32
+ export interface IEditorPosition extends IPosition {
33
+ isEditor: true;
34
+ }
35
+
36
+ export interface IVirtualPosition extends IPosition {
37
+ isVirtual: true;
38
+ }
39
+
40
+ export interface IRootPosition extends ISourcePosition {
41
+ isRoot: true;
42
+ }
43
+
44
+ /**
45
+ * Compare two `IPosition` variable.
46
+ *
47
+ */
48
+ export function isEqual(self: IPosition, other: IPosition): boolean {
49
+ return other && self.line === other.line && self.ch === other.ch;
50
+ }
51
+
52
+ /**
53
+ * Given a list of line and an offset from the start, compute the corresponding
54
+ * position in form of line and column number
55
+ *
56
+ * @param offset - number of spaces counted from the start of first line
57
+ * @param lines - list of lines to compute the position
58
+ * @return - the position of cursor
59
+ */
60
+ export function positionAtOffset(
61
+ offset: number,
62
+ lines: string[]
63
+ ): CodeEditor.IPosition {
64
+ let line = 0;
65
+ let column = 0;
66
+ for (let textLine of lines) {
67
+ // each line has a new line symbol which is accounted for in offset!
68
+ if (textLine.length + 1 <= offset) {
69
+ offset -= textLine.length + 1;
70
+ line += 1;
71
+ } else {
72
+ column = offset;
73
+ break;
74
+ }
75
+ }
76
+ return { line, column };
77
+ }
78
+
79
+ /**
80
+ * Given a list of line and position in form of line and column number,
81
+ * compute the offset from the start of first line.
82
+ * @param position - postion of cursor
83
+ * @param lines - list of lines to compute the position
84
+ * @param linesIncludeBreaks - should count the line break as space?
85
+ * return - offset number
86
+ */
87
+ export function offsetAtPosition(
88
+ position: CodeEditor.IPosition,
89
+ lines: string[],
90
+ linesIncludeBreaks = false
91
+ ): number {
92
+ let breakIncrement = linesIncludeBreaks ? 0 : 1;
93
+ let offset = 0;
94
+ for (let i = 0; i < lines.length; i++) {
95
+ let textLine = lines[i];
96
+ if (position.line > i) {
97
+ offset += textLine.length + breakIncrement;
98
+ } else {
99
+ offset += position.column;
100
+ break;
101
+ }
102
+ }
103
+ return offset;
104
+ }
105
+
106
+ export namespace ProtocolCoordinates {
107
+ /**
108
+ * Check if the position is in the input range
109
+ *
110
+ * @param position - position in form of line and character number.
111
+ * @param range - range in from of start and end position.
112
+ */
113
+ export function isWithinRange(
114
+ position: lsp.Position,
115
+ range: lsp.Range
116
+ ): boolean {
117
+ const { line, character } = position;
118
+ return (
119
+ line >= range.start.line &&
120
+ line <= range.end.line &&
121
+ // need to be non-overlapping see https://github.com/jupyter-lsp/jupyterlab-lsp/issues/628
122
+ (line != range.start.line || character > range.start.character) &&
123
+ (line != range.end.line || character <= range.end.character)
124
+ );
125
+ }
126
+ }