1 (function(e, a) { for(var i in a) e[i] = a[i]; if(a.__esModule) Object.defineProperty(e, "__esModule", { value: true }); }(exports,
2 /******/ (() => { // webpackBootstrap
4 /******/ var __webpack_modules__ = ([
6 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
9 var __importDefault = (this && this.__importDefault) || function (mod) {
10 return (mod && mod.__esModule) ? mod : { "default": mod };
12 Object.defineProperty(exports, "__esModule", ({ value: true }));
13 exports.activate = void 0;
14 /******************************************************************
15 MIT License http://www.opensource.org/licenses/mit-license.php
16 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
17 *******************************************************************/
18 const coc_nvim_1 = __webpack_require__(1);
19 const fs_1 = __importDefault(__webpack_require__(2));
20 const os_1 = __importDefault(__webpack_require__(3));
21 const path_1 = __importDefault(__webpack_require__(4));
22 const util_1 = __importDefault(__webpack_require__(5));
23 const vscode_languageserver_types_1 = __webpack_require__(6);
24 const languages_1 = __importDefault(__webpack_require__(7));
25 const snippet_1 = __importDefault(__webpack_require__(37));
26 const provider_1 = __webpack_require__(38);
27 const snipmateProvider_1 = __webpack_require__(40);
28 const textmateProvider_1 = __webpack_require__(44);
29 const ultisnipsProvider_1 = __webpack_require__(50);
30 const documentation = `# A valid snippet should starts with:
32 # snippet trigger_word [ "description" [ options ] ]
40 # b - Beginning of line.
41 # i - In-word expansion.
43 # r - Regular expression
44 # e - Custom context snippet
45 # A - Snippet will be triggered automatically, when condition matches.
49 # snippet emitter "emitter properties" b
50 # private readonly $\{1} = new Emitter<$2>()
51 # public readonly $\{1/^_(.*)/$1/}: Event<$2> = this.$1.event
54 # Online reference: https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt
56 async function activate(context) {
57 let { subscriptions } = context;
58 const { nvim } = coc_nvim_1.workspace;
59 const configuration = coc_nvim_1.workspace.getConfiguration('snippets');
60 const filetypeExtends = configuration.get('extends', {});
61 const manager = new provider_1.ProviderManager();
62 const trace = configuration.get('trace', 'error');
63 let mru = coc_nvim_1.workspace.createMru('snippets-mru');
64 const channel = coc_nvim_1.workspace.createOutputChannel('snippets');
65 let snippetsDir = configuration.get('userSnippetsDirectory');
67 snippetsDir = snippetsDir.replace(/^~/, os_1.default.homedir());
68 if (snippetsDir.indexOf('$') !== -1) {
69 snippetsDir = snippetsDir.replace(/\$(\w+)/g, (match, p1) => {
71 return (_a = process.env[p1]) !== null && _a !== void 0 ? _a : match;
74 if (!path_1.default.isAbsolute(snippetsDir)) {
75 coc_nvim_1.workspace.showMessage(`snippets.userSnippetsDirectory => ${snippetsDir} should be absolute path`, 'warning');
80 snippetsDir = path_1.default.join(path_1.default.dirname(coc_nvim_1.workspace.env.extensionRoot), 'ultisnips');
81 if (!fs_1.default.existsSync(snippetsDir)) {
82 await util_1.default.promisify(fs_1.default.mkdir)(snippetsDir);
84 coc_nvim_1.events.on('CompleteDone', async (item) => {
85 if (typeof item.user_data === 'string' && item.user_data.indexOf('snippets') !== -1) {
86 await mru.add(item.word);
88 }, null, subscriptions);
89 coc_nvim_1.workspace.onDidOpenTextDocument(async (document) => {
90 if (document.uri.endsWith('.snippets')) {
91 let doc = coc_nvim_1.workspace.getDocument(document.uri);
95 await buffer.setOption('filetype', 'snippets');
97 }, null, subscriptions);
98 if (configuration.get('ultisnips.enable', true)) {
99 let config = configuration.get('ultisnips', {});
100 let c = Object.assign({}, config, {
101 extends: Object.assign({}, filetypeExtends)
103 c.directories = c.directories ? c.directories.slice() : [];
104 if (c.directories.indexOf(snippetsDir) == -1) {
105 c.directories.push(snippetsDir);
107 let provider = new ultisnipsProvider_1.UltiSnippetsProvider(channel, trace, c, context);
108 manager.regist(provider, 'ultisnips');
109 subscriptions.push(provider);
110 // add rtp if ultisnips not found
111 nvim.getOption('runtimepath').then(async (rtp) => {
112 let paths = rtp.split(',');
113 let idx = paths.findIndex(s => /^ultisnips$/i.test(path_1.default.basename(s)));
116 let directory = path_1.default.resolve(__dirname, '..');
117 nvim.command('autocmd BufNewFile,BufRead *.snippets setf snippets', true);
118 nvim.command(`execute 'noa set rtp+='.fnameescape('${directory.replace(/'/g, "''")}')`, true);
119 coc_nvim_1.workspace.documents.forEach(doc => {
120 if (doc.uri.endsWith('.snippets')) {
121 doc.buffer.setOption('filetype', 'snippets', true);
129 loadFromExtensions: configuration.get('loadFromExtensions', true),
130 snippetsRoots: configuration.get('textmateSnippetsRoots', []),
131 extends: Object.assign({}, filetypeExtends)
133 let provider = new textmateProvider_1.TextmateProvider(channel, trace, config);
134 manager.regist(provider, 'snippets');
135 if (configuration.get('snipmate.enable', true)) {
137 author: configuration.get('snipmate.author', ''),
138 extends: Object.assign({}, filetypeExtends)
140 let provider = new snipmateProvider_1.SnipmateProvider(channel, trace, config);
141 manager.regist(provider, 'snipmate');
143 if (configuration.get('autoTrigger', true)) {
147 coc_nvim_1.events.on('InsertCharPre', character => {
148 insertTs = Date.now();
149 lastInsert = character;
150 }, null, subscriptions);
151 coc_nvim_1.events.on('InsertLeave', () => {
152 insertLeaveTs = Date.now();
153 }, null, subscriptions);
154 let inserting = false;
155 const handleTextChange = async (bufnr, pre) => {
156 let lastInsertTs = insertTs;
157 insertTs = undefined;
160 let doc = coc_nvim_1.workspace.getDocument(bufnr);
161 if (!doc || doc.isCommandLine || !doc.attached)
163 let now = Date.now();
164 if (!lastInsertTs || now - lastInsertTs > 100 || !pre.endsWith(lastInsert))
166 let edits = await manager.getTriggerSnippets(true);
167 if (edits.length == 0)
169 if (edits.length > 1) {
170 channel.appendLine(`Multiple snippet found for auto trigger: ${edits.map(s => s.prefix).join(', ')}`);
171 coc_nvim_1.workspace.showMessage('Multiple snippet found for auto trigger, check output by :CocCommand workspace.showOutput', 'warning');
173 if (insertLeaveTs > now || inserting)
177 await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[0]);
178 await mru.add(edits[0].prefix);
185 coc_nvim_1.events.on('TextChangedI', async (bufnr, info) => {
186 await handleTextChange(bufnr, info.pre);
187 }, null, subscriptions);
188 coc_nvim_1.events.on('TextChangedP', async (bufnr, info) => {
189 await handleTextChange(bufnr, info.pre);
190 }, null, subscriptions);
193 if (configuration.get('enableStatusItem', true)) {
194 statusItem = coc_nvim_1.workspace.createStatusBarItem(90, { progress: true });
195 statusItem.text = 'loading snippets';
198 manager.init().then(() => {
199 statusItem === null || statusItem === void 0 ? void 0 : statusItem.hide();
201 statusItem === null || statusItem === void 0 ? void 0 : statusItem.hide();
202 coc_nvim_1.workspace.showMessage(`Error on load snippets: ${e.message}`, 'error');
204 if (manager.hasProvider) {
205 let disposable = coc_nvim_1.languages.registerCompletionItemProvider('snippets', 'S', null, manager, configuration.get('triggerCharacters', []), configuration.get('priority', 90));
206 subscriptions.push(disposable);
208 async function fallback() {
209 await nvim.call('coc#start', [{ source: 'snippets' }]);
211 async function doExpand() {
212 let edits = await manager.getTriggerSnippets();
213 if (edits.length == 0)
215 if (edits.length == 1) {
216 await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[0]);
217 await mru.add(edits[0].prefix);
220 let idx = await coc_nvim_1.workspace.showQuickpick(edits.map(e => e.description || e.prefix), 'choose snippet:');
223 await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edits[idx]);
224 await mru.add(edits[idx].prefix);
228 subscriptions.push(coc_nvim_1.workspace.registerKeymap(['x'], 'convert-snippet', async () => {
229 let mode = await coc_nvim_1.workspace.nvim.call('visualmode');
232 let doc = await coc_nvim_1.workspace.document;
236 let range = await coc_nvim_1.workspace.getSelectedRange(mode, doc);
237 let text = doc.textDocument.getText(range);
239 await coc_nvim_1.commands.executeCommand('snippets.editSnippets', text);
240 }, { sync: false }));
241 subscriptions.push(coc_nvim_1.commands.registerCommand('snippets.editSnippets', async (text) => {
242 let buf = await nvim.buffer;
243 let doc = coc_nvim_1.workspace.getDocument(buf.id);
245 coc_nvim_1.workspace.showMessage('Document not found', 'error');
248 let file = path_1.default.join(snippetsDir, `${doc.filetype}.snippets`);
249 if (!fs_1.default.existsSync(file)) {
250 await util_1.default.promisify(fs_1.default.writeFile)(file, documentation, 'utf8');
252 let uri = coc_nvim_1.Uri.file(file).toString();
253 await coc_nvim_1.workspace.jumpTo(uri, null, configuration.get('editSnippetsCommand'));
255 await nvim.command('normal! G');
256 await nvim.command('normal! 2o');
257 let position = await coc_nvim_1.workspace.getCursorPosition();
258 let indent = text.match(/^\s*/)[0];
259 text = text.split(/\r?\n/).map(s => s.startsWith(indent) ? s.slice(indent.length) : s).join('\n');
260 let escaped = text.replace(/([$}\]])/g, '\\$1');
261 // tslint:disable-next-line: no-invalid-template-strings
262 let snippet = 'snippet ${1:Tab_trigger} "${2:Description}" ${3:b}\n' + escaped + '\nendsnippet';
263 let edit = vscode_languageserver_types_1.TextEdit.insert(position, snippet);
264 await coc_nvim_1.commands.executeCommand('editor.action.insertSnippet', edit);
267 subscriptions.push(coc_nvim_1.commands.registerCommand('snippets.openSnippetFiles', async () => {
268 let buf = await nvim.buffer;
269 let doc = coc_nvim_1.workspace.getDocument(buf.id);
271 coc_nvim_1.workspace.showMessage('Document not found', 'error');
274 let files = await manager.getSnippetFiles(doc.filetype);
276 coc_nvim_1.workspace.showMessage('No related snippet file found', 'warning');
279 let idx = await coc_nvim_1.workspace.showQuickpick(files, 'choose snippet file:');
282 let uri = coc_nvim_1.Uri.file(files[idx]).toString();
283 await coc_nvim_1.workspace.jumpTo(uri, null, configuration.get('editSnippetsCommand'));
285 subscriptions.push(coc_nvim_1.workspace.registerKeymap(['i'], 'snippets-expand', async () => {
286 let expanded = await doExpand();
289 }, { silent: true, sync: false, cancel: true }));
290 subscriptions.push(coc_nvim_1.workspace.registerKeymap(['i'], 'snippets-expand-jump', async () => {
291 let expanded = await doExpand();
293 let bufnr = await nvim.call('bufnr', '%');
294 let session = coc_nvim_1.snippetManager.getSession(bufnr);
295 if (session && session.isActive) {
296 await nvim.call('coc#_cancel', []);
297 await coc_nvim_1.snippetManager.nextPlaceholder();
302 }, { silent: true, sync: false, cancel: true }));
303 subscriptions.push(coc_nvim_1.workspace.registerKeymap(['v'], 'snippets-select', async () => {
304 let doc = await coc_nvim_1.workspace.document;
307 let mode = await nvim.call('visualmode');
308 if (['v', 'V'].indexOf(mode) == -1) {
309 coc_nvim_1.workspace.showMessage(`visual mode ${mode} not supported`, 'warning');
312 await nvim.command('normal! `<');
313 let start = await coc_nvim_1.workspace.getCursorPosition();
314 await nvim.command('normal! `>');
315 let end = await coc_nvim_1.workspace.getCursorPosition();
316 end = vscode_languageserver_types_1.Position.create(end.line, end.character + 1);
317 let range = vscode_languageserver_types_1.Range.create(start, end);
318 let text = doc.textDocument.getText(range);
319 await nvim.call('feedkeys', ['i', 'in']);
321 await doc.applyEdits([{ range, newText: '' }]);
325 let currline = doc.getline(start.line);
326 let indent = currline.match(/^\s*/)[0];
327 let lines = text.split(/\r?\n/);
328 lines = lines.map(s => s.startsWith(indent) ? s.slice(indent.length) : s);
329 text = lines.join('\n');
330 range = vscode_languageserver_types_1.Range.create(vscode_languageserver_types_1.Position.create(start.line, indent.length), end);
331 await doc.applyEdits([{ range, newText: '' }]);
333 await nvim.setVar('coc_selected_text', text);
334 await coc_nvim_1.workspace.moveTo(range.start);
335 }, { silent: true, sync: false, cancel: true }));
336 let languageProvider = new languages_1.default(channel, trace);
337 subscriptions.push(coc_nvim_1.languages.registerCompletionItemProvider('snippets-source', 'S', ['snippets'], languageProvider, ['$'], configuration.get('priority', 90)));
338 subscriptions.push(statusItem);
339 subscriptions.push(channel);
340 subscriptions.push(coc_nvim_1.listManager.registerList(new snippet_1.default(coc_nvim_1.workspace.nvim, manager, mru)));
342 expandable: async () => {
345 edits = await manager.getTriggerSnippets();
348 channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Error on getTriggerSnippets: ${e}`);
350 return edits && edits.length > 0;
354 exports.activate = activate;
361 module.exports = require("coc.nvim");;
367 module.exports = require("fs");;
373 module.exports = require("os");;
379 module.exports = require("path");;
385 module.exports = require("util");;
389 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
391 __webpack_require__.r(__webpack_exports__);
392 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
393 /* harmony export */ "Position": () => /* binding */ Position,
394 /* harmony export */ "Range": () => /* binding */ Range,
395 /* harmony export */ "Location": () => /* binding */ Location,
396 /* harmony export */ "LocationLink": () => /* binding */ LocationLink,
397 /* harmony export */ "Color": () => /* binding */ Color,
398 /* harmony export */ "ColorInformation": () => /* binding */ ColorInformation,
399 /* harmony export */ "ColorPresentation": () => /* binding */ ColorPresentation,
400 /* harmony export */ "FoldingRangeKind": () => /* binding */ FoldingRangeKind,
401 /* harmony export */ "FoldingRange": () => /* binding */ FoldingRange,
402 /* harmony export */ "DiagnosticRelatedInformation": () => /* binding */ DiagnosticRelatedInformation,
403 /* harmony export */ "DiagnosticSeverity": () => /* binding */ DiagnosticSeverity,
404 /* harmony export */ "DiagnosticTag": () => /* binding */ DiagnosticTag,
405 /* harmony export */ "Diagnostic": () => /* binding */ Diagnostic,
406 /* harmony export */ "Command": () => /* binding */ Command,
407 /* harmony export */ "TextEdit": () => /* binding */ TextEdit,
408 /* harmony export */ "TextDocumentEdit": () => /* binding */ TextDocumentEdit,
409 /* harmony export */ "CreateFile": () => /* binding */ CreateFile,
410 /* harmony export */ "RenameFile": () => /* binding */ RenameFile,
411 /* harmony export */ "DeleteFile": () => /* binding */ DeleteFile,
412 /* harmony export */ "WorkspaceEdit": () => /* binding */ WorkspaceEdit,
413 /* harmony export */ "WorkspaceChange": () => /* binding */ WorkspaceChange,
414 /* harmony export */ "TextDocumentIdentifier": () => /* binding */ TextDocumentIdentifier,
415 /* harmony export */ "VersionedTextDocumentIdentifier": () => /* binding */ VersionedTextDocumentIdentifier,
416 /* harmony export */ "TextDocumentItem": () => /* binding */ TextDocumentItem,
417 /* harmony export */ "MarkupKind": () => /* binding */ MarkupKind,
418 /* harmony export */ "MarkupContent": () => /* binding */ MarkupContent,
419 /* harmony export */ "CompletionItemKind": () => /* binding */ CompletionItemKind,
420 /* harmony export */ "InsertTextFormat": () => /* binding */ InsertTextFormat,
421 /* harmony export */ "CompletionItemTag": () => /* binding */ CompletionItemTag,
422 /* harmony export */ "CompletionItem": () => /* binding */ CompletionItem,
423 /* harmony export */ "CompletionList": () => /* binding */ CompletionList,
424 /* harmony export */ "MarkedString": () => /* binding */ MarkedString,
425 /* harmony export */ "Hover": () => /* binding */ Hover,
426 /* harmony export */ "ParameterInformation": () => /* binding */ ParameterInformation,
427 /* harmony export */ "SignatureInformation": () => /* binding */ SignatureInformation,
428 /* harmony export */ "DocumentHighlightKind": () => /* binding */ DocumentHighlightKind,
429 /* harmony export */ "DocumentHighlight": () => /* binding */ DocumentHighlight,
430 /* harmony export */ "SymbolKind": () => /* binding */ SymbolKind,
431 /* harmony export */ "SymbolTag": () => /* binding */ SymbolTag,
432 /* harmony export */ "SymbolInformation": () => /* binding */ SymbolInformation,
433 /* harmony export */ "DocumentSymbol": () => /* binding */ DocumentSymbol,
434 /* harmony export */ "CodeActionKind": () => /* binding */ CodeActionKind,
435 /* harmony export */ "CodeActionContext": () => /* binding */ CodeActionContext,
436 /* harmony export */ "CodeAction": () => /* binding */ CodeAction,
437 /* harmony export */ "CodeLens": () => /* binding */ CodeLens,
438 /* harmony export */ "FormattingOptions": () => /* binding */ FormattingOptions,
439 /* harmony export */ "DocumentLink": () => /* binding */ DocumentLink,
440 /* harmony export */ "SelectionRange": () => /* binding */ SelectionRange,
441 /* harmony export */ "EOL": () => /* binding */ EOL,
442 /* harmony export */ "TextDocument": () => /* binding */ TextDocument
443 /* harmony export */ });
444 /* --------------------------------------------------------------------------------------------
\r
445 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
446 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
447 * ------------------------------------------------------------------------------------------ */
\r
450 * The Position namespace provides helper functions to work with
\r
451 * [Position](#Position) literals.
\r
454 (function (Position) {
\r
456 * Creates a new Position literal from the given line and character.
\r
457 * @param line The position's line.
\r
458 * @param character The position's character.
\r
460 function create(line, character) {
\r
461 return { line: line, character: character };
\r
463 Position.create = create;
\r
465 * Checks whether the given liternal conforms to the [Position](#Position) interface.
\r
467 function is(value) {
\r
468 var candidate = value;
\r
469 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
\r
472 })(Position || (Position = {}));
\r
474 * The Range namespace provides helper functions to work with
\r
475 * [Range](#Range) literals.
\r
478 (function (Range) {
\r
479 function create(one, two, three, four) {
\r
480 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
\r
481 return { start: Position.create(one, two), end: Position.create(three, four) };
\r
483 else if (Position.is(one) && Position.is(two)) {
\r
484 return { start: one, end: two };
\r
487 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
\r
490 Range.create = create;
\r
492 * Checks whether the given literal conforms to the [Range](#Range) interface.
\r
494 function is(value) {
\r
495 var candidate = value;
\r
496 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
\r
499 })(Range || (Range = {}));
\r
501 * The Location namespace provides helper functions to work with
\r
502 * [Location](#Location) literals.
\r
505 (function (Location) {
\r
507 * Creates a Location literal.
\r
508 * @param uri The location's uri.
\r
509 * @param range The location's range.
\r
511 function create(uri, range) {
\r
512 return { uri: uri, range: range };
\r
514 Location.create = create;
\r
516 * Checks whether the given literal conforms to the [Location](#Location) interface.
\r
518 function is(value) {
\r
519 var candidate = value;
\r
520 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
\r
523 })(Location || (Location = {}));
\r
525 * The LocationLink namespace provides helper functions to work with
\r
526 * [LocationLink](#LocationLink) literals.
\r
529 (function (LocationLink) {
\r
531 * Creates a LocationLink literal.
\r
532 * @param targetUri The definition's uri.
\r
533 * @param targetRange The full range of the definition.
\r
534 * @param targetSelectionRange The span of the symbol definition at the target.
\r
535 * @param originSelectionRange The span of the symbol being defined in the originating source file.
\r
537 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
\r
538 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
\r
540 LocationLink.create = create;
\r
542 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
\r
544 function is(value) {
\r
545 var candidate = value;
\r
546 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
\r
547 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
\r
548 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
\r
550 LocationLink.is = is;
\r
551 })(LocationLink || (LocationLink = {}));
\r
553 * The Color namespace provides helper functions to work with
\r
554 * [Color](#Color) literals.
\r
557 (function (Color) {
\r
559 * Creates a new Color literal.
\r
561 function create(red, green, blue, alpha) {
\r
569 Color.create = create;
\r
571 * Checks whether the given literal conforms to the [Color](#Color) interface.
\r
573 function is(value) {
\r
574 var candidate = value;
\r
575 return Is.number(candidate.red)
\r
576 && Is.number(candidate.green)
\r
577 && Is.number(candidate.blue)
\r
578 && Is.number(candidate.alpha);
\r
581 })(Color || (Color = {}));
\r
583 * The ColorInformation namespace provides helper functions to work with
\r
584 * [ColorInformation](#ColorInformation) literals.
\r
586 var ColorInformation;
\r
587 (function (ColorInformation) {
\r
589 * Creates a new ColorInformation literal.
\r
591 function create(range, color) {
\r
597 ColorInformation.create = create;
\r
599 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
601 function is(value) {
\r
602 var candidate = value;
\r
603 return Range.is(candidate.range) && Color.is(candidate.color);
\r
605 ColorInformation.is = is;
\r
606 })(ColorInformation || (ColorInformation = {}));
\r
608 * The Color namespace provides helper functions to work with
\r
609 * [ColorPresentation](#ColorPresentation) literals.
\r
611 var ColorPresentation;
\r
612 (function (ColorPresentation) {
\r
614 * Creates a new ColorInformation literal.
\r
616 function create(label, textEdit, additionalTextEdits) {
\r
619 textEdit: textEdit,
\r
620 additionalTextEdits: additionalTextEdits,
\r
623 ColorPresentation.create = create;
\r
625 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
627 function is(value) {
\r
628 var candidate = value;
\r
629 return Is.string(candidate.label)
\r
630 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
\r
631 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
\r
633 ColorPresentation.is = is;
\r
634 })(ColorPresentation || (ColorPresentation = {}));
\r
636 * Enum of known range kinds
\r
638 var FoldingRangeKind;
\r
639 (function (FoldingRangeKind) {
\r
641 * Folding range for a comment
\r
643 FoldingRangeKind["Comment"] = "comment";
\r
645 * Folding range for a imports or includes
\r
647 FoldingRangeKind["Imports"] = "imports";
\r
649 * Folding range for a region (e.g. `#region`)
\r
651 FoldingRangeKind["Region"] = "region";
\r
652 })(FoldingRangeKind || (FoldingRangeKind = {}));
\r
654 * The folding range namespace provides helper functions to work with
\r
655 * [FoldingRange](#FoldingRange) literals.
\r
658 (function (FoldingRange) {
\r
660 * Creates a new FoldingRange literal.
\r
662 function create(startLine, endLine, startCharacter, endCharacter, kind) {
\r
664 startLine: startLine,
\r
667 if (Is.defined(startCharacter)) {
\r
668 result.startCharacter = startCharacter;
\r
670 if (Is.defined(endCharacter)) {
\r
671 result.endCharacter = endCharacter;
\r
673 if (Is.defined(kind)) {
\r
674 result.kind = kind;
\r
678 FoldingRange.create = create;
\r
680 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
\r
682 function is(value) {
\r
683 var candidate = value;
\r
684 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
\r
685 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
\r
686 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
\r
687 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
\r
689 FoldingRange.is = is;
\r
690 })(FoldingRange || (FoldingRange = {}));
\r
692 * The DiagnosticRelatedInformation namespace provides helper functions to work with
\r
693 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
\r
695 var DiagnosticRelatedInformation;
\r
696 (function (DiagnosticRelatedInformation) {
\r
698 * Creates a new DiagnosticRelatedInformation literal.
\r
700 function create(location, message) {
\r
702 location: location,
\r
706 DiagnosticRelatedInformation.create = create;
\r
708 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
\r
710 function is(value) {
\r
711 var candidate = value;
\r
712 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
\r
714 DiagnosticRelatedInformation.is = is;
\r
715 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
\r
717 * The diagnostic's severity.
\r
719 var DiagnosticSeverity;
\r
720 (function (DiagnosticSeverity) {
\r
722 * Reports an error.
\r
724 DiagnosticSeverity.Error = 1;
\r
726 * Reports a warning.
\r
728 DiagnosticSeverity.Warning = 2;
\r
730 * Reports an information.
\r
732 DiagnosticSeverity.Information = 3;
\r
736 DiagnosticSeverity.Hint = 4;
\r
737 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
\r
739 * The diagnostic tags.
\r
744 (function (DiagnosticTag) {
\r
746 * Unused or unnecessary code.
\r
748 * Clients are allowed to render diagnostics with this tag faded out instead of having
\r
749 * an error squiggle.
\r
751 DiagnosticTag.Unnecessary = 1;
\r
753 * Deprecated or obsolete code.
\r
755 * Clients are allowed to rendered diagnostics with this tag strike through.
\r
757 DiagnosticTag.Deprecated = 2;
\r
758 })(DiagnosticTag || (DiagnosticTag = {}));
\r
760 * The Diagnostic namespace provides helper functions to work with
\r
761 * [Diagnostic](#Diagnostic) literals.
\r
764 (function (Diagnostic) {
\r
766 * Creates a new Diagnostic literal.
\r
768 function create(range, message, severity, code, source, relatedInformation) {
\r
769 var result = { range: range, message: message };
\r
770 if (Is.defined(severity)) {
\r
771 result.severity = severity;
\r
773 if (Is.defined(code)) {
\r
774 result.code = code;
\r
776 if (Is.defined(source)) {
\r
777 result.source = source;
\r
779 if (Is.defined(relatedInformation)) {
\r
780 result.relatedInformation = relatedInformation;
\r
784 Diagnostic.create = create;
\r
786 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
\r
788 function is(value) {
\r
789 var candidate = value;
\r
790 return Is.defined(candidate)
\r
791 && Range.is(candidate.range)
\r
792 && Is.string(candidate.message)
\r
793 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
\r
794 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
\r
795 && (Is.string(candidate.source) || Is.undefined(candidate.source))
\r
796 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
\r
798 Diagnostic.is = is;
\r
799 })(Diagnostic || (Diagnostic = {}));
\r
801 * The Command namespace provides helper functions to work with
\r
802 * [Command](#Command) literals.
\r
805 (function (Command) {
\r
807 * Creates a new Command literal.
\r
809 function create(title, command) {
\r
811 for (var _i = 2; _i < arguments.length; _i++) {
\r
812 args[_i - 2] = arguments[_i];
\r
814 var result = { title: title, command: command };
\r
815 if (Is.defined(args) && args.length > 0) {
\r
816 result.arguments = args;
\r
820 Command.create = create;
\r
822 * Checks whether the given literal conforms to the [Command](#Command) interface.
\r
824 function is(value) {
\r
825 var candidate = value;
\r
826 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
\r
829 })(Command || (Command = {}));
\r
831 * The TextEdit namespace provides helper function to create replace,
\r
832 * insert and delete edits more easily.
\r
835 (function (TextEdit) {
\r
837 * Creates a replace text edit.
\r
838 * @param range The range of text to be replaced.
\r
839 * @param newText The new text.
\r
841 function replace(range, newText) {
\r
842 return { range: range, newText: newText };
\r
844 TextEdit.replace = replace;
\r
846 * Creates a insert text edit.
\r
847 * @param position The position to insert the text at.
\r
848 * @param newText The text to be inserted.
\r
850 function insert(position, newText) {
\r
851 return { range: { start: position, end: position }, newText: newText };
\r
853 TextEdit.insert = insert;
\r
855 * Creates a delete text edit.
\r
856 * @param range The range of text to be deleted.
\r
858 function del(range) {
\r
859 return { range: range, newText: '' };
\r
861 TextEdit.del = del;
\r
862 function is(value) {
\r
863 var candidate = value;
\r
864 return Is.objectLiteral(candidate)
\r
865 && Is.string(candidate.newText)
\r
866 && Range.is(candidate.range);
\r
869 })(TextEdit || (TextEdit = {}));
\r
871 * The TextDocumentEdit namespace provides helper function to create
\r
872 * an edit that manipulates a text document.
\r
874 var TextDocumentEdit;
\r
875 (function (TextDocumentEdit) {
\r
877 * Creates a new `TextDocumentEdit`
\r
879 function create(textDocument, edits) {
\r
880 return { textDocument: textDocument, edits: edits };
\r
882 TextDocumentEdit.create = create;
\r
883 function is(value) {
\r
884 var candidate = value;
\r
885 return Is.defined(candidate)
\r
886 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
\r
887 && Array.isArray(candidate.edits);
\r
889 TextDocumentEdit.is = is;
\r
890 })(TextDocumentEdit || (TextDocumentEdit = {}));
\r
892 (function (CreateFile) {
\r
893 function create(uri, options) {
\r
898 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
899 result.options = options;
\r
903 CreateFile.create = create;
\r
904 function is(value) {
\r
905 var candidate = value;
\r
906 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
\r
907 (candidate.options === void 0 ||
\r
908 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
910 CreateFile.is = is;
\r
911 })(CreateFile || (CreateFile = {}));
\r
913 (function (RenameFile) {
\r
914 function create(oldUri, newUri, options) {
\r
920 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
921 result.options = options;
\r
925 RenameFile.create = create;
\r
926 function is(value) {
\r
927 var candidate = value;
\r
928 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
\r
929 (candidate.options === void 0 ||
\r
930 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
932 RenameFile.is = is;
\r
933 })(RenameFile || (RenameFile = {}));
\r
935 (function (DeleteFile) {
\r
936 function create(uri, options) {
\r
941 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
\r
942 result.options = options;
\r
946 DeleteFile.create = create;
\r
947 function is(value) {
\r
948 var candidate = value;
\r
949 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
\r
950 (candidate.options === void 0 ||
\r
951 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
\r
953 DeleteFile.is = is;
\r
954 })(DeleteFile || (DeleteFile = {}));
\r
956 (function (WorkspaceEdit) {
\r
957 function is(value) {
\r
958 var candidate = value;
\r
959 return candidate &&
\r
960 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
\r
961 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
\r
962 if (Is.string(change.kind)) {
\r
963 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
\r
966 return TextDocumentEdit.is(change);
\r
970 WorkspaceEdit.is = is;
\r
971 })(WorkspaceEdit || (WorkspaceEdit = {}));
\r
972 var TextEditChangeImpl = /** @class */ (function () {
\r
973 function TextEditChangeImpl(edits) {
\r
974 this.edits = edits;
\r
976 TextEditChangeImpl.prototype.insert = function (position, newText) {
\r
977 this.edits.push(TextEdit.insert(position, newText));
\r
979 TextEditChangeImpl.prototype.replace = function (range, newText) {
\r
980 this.edits.push(TextEdit.replace(range, newText));
\r
982 TextEditChangeImpl.prototype.delete = function (range) {
\r
983 this.edits.push(TextEdit.del(range));
\r
985 TextEditChangeImpl.prototype.add = function (edit) {
\r
986 this.edits.push(edit);
\r
988 TextEditChangeImpl.prototype.all = function () {
\r
991 TextEditChangeImpl.prototype.clear = function () {
\r
992 this.edits.splice(0, this.edits.length);
\r
994 return TextEditChangeImpl;
\r
997 * A workspace change helps constructing changes to a workspace.
\r
999 var WorkspaceChange = /** @class */ (function () {
\r
1000 function WorkspaceChange(workspaceEdit) {
\r
1002 this._textEditChanges = Object.create(null);
\r
1003 if (workspaceEdit) {
\r
1004 this._workspaceEdit = workspaceEdit;
\r
1005 if (workspaceEdit.documentChanges) {
\r
1006 workspaceEdit.documentChanges.forEach(function (change) {
\r
1007 if (TextDocumentEdit.is(change)) {
\r
1008 var textEditChange = new TextEditChangeImpl(change.edits);
\r
1009 _this._textEditChanges[change.textDocument.uri] = textEditChange;
\r
1013 else if (workspaceEdit.changes) {
\r
1014 Object.keys(workspaceEdit.changes).forEach(function (key) {
\r
1015 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
\r
1016 _this._textEditChanges[key] = textEditChange;
\r
1021 Object.defineProperty(WorkspaceChange.prototype, "edit", {
\r
1023 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
\r
1024 * use to be returned from a workspace edit operation like rename.
\r
1026 get: function () {
\r
1027 return this._workspaceEdit;
\r
1030 configurable: true
\r
1032 WorkspaceChange.prototype.getTextEditChange = function (key) {
\r
1033 if (VersionedTextDocumentIdentifier.is(key)) {
\r
1034 if (!this._workspaceEdit) {
\r
1035 this._workspaceEdit = {
\r
1036 documentChanges: []
\r
1039 if (!this._workspaceEdit.documentChanges) {
\r
1040 throw new Error('Workspace edit is not configured for document changes.');
\r
1042 var textDocument = key;
\r
1043 var result = this._textEditChanges[textDocument.uri];
\r
1046 var textDocumentEdit = {
\r
1047 textDocument: textDocument,
\r
1050 this._workspaceEdit.documentChanges.push(textDocumentEdit);
\r
1051 result = new TextEditChangeImpl(edits);
\r
1052 this._textEditChanges[textDocument.uri] = result;
\r
1057 if (!this._workspaceEdit) {
\r
1058 this._workspaceEdit = {
\r
1059 changes: Object.create(null)
\r
1062 if (!this._workspaceEdit.changes) {
\r
1063 throw new Error('Workspace edit is not configured for normal text edit changes.');
\r
1065 var result = this._textEditChanges[key];
\r
1068 this._workspaceEdit.changes[key] = edits;
\r
1069 result = new TextEditChangeImpl(edits);
\r
1070 this._textEditChanges[key] = result;
\r
1075 WorkspaceChange.prototype.createFile = function (uri, options) {
\r
1076 this.checkDocumentChanges();
\r
1077 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
\r
1079 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
\r
1080 this.checkDocumentChanges();
\r
1081 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
\r
1083 WorkspaceChange.prototype.deleteFile = function (uri, options) {
\r
1084 this.checkDocumentChanges();
\r
1085 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
\r
1087 WorkspaceChange.prototype.checkDocumentChanges = function () {
\r
1088 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
\r
1089 throw new Error('Workspace edit is not configured for document changes.');
\r
1092 return WorkspaceChange;
\r
1096 * The TextDocumentIdentifier namespace provides helper functions to work with
\r
1097 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
\r
1099 var TextDocumentIdentifier;
\r
1100 (function (TextDocumentIdentifier) {
\r
1102 * Creates a new TextDocumentIdentifier literal.
\r
1103 * @param uri The document's uri.
\r
1105 function create(uri) {
\r
1106 return { uri: uri };
\r
1108 TextDocumentIdentifier.create = create;
\r
1110 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
\r
1112 function is(value) {
\r
1113 var candidate = value;
\r
1114 return Is.defined(candidate) && Is.string(candidate.uri);
\r
1116 TextDocumentIdentifier.is = is;
\r
1117 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
\r
1119 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
\r
1120 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
\r
1122 var VersionedTextDocumentIdentifier;
\r
1123 (function (VersionedTextDocumentIdentifier) {
\r
1125 * Creates a new VersionedTextDocumentIdentifier literal.
\r
1126 * @param uri The document's uri.
\r
1127 * @param uri The document's text.
\r
1129 function create(uri, version) {
\r
1130 return { uri: uri, version: version };
\r
1132 VersionedTextDocumentIdentifier.create = create;
\r
1134 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
\r
1136 function is(value) {
\r
1137 var candidate = value;
\r
1138 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
\r
1140 VersionedTextDocumentIdentifier.is = is;
\r
1141 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
\r
1143 * The TextDocumentItem namespace provides helper functions to work with
\r
1144 * [TextDocumentItem](#TextDocumentItem) literals.
\r
1146 var TextDocumentItem;
\r
1147 (function (TextDocumentItem) {
\r
1149 * Creates a new TextDocumentItem literal.
\r
1150 * @param uri The document's uri.
\r
1151 * @param languageId The document's language identifier.
\r
1152 * @param version The document's version number.
\r
1153 * @param text The document's text.
\r
1155 function create(uri, languageId, version, text) {
\r
1156 return { uri: uri, languageId: languageId, version: version, text: text };
\r
1158 TextDocumentItem.create = create;
\r
1160 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
\r
1162 function is(value) {
\r
1163 var candidate = value;
\r
1164 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
\r
1166 TextDocumentItem.is = is;
\r
1167 })(TextDocumentItem || (TextDocumentItem = {}));
\r
1169 * Describes the content type that a client supports in various
\r
1170 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
\r
1172 * Please note that `MarkupKinds` must not start with a `$`. This kinds
\r
1173 * are reserved for internal usage.
\r
1176 (function (MarkupKind) {
\r
1178 * Plain text is supported as a content format
\r
1180 MarkupKind.PlainText = 'plaintext';
\r
1182 * Markdown is supported as a content format
\r
1184 MarkupKind.Markdown = 'markdown';
\r
1185 })(MarkupKind || (MarkupKind = {}));
\r
1186 (function (MarkupKind) {
\r
1188 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
\r
1190 function is(value) {
\r
1191 var candidate = value;
\r
1192 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
\r
1194 MarkupKind.is = is;
\r
1195 })(MarkupKind || (MarkupKind = {}));
\r
1196 var MarkupContent;
\r
1197 (function (MarkupContent) {
\r
1199 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
\r
1201 function is(value) {
\r
1202 var candidate = value;
\r
1203 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
\r
1205 MarkupContent.is = is;
\r
1206 })(MarkupContent || (MarkupContent = {}));
\r
1208 * The kind of a completion entry.
\r
1210 var CompletionItemKind;
\r
1211 (function (CompletionItemKind) {
\r
1212 CompletionItemKind.Text = 1;
\r
1213 CompletionItemKind.Method = 2;
\r
1214 CompletionItemKind.Function = 3;
\r
1215 CompletionItemKind.Constructor = 4;
\r
1216 CompletionItemKind.Field = 5;
\r
1217 CompletionItemKind.Variable = 6;
\r
1218 CompletionItemKind.Class = 7;
\r
1219 CompletionItemKind.Interface = 8;
\r
1220 CompletionItemKind.Module = 9;
\r
1221 CompletionItemKind.Property = 10;
\r
1222 CompletionItemKind.Unit = 11;
\r
1223 CompletionItemKind.Value = 12;
\r
1224 CompletionItemKind.Enum = 13;
\r
1225 CompletionItemKind.Keyword = 14;
\r
1226 CompletionItemKind.Snippet = 15;
\r
1227 CompletionItemKind.Color = 16;
\r
1228 CompletionItemKind.File = 17;
\r
1229 CompletionItemKind.Reference = 18;
\r
1230 CompletionItemKind.Folder = 19;
\r
1231 CompletionItemKind.EnumMember = 20;
\r
1232 CompletionItemKind.Constant = 21;
\r
1233 CompletionItemKind.Struct = 22;
\r
1234 CompletionItemKind.Event = 23;
\r
1235 CompletionItemKind.Operator = 24;
\r
1236 CompletionItemKind.TypeParameter = 25;
\r
1237 })(CompletionItemKind || (CompletionItemKind = {}));
\r
1239 * Defines whether the insert text in a completion item should be interpreted as
\r
1240 * plain text or a snippet.
\r
1242 var InsertTextFormat;
\r
1243 (function (InsertTextFormat) {
\r
1245 * The primary text to be inserted is treated as a plain string.
\r
1247 InsertTextFormat.PlainText = 1;
\r
1249 * The primary text to be inserted is treated as a snippet.
\r
1251 * A snippet can define tab stops and placeholders with `$1`, `$2`
\r
1252 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
\r
1253 * the end of the snippet. Placeholders with equal identifiers are linked,
\r
1254 * that is typing in one will update others too.
\r
1256 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
\r
1258 InsertTextFormat.Snippet = 2;
\r
1259 })(InsertTextFormat || (InsertTextFormat = {}));
\r
1261 * Completion item tags are extra annotations that tweak the rendering of a completion
\r
1266 var CompletionItemTag;
\r
1267 (function (CompletionItemTag) {
\r
1269 * Render a completion as obsolete, usually using a strike-out.
\r
1271 CompletionItemTag.Deprecated = 1;
\r
1272 })(CompletionItemTag || (CompletionItemTag = {}));
\r
1274 * The CompletionItem namespace provides functions to deal with
\r
1275 * completion items.
\r
1277 var CompletionItem;
\r
1278 (function (CompletionItem) {
\r
1280 * Create a completion item and seed it with a label.
\r
1281 * @param label The completion item's label
\r
1283 function create(label) {
\r
1284 return { label: label };
\r
1286 CompletionItem.create = create;
\r
1287 })(CompletionItem || (CompletionItem = {}));
\r
1289 * The CompletionList namespace provides functions to deal with
\r
1290 * completion lists.
\r
1292 var CompletionList;
\r
1293 (function (CompletionList) {
\r
1295 * Creates a new completion list.
\r
1297 * @param items The completion items.
\r
1298 * @param isIncomplete The list is not complete.
\r
1300 function create(items, isIncomplete) {
\r
1301 return { items: items ? items : [], isIncomplete: !!isIncomplete };
\r
1303 CompletionList.create = create;
\r
1304 })(CompletionList || (CompletionList = {}));
\r
1306 (function (MarkedString) {
\r
1308 * Creates a marked string from plain text.
\r
1310 * @param plainText The plain text.
\r
1312 function fromPlainText(plainText) {
\r
1313 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
\r
1315 MarkedString.fromPlainText = fromPlainText;
\r
1317 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
\r
1319 function is(value) {
\r
1320 var candidate = value;
\r
1321 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
\r
1323 MarkedString.is = is;
\r
1324 })(MarkedString || (MarkedString = {}));
\r
1326 (function (Hover) {
\r
1328 * Checks whether the given value conforms to the [Hover](#Hover) interface.
\r
1330 function is(value) {
\r
1331 var candidate = value;
\r
1332 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
\r
1333 MarkedString.is(candidate.contents) ||
\r
1334 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
\r
1337 })(Hover || (Hover = {}));
\r
1339 * The ParameterInformation namespace provides helper functions to work with
\r
1340 * [ParameterInformation](#ParameterInformation) literals.
\r
1342 var ParameterInformation;
\r
1343 (function (ParameterInformation) {
\r
1345 * Creates a new parameter information literal.
\r
1347 * @param label A label string.
\r
1348 * @param documentation A doc string.
\r
1350 function create(label, documentation) {
\r
1351 return documentation ? { label: label, documentation: documentation } : { label: label };
\r
1353 ParameterInformation.create = create;
\r
1354 })(ParameterInformation || (ParameterInformation = {}));
\r
1356 * The SignatureInformation namespace provides helper functions to work with
\r
1357 * [SignatureInformation](#SignatureInformation) literals.
\r
1359 var SignatureInformation;
\r
1360 (function (SignatureInformation) {
\r
1361 function create(label, documentation) {
\r
1362 var parameters = [];
\r
1363 for (var _i = 2; _i < arguments.length; _i++) {
\r
1364 parameters[_i - 2] = arguments[_i];
\r
1366 var result = { label: label };
\r
1367 if (Is.defined(documentation)) {
\r
1368 result.documentation = documentation;
\r
1370 if (Is.defined(parameters)) {
\r
1371 result.parameters = parameters;
\r
1374 result.parameters = [];
\r
1378 SignatureInformation.create = create;
\r
1379 })(SignatureInformation || (SignatureInformation = {}));
\r
1381 * A document highlight kind.
\r
1383 var DocumentHighlightKind;
\r
1384 (function (DocumentHighlightKind) {
\r
1386 * A textual occurrence.
\r
1388 DocumentHighlightKind.Text = 1;
\r
1390 * Read-access of a symbol, like reading a variable.
\r
1392 DocumentHighlightKind.Read = 2;
\r
1394 * Write-access of a symbol, like writing to a variable.
\r
1396 DocumentHighlightKind.Write = 3;
\r
1397 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
\r
1399 * DocumentHighlight namespace to provide helper functions to work with
\r
1400 * [DocumentHighlight](#DocumentHighlight) literals.
\r
1402 var DocumentHighlight;
\r
1403 (function (DocumentHighlight) {
\r
1405 * Create a DocumentHighlight object.
\r
1406 * @param range The range the highlight applies to.
\r
1408 function create(range, kind) {
\r
1409 var result = { range: range };
\r
1410 if (Is.number(kind)) {
\r
1411 result.kind = kind;
\r
1415 DocumentHighlight.create = create;
\r
1416 })(DocumentHighlight || (DocumentHighlight = {}));
\r
1421 (function (SymbolKind) {
\r
1422 SymbolKind.File = 1;
\r
1423 SymbolKind.Module = 2;
\r
1424 SymbolKind.Namespace = 3;
\r
1425 SymbolKind.Package = 4;
\r
1426 SymbolKind.Class = 5;
\r
1427 SymbolKind.Method = 6;
\r
1428 SymbolKind.Property = 7;
\r
1429 SymbolKind.Field = 8;
\r
1430 SymbolKind.Constructor = 9;
\r
1431 SymbolKind.Enum = 10;
\r
1432 SymbolKind.Interface = 11;
\r
1433 SymbolKind.Function = 12;
\r
1434 SymbolKind.Variable = 13;
\r
1435 SymbolKind.Constant = 14;
\r
1436 SymbolKind.String = 15;
\r
1437 SymbolKind.Number = 16;
\r
1438 SymbolKind.Boolean = 17;
\r
1439 SymbolKind.Array = 18;
\r
1440 SymbolKind.Object = 19;
\r
1441 SymbolKind.Key = 20;
\r
1442 SymbolKind.Null = 21;
\r
1443 SymbolKind.EnumMember = 22;
\r
1444 SymbolKind.Struct = 23;
\r
1445 SymbolKind.Event = 24;
\r
1446 SymbolKind.Operator = 25;
\r
1447 SymbolKind.TypeParameter = 26;
\r
1448 })(SymbolKind || (SymbolKind = {}));
\r
1450 * Symbol tags are extra annotations that tweak the rendering of a symbol.
\r
1454 (function (SymbolTag) {
\r
1456 * Render a symbol as obsolete, usually using a strike-out.
\r
1458 SymbolTag.Deprecated = 1;
\r
1459 })(SymbolTag || (SymbolTag = {}));
\r
1460 var SymbolInformation;
\r
1461 (function (SymbolInformation) {
\r
1463 * Creates a new symbol information literal.
\r
1465 * @param name The name of the symbol.
\r
1466 * @param kind The kind of the symbol.
\r
1467 * @param range The range of the location of the symbol.
\r
1468 * @param uri The resource of the location of symbol, defaults to the current document.
\r
1469 * @param containerName The name of the symbol containing the symbol.
\r
1471 function create(name, kind, range, uri, containerName) {
\r
1475 location: { uri: uri, range: range }
\r
1477 if (containerName) {
\r
1478 result.containerName = containerName;
\r
1482 SymbolInformation.create = create;
\r
1483 })(SymbolInformation || (SymbolInformation = {}));
\r
1484 var DocumentSymbol;
\r
1485 (function (DocumentSymbol) {
\r
1487 * Creates a new symbol information literal.
\r
1489 * @param name The name of the symbol.
\r
1490 * @param detail The detail of the symbol.
\r
1491 * @param kind The kind of the symbol.
\r
1492 * @param range The range of the symbol.
\r
1493 * @param selectionRange The selectionRange of the symbol.
\r
1494 * @param children Children of the symbol.
\r
1496 function create(name, detail, kind, range, selectionRange, children) {
\r
1502 selectionRange: selectionRange
\r
1504 if (children !== void 0) {
\r
1505 result.children = children;
\r
1509 DocumentSymbol.create = create;
\r
1511 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
\r
1513 function is(value) {
\r
1514 var candidate = value;
\r
1515 return candidate &&
\r
1516 Is.string(candidate.name) && Is.number(candidate.kind) &&
\r
1517 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
\r
1518 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
\r
1519 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
\r
1520 (candidate.children === void 0 || Array.isArray(candidate.children));
\r
1522 DocumentSymbol.is = is;
\r
1523 })(DocumentSymbol || (DocumentSymbol = {}));
\r
1525 * A set of predefined code action kinds
\r
1527 var CodeActionKind;
\r
1528 (function (CodeActionKind) {
\r
1532 CodeActionKind.Empty = '';
\r
1534 * Base kind for quickfix actions: 'quickfix'
\r
1536 CodeActionKind.QuickFix = 'quickfix';
\r
1538 * Base kind for refactoring actions: 'refactor'
\r
1540 CodeActionKind.Refactor = 'refactor';
\r
1542 * Base kind for refactoring extraction actions: 'refactor.extract'
\r
1544 * Example extract actions:
\r
1546 * - Extract method
\r
1547 * - Extract function
\r
1548 * - Extract variable
\r
1549 * - Extract interface from class
\r
1552 CodeActionKind.RefactorExtract = 'refactor.extract';
\r
1554 * Base kind for refactoring inline actions: 'refactor.inline'
\r
1556 * Example inline actions:
\r
1558 * - Inline function
\r
1559 * - Inline variable
\r
1560 * - Inline constant
\r
1563 CodeActionKind.RefactorInline = 'refactor.inline';
\r
1565 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
\r
1567 * Example rewrite actions:
\r
1569 * - Convert JavaScript function to class
\r
1570 * - Add or remove parameter
\r
1571 * - Encapsulate field
\r
1572 * - Make method static
\r
1573 * - Move method to base class
\r
1576 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
\r
1578 * Base kind for source actions: `source`
\r
1580 * Source code actions apply to the entire file.
\r
1582 CodeActionKind.Source = 'source';
\r
1584 * Base kind for an organize imports source action: `source.organizeImports`
\r
1586 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
\r
1588 * Base kind for auto-fix source actions: `source.fixAll`.
\r
1590 * Fix all actions automatically fix errors that have a clear fix that do not require user input.
\r
1591 * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
\r
1595 CodeActionKind.SourceFixAll = 'source.fixAll';
\r
1596 })(CodeActionKind || (CodeActionKind = {}));
\r
1598 * The CodeActionContext namespace provides helper functions to work with
\r
1599 * [CodeActionContext](#CodeActionContext) literals.
\r
1601 var CodeActionContext;
\r
1602 (function (CodeActionContext) {
\r
1604 * Creates a new CodeActionContext literal.
\r
1606 function create(diagnostics, only) {
\r
1607 var result = { diagnostics: diagnostics };
\r
1608 if (only !== void 0 && only !== null) {
\r
1609 result.only = only;
\r
1613 CodeActionContext.create = create;
\r
1615 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
\r
1617 function is(value) {
\r
1618 var candidate = value;
\r
1619 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
\r
1621 CodeActionContext.is = is;
\r
1622 })(CodeActionContext || (CodeActionContext = {}));
\r
1624 (function (CodeAction) {
\r
1625 function create(title, commandOrEdit, kind) {
\r
1626 var result = { title: title };
\r
1627 if (Command.is(commandOrEdit)) {
\r
1628 result.command = commandOrEdit;
\r
1631 result.edit = commandOrEdit;
\r
1633 if (kind !== void 0) {
\r
1634 result.kind = kind;
\r
1638 CodeAction.create = create;
\r
1639 function is(value) {
\r
1640 var candidate = value;
\r
1641 return candidate && Is.string(candidate.title) &&
\r
1642 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
\r
1643 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
\r
1644 (candidate.edit !== void 0 || candidate.command !== void 0) &&
\r
1645 (candidate.command === void 0 || Command.is(candidate.command)) &&
\r
1646 (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
\r
1647 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
\r
1649 CodeAction.is = is;
\r
1650 })(CodeAction || (CodeAction = {}));
\r
1652 * The CodeLens namespace provides helper functions to work with
\r
1653 * [CodeLens](#CodeLens) literals.
\r
1656 (function (CodeLens) {
\r
1658 * Creates a new CodeLens literal.
\r
1660 function create(range, data) {
\r
1661 var result = { range: range };
\r
1662 if (Is.defined(data)) {
\r
1663 result.data = data;
\r
1667 CodeLens.create = create;
\r
1669 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
\r
1671 function is(value) {
\r
1672 var candidate = value;
\r
1673 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
\r
1676 })(CodeLens || (CodeLens = {}));
\r
1678 * The FormattingOptions namespace provides helper functions to work with
\r
1679 * [FormattingOptions](#FormattingOptions) literals.
\r
1681 var FormattingOptions;
\r
1682 (function (FormattingOptions) {
\r
1684 * Creates a new FormattingOptions literal.
\r
1686 function create(tabSize, insertSpaces) {
\r
1687 return { tabSize: tabSize, insertSpaces: insertSpaces };
\r
1689 FormattingOptions.create = create;
\r
1691 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
\r
1693 function is(value) {
\r
1694 var candidate = value;
\r
1695 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
\r
1697 FormattingOptions.is = is;
\r
1698 })(FormattingOptions || (FormattingOptions = {}));
\r
1700 * The DocumentLink namespace provides helper functions to work with
\r
1701 * [DocumentLink](#DocumentLink) literals.
\r
1704 (function (DocumentLink) {
\r
1706 * Creates a new DocumentLink literal.
\r
1708 function create(range, target, data) {
\r
1709 return { range: range, target: target, data: data };
\r
1711 DocumentLink.create = create;
\r
1713 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
\r
1715 function is(value) {
\r
1716 var candidate = value;
\r
1717 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
\r
1719 DocumentLink.is = is;
\r
1720 })(DocumentLink || (DocumentLink = {}));
\r
1722 * The SelectionRange namespace provides helper function to work with
\r
1723 * SelectionRange literals.
\r
1725 var SelectionRange;
\r
1726 (function (SelectionRange) {
\r
1728 * Creates a new SelectionRange
\r
1729 * @param range the range.
\r
1730 * @param parent an optional parent.
\r
1732 function create(range, parent) {
\r
1733 return { range: range, parent: parent };
\r
1735 SelectionRange.create = create;
\r
1736 function is(value) {
\r
1737 var candidate = value;
\r
1738 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
\r
1740 SelectionRange.is = is;
\r
1741 })(SelectionRange || (SelectionRange = {}));
\r
1742 var EOL = ['\n', '\r\n', '\r'];
\r
1744 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
\r
1747 (function (TextDocument) {
\r
1749 * Creates a new ITextDocument literal from the given uri and content.
\r
1750 * @param uri The document's uri.
\r
1751 * @param languageId The document's language Id.
\r
1752 * @param content The document's content.
\r
1754 function create(uri, languageId, version, content) {
\r
1755 return new FullTextDocument(uri, languageId, version, content);
\r
1757 TextDocument.create = create;
\r
1759 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
\r
1761 function is(value) {
\r
1762 var candidate = value;
\r
1763 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
\r
1764 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
\r
1766 TextDocument.is = is;
\r
1767 function applyEdits(document, edits) {
\r
1768 var text = document.getText();
\r
1769 var sortedEdits = mergeSort(edits, function (a, b) {
\r
1770 var diff = a.range.start.line - b.range.start.line;
\r
1772 return a.range.start.character - b.range.start.character;
\r
1776 var lastModifiedOffset = text.length;
\r
1777 for (var i = sortedEdits.length - 1; i >= 0; i--) {
\r
1778 var e = sortedEdits[i];
\r
1779 var startOffset = document.offsetAt(e.range.start);
\r
1780 var endOffset = document.offsetAt(e.range.end);
\r
1781 if (endOffset <= lastModifiedOffset) {
\r
1782 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
\r
1785 throw new Error('Overlapping edit');
\r
1787 lastModifiedOffset = startOffset;
\r
1791 TextDocument.applyEdits = applyEdits;
\r
1792 function mergeSort(data, compare) {
\r
1793 if (data.length <= 1) {
\r
1797 var p = (data.length / 2) | 0;
\r
1798 var left = data.slice(0, p);
\r
1799 var right = data.slice(p);
\r
1800 mergeSort(left, compare);
\r
1801 mergeSort(right, compare);
\r
1805 while (leftIdx < left.length && rightIdx < right.length) {
\r
1806 var ret = compare(left[leftIdx], right[rightIdx]);
\r
1808 // smaller_equal -> take left to preserve order
\r
1809 data[i++] = left[leftIdx++];
\r
1812 // greater -> take right
\r
1813 data[i++] = right[rightIdx++];
\r
1816 while (leftIdx < left.length) {
\r
1817 data[i++] = left[leftIdx++];
\r
1819 while (rightIdx < right.length) {
\r
1820 data[i++] = right[rightIdx++];
\r
1824 })(TextDocument || (TextDocument = {}));
\r
1825 var FullTextDocument = /** @class */ (function () {
\r
1826 function FullTextDocument(uri, languageId, version, content) {
\r
1828 this._languageId = languageId;
\r
1829 this._version = version;
\r
1830 this._content = content;
\r
1831 this._lineOffsets = undefined;
\r
1833 Object.defineProperty(FullTextDocument.prototype, "uri", {
\r
1834 get: function () {
\r
1838 configurable: true
\r
1840 Object.defineProperty(FullTextDocument.prototype, "languageId", {
\r
1841 get: function () {
\r
1842 return this._languageId;
\r
1845 configurable: true
\r
1847 Object.defineProperty(FullTextDocument.prototype, "version", {
\r
1848 get: function () {
\r
1849 return this._version;
\r
1852 configurable: true
\r
1854 FullTextDocument.prototype.getText = function (range) {
\r
1856 var start = this.offsetAt(range.start);
\r
1857 var end = this.offsetAt(range.end);
\r
1858 return this._content.substring(start, end);
\r
1860 return this._content;
\r
1862 FullTextDocument.prototype.update = function (event, version) {
\r
1863 this._content = event.text;
\r
1864 this._version = version;
\r
1865 this._lineOffsets = undefined;
\r
1867 FullTextDocument.prototype.getLineOffsets = function () {
\r
1868 if (this._lineOffsets === undefined) {
\r
1869 var lineOffsets = [];
\r
1870 var text = this._content;
\r
1871 var isLineStart = true;
\r
1872 for (var i = 0; i < text.length; i++) {
\r
1873 if (isLineStart) {
\r
1874 lineOffsets.push(i);
\r
1875 isLineStart = false;
\r
1877 var ch = text.charAt(i);
\r
1878 isLineStart = (ch === '\r' || ch === '\n');
\r
1879 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
\r
1883 if (isLineStart && text.length > 0) {
\r
1884 lineOffsets.push(text.length);
\r
1886 this._lineOffsets = lineOffsets;
\r
1888 return this._lineOffsets;
\r
1890 FullTextDocument.prototype.positionAt = function (offset) {
\r
1891 offset = Math.max(Math.min(offset, this._content.length), 0);
\r
1892 var lineOffsets = this.getLineOffsets();
\r
1893 var low = 0, high = lineOffsets.length;
\r
1895 return Position.create(0, offset);
\r
1897 while (low < high) {
\r
1898 var mid = Math.floor((low + high) / 2);
\r
1899 if (lineOffsets[mid] > offset) {
\r
1906 // low is the least x for which the line offset is larger than the current offset
\r
1907 // or array.length if no line offset is larger than the current offset
\r
1908 var line = low - 1;
\r
1909 return Position.create(line, offset - lineOffsets[line]);
\r
1911 FullTextDocument.prototype.offsetAt = function (position) {
\r
1912 var lineOffsets = this.getLineOffsets();
\r
1913 if (position.line >= lineOffsets.length) {
\r
1914 return this._content.length;
\r
1916 else if (position.line < 0) {
\r
1919 var lineOffset = lineOffsets[position.line];
\r
1920 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
\r
1921 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
\r
1923 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
\r
1924 get: function () {
\r
1925 return this.getLineOffsets().length;
\r
1928 configurable: true
\r
1930 return FullTextDocument;
\r
1934 var toString = Object.prototype.toString;
\r
1935 function defined(value) {
\r
1936 return typeof value !== 'undefined';
\r
1938 Is.defined = defined;
\r
1939 function undefined(value) {
\r
1940 return typeof value === 'undefined';
\r
1942 Is.undefined = undefined;
\r
1943 function boolean(value) {
\r
1944 return value === true || value === false;
\r
1946 Is.boolean = boolean;
\r
1947 function string(value) {
\r
1948 return toString.call(value) === '[object String]';
\r
1950 Is.string = string;
\r
1951 function number(value) {
\r
1952 return toString.call(value) === '[object Number]';
\r
1954 Is.number = number;
\r
1955 function func(value) {
\r
1956 return toString.call(value) === '[object Function]';
\r
1959 function objectLiteral(value) {
\r
1960 // Strictly speaking class instances pass this check as well. Since the LSP
\r
1961 // doesn't use classes we ignore this for now. If we do we need to add something
\r
1962 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
1963 return value !== null && typeof value === 'object';
\r
1965 Is.objectLiteral = objectLiteral;
\r
1966 function typedArray(value, check) {
\r
1967 return Array.isArray(value) && value.every(check);
\r
1969 Is.typedArray = typedArray;
\r
1970 })(Is || (Is = {}));
\r
1975 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1978 Object.defineProperty(exports, "__esModule", ({ value: true }));
1979 const coc_nvim_1 = __webpack_require__(1);
1980 const vscode_languageserver_protocol_1 = __webpack_require__(8);
1981 const util_1 = __webpack_require__(35);
1982 const codesMap = new Map();
1983 codesMap.set(1, 'invalid snippet line, trigger requried.');
1984 codesMap.set(2, 'invalid snippet option, option "$1" not supported.');
1985 codesMap.set(3, 'invalid python expression, $1');
1986 codesMap.set(4, 'invalid code interpolation, #! not supported.');
1987 const validOptions = ['b', 'i', 'w', 'r', 'e', 'A'];
1988 class LanguageProvider {
1989 constructor(channel, trace = 'error') {
1990 this.channel = channel;
1992 this.disposables = [];
1993 this.collection = coc_nvim_1.languages.createDiagnosticCollection('snippets');
1994 for (let doc of coc_nvim_1.workspace.documents) {
1995 if (this.shouldValidate(doc.uri)) {
1996 this.validate(doc.uri, doc.getDocumentContent()).catch(e => {
1997 channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}]: ${e.message}`);
2001 coc_nvim_1.workspace.onDidOpenTextDocument(async (textDocument) => {
2002 let doc = coc_nvim_1.workspace.getDocument(textDocument.uri);
2003 if (!this.shouldValidate(doc.uri))
2005 await this.validate(doc.uri, doc.getDocumentContent());
2006 }, null, this.disposables);
2007 coc_nvim_1.workspace.onDidChangeTextDocument(async (ev) => {
2008 let doc = coc_nvim_1.workspace.getDocument(ev.textDocument.uri);
2009 if (!doc || !this.shouldValidate(doc.uri))
2011 await this.validate(doc.uri, doc.getDocumentContent());
2012 }, null, this.disposables);
2013 coc_nvim_1.workspace.onDidCloseTextDocument(e => {
2014 this.collection.delete(e.uri);
2015 }, null, this.disposables);
2017 shouldValidate(uri) {
2018 return uri.endsWith('.snippets');
2020 async validate(uri, content) {
2021 let lines = content.split('\n');
2022 let diagnostics = [];
2024 for (let line of lines) {
2025 if (/^snippet\s*$/.test(line)) {
2026 let range = vscode_languageserver_protocol_1.Range.create(curr, 0, curr, line.length);
2027 diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, codesMap.get(1), vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 1));
2030 if (line.startsWith('snippet ')) {
2031 let content = util_1.headTail(line)[1];
2032 let ms = content.match(/^(.+?)(?:\s+(?:"(.*?)")?(?:\s+"(.*?)")?(?:\s+(\w+))?)?$/);
2034 if (prefix.length > 2 && prefix[0] == prefix[prefix.length - 1] && !/\w/.test(prefix[0])) {
2035 prefix = prefix.slice(1, prefix.length - 1);
2037 let option = ms[4] || '';
2038 let isExpression = option.indexOf('r') !== -1;
2039 let startCharacter = line.length - option.length;
2040 for (let ch of option) {
2041 if (validOptions.indexOf(ch) == -1) {
2042 let range = vscode_languageserver_protocol_1.Range.create(curr, startCharacter, curr, startCharacter + 1);
2043 let message = codesMap.get(2).replace('$1', ch);
2044 diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 2));
2046 startCharacter = startCharacter + 1;
2050 util_1.convertRegex(prefix);
2053 let start = line.indexOf(prefix);
2054 let range = vscode_languageserver_protocol_1.Range.create(curr, start, curr, start + prefix.length);
2055 let message = codesMap.get(3).replace('$1', e.message);
2056 diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 3));
2061 let idx = line.indexOf('`#!');
2063 let range = vscode_languageserver_protocol_1.Range.create(curr, idx, curr, idx + 3);
2064 let message = codesMap.get(4);
2065 diagnostics.push(vscode_languageserver_protocol_1.Diagnostic.create(range, message, vscode_languageserver_protocol_1.DiagnosticSeverity.Error, 4));
2070 if (this.trace == 'verbose') {
2071 this.channel.appendLine(`[Debug ${(new Date()).toLocaleTimeString()}] diagnostics of ${uri} -> ${JSON.stringify(diagnostics)}`);
2073 this.collection.set(uri, diagnostics);
2075 provideCompletionItems(_document, position, _token, context) {
2076 let { input, col } = context.option;
2077 if (context.triggerCharacter == '$') {
2080 kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
2081 // tslint:disable-next-line: no-invalid-template-strings
2082 detail: '${VISUAL}',
2083 insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet,
2085 range: vscode_languageserver_protocol_1.Range.create(position.line, position.character - 1, position.line, position.character),
2086 // tslint:disable-next-line: no-invalid-template-strings
2087 newText: '\\${VISUAL${1::default}\\}'
2091 if (col == 0 && 'snippet'.startsWith(input)) {
2094 kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
2095 detail: 'Snippet definition',
2096 insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet,
2097 // tslint:disable-next-line: no-invalid-template-strings
2098 insertText: 'snippet ${1:Tab_trigger} "${2:Description}" ${3:b}\n$0\nendsnippet'
2103 async resolveCompletionItem(item) {
2104 // tslint:disable-next-line: deprecation
2105 let text = item.insertText || item.textEdit.newText;
2106 // tslint:disable-next-line: deprecation
2107 let snip = await Promise.resolve(coc_nvim_1.snippetManager.resolveSnippet(text));
2108 item.documentation = {
2110 value: util_1.markdownBlock(snip.toString(), 'snippets')
2115 exports.default = LanguageProvider;
2120 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2122 /* --------------------------------------------------------------------------------------------
\r
2123 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2124 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2125 * ------------------------------------------------------------------------------------------ */
\r
2127 function __export(m) {
\r
2128 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
2130 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
2131 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
2132 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
\r
2133 exports.ResponseError = vscode_jsonrpc_1.ResponseError;
\r
2134 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
\r
2135 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
\r
2136 exports.Disposable = vscode_jsonrpc_1.Disposable;
\r
2137 exports.Event = vscode_jsonrpc_1.Event;
\r
2138 exports.Emitter = vscode_jsonrpc_1.Emitter;
\r
2139 exports.Trace = vscode_jsonrpc_1.Trace;
\r
2140 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
\r
2141 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
\r
2142 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
\r
2143 exports.RequestType = vscode_jsonrpc_1.RequestType;
\r
2144 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
\r
2145 exports.NotificationType = vscode_jsonrpc_1.NotificationType;
\r
2146 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
\r
2147 exports.MessageReader = vscode_jsonrpc_1.MessageReader;
\r
2148 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
\r
2149 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
\r
2150 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
\r
2151 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
\r
2152 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
\r
2153 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
\r
2154 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
\r
2155 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
\r
2156 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
\r
2157 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
\r
2158 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
\r
2159 exports.ProgressType = vscode_jsonrpc_1.ProgressType;
\r
2160 __export(__webpack_require__(6));
\r
2161 __export(__webpack_require__(21));
\r
2162 const callHierarchy = __webpack_require__(33);
\r
2163 const st = __webpack_require__(34);
\r
2165 (function (Proposed) {
\r
2166 let CallHierarchyPrepareRequest;
\r
2167 (function (CallHierarchyPrepareRequest) {
\r
2168 CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
\r
2169 CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
\r
2170 })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
\r
2171 let CallHierarchyIncomingCallsRequest;
\r
2172 (function (CallHierarchyIncomingCallsRequest) {
\r
2173 CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
\r
2174 CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
\r
2175 })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
\r
2176 let CallHierarchyOutgoingCallsRequest;
\r
2177 (function (CallHierarchyOutgoingCallsRequest) {
\r
2178 CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
\r
2179 CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
\r
2180 })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
\r
2181 Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
\r
2182 Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
\r
2183 Proposed.SemanticTokens = st.SemanticTokens;
\r
2184 let SemanticTokensRequest;
\r
2185 (function (SemanticTokensRequest) {
\r
2186 SemanticTokensRequest.method = st.SemanticTokensRequest.method;
\r
2187 SemanticTokensRequest.type = st.SemanticTokensRequest.type;
\r
2188 })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
\r
2189 let SemanticTokensEditsRequest;
\r
2190 (function (SemanticTokensEditsRequest) {
\r
2191 SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
\r
2192 SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
\r
2193 })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
\r
2194 let SemanticTokensRangeRequest;
\r
2195 (function (SemanticTokensRangeRequest) {
\r
2196 SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
\r
2197 SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
\r
2198 })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
\r
2199 })(Proposed = exports.Proposed || (exports.Proposed = {}));
\r
2200 function createProtocolConnection(reader, writer, logger, strategy) {
\r
2201 return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
\r
2203 exports.createProtocolConnection = createProtocolConnection;
\r
2208 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2210 /* --------------------------------------------------------------------------------------------
\r
2211 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2212 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2213 * ------------------------------------------------------------------------------------------ */
\r
2214 /// <reference path="../typings/thenable.d.ts" />
\r
2216 function __export(m) {
\r
2217 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
2219 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
2220 const Is = __webpack_require__(10);
\r
2221 const messages_1 = __webpack_require__(11);
\r
2222 exports.RequestType = messages_1.RequestType;
\r
2223 exports.RequestType0 = messages_1.RequestType0;
\r
2224 exports.RequestType1 = messages_1.RequestType1;
\r
2225 exports.RequestType2 = messages_1.RequestType2;
\r
2226 exports.RequestType3 = messages_1.RequestType3;
\r
2227 exports.RequestType4 = messages_1.RequestType4;
\r
2228 exports.RequestType5 = messages_1.RequestType5;
\r
2229 exports.RequestType6 = messages_1.RequestType6;
\r
2230 exports.RequestType7 = messages_1.RequestType7;
\r
2231 exports.RequestType8 = messages_1.RequestType8;
\r
2232 exports.RequestType9 = messages_1.RequestType9;
\r
2233 exports.ResponseError = messages_1.ResponseError;
\r
2234 exports.ErrorCodes = messages_1.ErrorCodes;
\r
2235 exports.NotificationType = messages_1.NotificationType;
\r
2236 exports.NotificationType0 = messages_1.NotificationType0;
\r
2237 exports.NotificationType1 = messages_1.NotificationType1;
\r
2238 exports.NotificationType2 = messages_1.NotificationType2;
\r
2239 exports.NotificationType3 = messages_1.NotificationType3;
\r
2240 exports.NotificationType4 = messages_1.NotificationType4;
\r
2241 exports.NotificationType5 = messages_1.NotificationType5;
\r
2242 exports.NotificationType6 = messages_1.NotificationType6;
\r
2243 exports.NotificationType7 = messages_1.NotificationType7;
\r
2244 exports.NotificationType8 = messages_1.NotificationType8;
\r
2245 exports.NotificationType9 = messages_1.NotificationType9;
\r
2246 const messageReader_1 = __webpack_require__(12);
\r
2247 exports.MessageReader = messageReader_1.MessageReader;
\r
2248 exports.StreamMessageReader = messageReader_1.StreamMessageReader;
\r
2249 exports.IPCMessageReader = messageReader_1.IPCMessageReader;
\r
2250 exports.SocketMessageReader = messageReader_1.SocketMessageReader;
\r
2251 const messageWriter_1 = __webpack_require__(14);
\r
2252 exports.MessageWriter = messageWriter_1.MessageWriter;
\r
2253 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
\r
2254 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
\r
2255 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
\r
2256 const events_1 = __webpack_require__(13);
\r
2257 exports.Disposable = events_1.Disposable;
\r
2258 exports.Event = events_1.Event;
\r
2259 exports.Emitter = events_1.Emitter;
\r
2260 const cancellation_1 = __webpack_require__(15);
\r
2261 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
\r
2262 exports.CancellationToken = cancellation_1.CancellationToken;
\r
2263 const linkedMap_1 = __webpack_require__(16);
\r
2264 __export(__webpack_require__(17));
\r
2265 __export(__webpack_require__(20));
\r
2266 var CancelNotification;
\r
2267 (function (CancelNotification) {
\r
2268 CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
\r
2269 })(CancelNotification || (CancelNotification = {}));
\r
2270 var ProgressNotification;
\r
2271 (function (ProgressNotification) {
\r
2272 ProgressNotification.type = new messages_1.NotificationType('$/progress');
\r
2273 })(ProgressNotification || (ProgressNotification = {}));
\r
2274 class ProgressType {
\r
2278 exports.ProgressType = ProgressType;
\r
2279 exports.NullLogger = Object.freeze({
\r
2286 (function (Trace) {
\r
2287 Trace[Trace["Off"] = 0] = "Off";
\r
2288 Trace[Trace["Messages"] = 1] = "Messages";
\r
2289 Trace[Trace["Verbose"] = 2] = "Verbose";
\r
2290 })(Trace = exports.Trace || (exports.Trace = {}));
\r
2291 (function (Trace) {
\r
2292 function fromString(value) {
\r
2293 if (!Is.string(value)) {
\r
2296 value = value.toLowerCase();
\r
2301 return Trace.Messages;
\r
2303 return Trace.Verbose;
\r
2308 Trace.fromString = fromString;
\r
2309 function toString(value) {
\r
2313 case Trace.Messages:
\r
2314 return 'messages';
\r
2315 case Trace.Verbose:
\r
2321 Trace.toString = toString;
\r
2322 })(Trace = exports.Trace || (exports.Trace = {}));
\r
2324 (function (TraceFormat) {
\r
2325 TraceFormat["Text"] = "text";
\r
2326 TraceFormat["JSON"] = "json";
\r
2327 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
2328 (function (TraceFormat) {
\r
2329 function fromString(value) {
\r
2330 value = value.toLowerCase();
\r
2331 if (value === 'json') {
\r
2332 return TraceFormat.JSON;
\r
2335 return TraceFormat.Text;
\r
2338 TraceFormat.fromString = fromString;
\r
2339 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
2340 var SetTraceNotification;
\r
2341 (function (SetTraceNotification) {
\r
2342 SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
\r
2343 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
\r
2344 var LogTraceNotification;
\r
2345 (function (LogTraceNotification) {
\r
2346 LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
\r
2347 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
\r
2348 var ConnectionErrors;
\r
2349 (function (ConnectionErrors) {
\r
2351 * The connection is closed.
\r
2353 ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
\r
2355 * The connection got disposed.
\r
2357 ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
\r
2359 * The connection is already in listening mode.
\r
2361 ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
\r
2362 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
\r
2363 class ConnectionError extends Error {
\r
2364 constructor(code, message) {
\r
2367 Object.setPrototypeOf(this, ConnectionError.prototype);
\r
2370 exports.ConnectionError = ConnectionError;
\r
2371 var ConnectionStrategy;
\r
2372 (function (ConnectionStrategy) {
\r
2373 function is(value) {
\r
2374 let candidate = value;
\r
2375 return candidate && Is.func(candidate.cancelUndispatched);
\r
2377 ConnectionStrategy.is = is;
\r
2378 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
\r
2379 var ConnectionState;
\r
2380 (function (ConnectionState) {
\r
2381 ConnectionState[ConnectionState["New"] = 1] = "New";
\r
2382 ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
\r
2383 ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
\r
2384 ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
\r
2385 })(ConnectionState || (ConnectionState = {}));
\r
2386 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
\r
2387 let sequenceNumber = 0;
\r
2388 let notificationSquenceNumber = 0;
\r
2389 let unknownResponseSquenceNumber = 0;
\r
2390 const version = '2.0';
\r
2391 let starRequestHandler = undefined;
\r
2392 let requestHandlers = Object.create(null);
\r
2393 let starNotificationHandler = undefined;
\r
2394 let notificationHandlers = Object.create(null);
\r
2395 let progressHandlers = new Map();
\r
2397 let messageQueue = new linkedMap_1.LinkedMap();
\r
2398 let responsePromises = Object.create(null);
\r
2399 let requestTokens = Object.create(null);
\r
2400 let trace = Trace.Off;
\r
2401 let traceFormat = TraceFormat.Text;
\r
2403 let state = ConnectionState.New;
\r
2404 let errorEmitter = new events_1.Emitter();
\r
2405 let closeEmitter = new events_1.Emitter();
\r
2406 let unhandledNotificationEmitter = new events_1.Emitter();
\r
2407 let unhandledProgressEmitter = new events_1.Emitter();
\r
2408 let disposeEmitter = new events_1.Emitter();
\r
2409 function createRequestQueueKey(id) {
\r
2410 return 'req-' + id.toString();
\r
2412 function createResponseQueueKey(id) {
\r
2413 if (id === null) {
\r
2414 return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
\r
2417 return 'res-' + id.toString();
\r
2420 function createNotificationQueueKey() {
\r
2421 return 'not-' + (++notificationSquenceNumber).toString();
\r
2423 function addMessageToQueue(queue, message) {
\r
2424 if (messages_1.isRequestMessage(message)) {
\r
2425 queue.set(createRequestQueueKey(message.id), message);
\r
2427 else if (messages_1.isResponseMessage(message)) {
\r
2428 queue.set(createResponseQueueKey(message.id), message);
\r
2431 queue.set(createNotificationQueueKey(), message);
\r
2434 function cancelUndispatched(_message) {
\r
2437 function isListening() {
\r
2438 return state === ConnectionState.Listening;
\r
2440 function isClosed() {
\r
2441 return state === ConnectionState.Closed;
\r
2443 function isDisposed() {
\r
2444 return state === ConnectionState.Disposed;
\r
2446 function closeHandler() {
\r
2447 if (state === ConnectionState.New || state === ConnectionState.Listening) {
\r
2448 state = ConnectionState.Closed;
\r
2449 closeEmitter.fire(undefined);
\r
2451 // If the connection is disposed don't sent close events.
\r
2453 function readErrorHandler(error) {
\r
2454 errorEmitter.fire([error, undefined, undefined]);
\r
2456 function writeErrorHandler(data) {
\r
2457 errorEmitter.fire(data);
\r
2459 messageReader.onClose(closeHandler);
\r
2460 messageReader.onError(readErrorHandler);
\r
2461 messageWriter.onClose(closeHandler);
\r
2462 messageWriter.onError(writeErrorHandler);
\r
2463 function triggerMessageQueue() {
\r
2464 if (timer || messageQueue.size === 0) {
\r
2467 timer = setImmediate(() => {
\r
2468 timer = undefined;
\r
2469 processMessageQueue();
\r
2472 function processMessageQueue() {
\r
2473 if (messageQueue.size === 0) {
\r
2476 let message = messageQueue.shift();
\r
2478 if (messages_1.isRequestMessage(message)) {
\r
2479 handleRequest(message);
\r
2481 else if (messages_1.isNotificationMessage(message)) {
\r
2482 handleNotification(message);
\r
2484 else if (messages_1.isResponseMessage(message)) {
\r
2485 handleResponse(message);
\r
2488 handleInvalidMessage(message);
\r
2492 triggerMessageQueue();
\r
2495 let callback = (message) => {
\r
2497 // We have received a cancellation message. Check if the message is still in the queue
\r
2498 // and cancel it if allowed to do so.
\r
2499 if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
\r
2500 let key = createRequestQueueKey(message.params.id);
\r
2501 let toCancel = messageQueue.get(key);
\r
2502 if (messages_1.isRequestMessage(toCancel)) {
\r
2503 let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
\r
2504 if (response && (response.error !== void 0 || response.result !== void 0)) {
\r
2505 messageQueue.delete(key);
\r
2506 response.id = toCancel.id;
\r
2507 traceSendingResponse(response, message.method, Date.now());
\r
2508 messageWriter.write(response);
\r
2513 addMessageToQueue(messageQueue, message);
\r
2516 triggerMessageQueue();
\r
2519 function handleRequest(requestMessage) {
\r
2520 if (isDisposed()) {
\r
2521 // we return here silently since we fired an event when the
\r
2522 // connection got disposed.
\r
2525 function reply(resultOrError, method, startTime) {
\r
2528 id: requestMessage.id
\r
2530 if (resultOrError instanceof messages_1.ResponseError) {
\r
2531 message.error = resultOrError.toJson();
\r
2534 message.result = resultOrError === void 0 ? null : resultOrError;
\r
2536 traceSendingResponse(message, method, startTime);
\r
2537 messageWriter.write(message);
\r
2539 function replyError(error, method, startTime) {
\r
2542 id: requestMessage.id,
\r
2543 error: error.toJson()
\r
2545 traceSendingResponse(message, method, startTime);
\r
2546 messageWriter.write(message);
\r
2548 function replySuccess(result, method, startTime) {
\r
2549 // The JSON RPC defines that a response must either have a result or an error
\r
2550 // So we can't treat undefined as a valid response result.
\r
2551 if (result === void 0) {
\r
2556 id: requestMessage.id,
\r
2559 traceSendingResponse(message, method, startTime);
\r
2560 messageWriter.write(message);
\r
2562 traceReceivedRequest(requestMessage);
\r
2563 let element = requestHandlers[requestMessage.method];
\r
2565 let requestHandler;
\r
2567 type = element.type;
\r
2568 requestHandler = element.handler;
\r
2570 let startTime = Date.now();
\r
2571 if (requestHandler || starRequestHandler) {
\r
2572 let cancellationSource = new cancellation_1.CancellationTokenSource();
\r
2573 let tokenKey = String(requestMessage.id);
\r
2574 requestTokens[tokenKey] = cancellationSource;
\r
2576 let handlerResult;
\r
2577 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
2578 handlerResult = requestHandler
\r
2579 ? requestHandler(cancellationSource.token)
\r
2580 : starRequestHandler(requestMessage.method, cancellationSource.token);
\r
2582 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
2583 handlerResult = requestHandler
\r
2584 ? requestHandler(...requestMessage.params, cancellationSource.token)
\r
2585 : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
\r
2588 handlerResult = requestHandler
\r
2589 ? requestHandler(requestMessage.params, cancellationSource.token)
\r
2590 : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
\r
2592 let promise = handlerResult;
\r
2593 if (!handlerResult) {
\r
2594 delete requestTokens[tokenKey];
\r
2595 replySuccess(handlerResult, requestMessage.method, startTime);
\r
2597 else if (promise.then) {
\r
2598 promise.then((resultOrError) => {
\r
2599 delete requestTokens[tokenKey];
\r
2600 reply(resultOrError, requestMessage.method, startTime);
\r
2602 delete requestTokens[tokenKey];
\r
2603 if (error instanceof messages_1.ResponseError) {
\r
2604 replyError(error, requestMessage.method, startTime);
\r
2606 else if (error && Is.string(error.message)) {
\r
2607 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
2610 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
2615 delete requestTokens[tokenKey];
\r
2616 reply(handlerResult, requestMessage.method, startTime);
\r
2620 delete requestTokens[tokenKey];
\r
2621 if (error instanceof messages_1.ResponseError) {
\r
2622 reply(error, requestMessage.method, startTime);
\r
2624 else if (error && Is.string(error.message)) {
\r
2625 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
2628 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
2633 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
\r
2636 function handleResponse(responseMessage) {
\r
2637 if (isDisposed()) {
\r
2638 // See handle request.
\r
2641 if (responseMessage.id === null) {
\r
2642 if (responseMessage.error) {
\r
2643 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
\r
2646 logger.error(`Received response message without id. No further error information provided.`);
\r
2650 let key = String(responseMessage.id);
\r
2651 let responsePromise = responsePromises[key];
\r
2652 traceReceivedResponse(responseMessage, responsePromise);
\r
2653 if (responsePromise) {
\r
2654 delete responsePromises[key];
\r
2656 if (responseMessage.error) {
\r
2657 let error = responseMessage.error;
\r
2658 responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
\r
2660 else if (responseMessage.result !== void 0) {
\r
2661 responsePromise.resolve(responseMessage.result);
\r
2664 throw new Error('Should never happen.');
\r
2668 if (error.message) {
\r
2669 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
\r
2672 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
\r
2678 function handleNotification(message) {
\r
2679 if (isDisposed()) {
\r
2680 // See handle request.
\r
2683 let type = undefined;
\r
2684 let notificationHandler;
\r
2685 if (message.method === CancelNotification.type.method) {
\r
2686 notificationHandler = (params) => {
\r
2687 let id = params.id;
\r
2688 let source = requestTokens[String(id)];
\r
2695 let element = notificationHandlers[message.method];
\r
2697 notificationHandler = element.handler;
\r
2698 type = element.type;
\r
2701 if (notificationHandler || starNotificationHandler) {
\r
2703 traceReceivedNotification(message);
\r
2704 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
2705 notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
\r
2707 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
2708 notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
\r
2711 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
\r
2715 if (error.message) {
\r
2716 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
\r
2719 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
\r
2724 unhandledNotificationEmitter.fire(message);
\r
2727 function handleInvalidMessage(message) {
\r
2729 logger.error('Received empty message.');
\r
2732 logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
\r
2733 // Test whether we find an id to reject the promise
\r
2734 let responseMessage = message;
\r
2735 if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
\r
2736 let key = String(responseMessage.id);
\r
2737 let responseHandler = responsePromises[key];
\r
2738 if (responseHandler) {
\r
2739 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
\r
2743 function traceSendingRequest(message) {
\r
2744 if (trace === Trace.Off || !tracer) {
\r
2747 if (traceFormat === TraceFormat.Text) {
\r
2748 let data = undefined;
\r
2749 if (trace === Trace.Verbose && message.params) {
\r
2750 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
2752 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
\r
2755 logLSPMessage('send-request', message);
\r
2758 function traceSendingNotification(message) {
\r
2759 if (trace === Trace.Off || !tracer) {
\r
2762 if (traceFormat === TraceFormat.Text) {
\r
2763 let data = undefined;
\r
2764 if (trace === Trace.Verbose) {
\r
2765 if (message.params) {
\r
2766 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
2769 data = 'No parameters provided.\n\n';
\r
2772 tracer.log(`Sending notification '${message.method}'.`, data);
\r
2775 logLSPMessage('send-notification', message);
\r
2778 function traceSendingResponse(message, method, startTime) {
\r
2779 if (trace === Trace.Off || !tracer) {
\r
2782 if (traceFormat === TraceFormat.Text) {
\r
2783 let data = undefined;
\r
2784 if (trace === Trace.Verbose) {
\r
2785 if (message.error && message.error.data) {
\r
2786 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
2789 if (message.result) {
\r
2790 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
2792 else if (message.error === void 0) {
\r
2793 data = 'No result returned.\n\n';
\r
2797 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
\r
2800 logLSPMessage('send-response', message);
\r
2803 function traceReceivedRequest(message) {
\r
2804 if (trace === Trace.Off || !tracer) {
\r
2807 if (traceFormat === TraceFormat.Text) {
\r
2808 let data = undefined;
\r
2809 if (trace === Trace.Verbose && message.params) {
\r
2810 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
2812 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
\r
2815 logLSPMessage('receive-request', message);
\r
2818 function traceReceivedNotification(message) {
\r
2819 if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
\r
2822 if (traceFormat === TraceFormat.Text) {
\r
2823 let data = undefined;
\r
2824 if (trace === Trace.Verbose) {
\r
2825 if (message.params) {
\r
2826 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
2829 data = 'No parameters provided.\n\n';
\r
2832 tracer.log(`Received notification '${message.method}'.`, data);
\r
2835 logLSPMessage('receive-notification', message);
\r
2838 function traceReceivedResponse(message, responsePromise) {
\r
2839 if (trace === Trace.Off || !tracer) {
\r
2842 if (traceFormat === TraceFormat.Text) {
\r
2843 let data = undefined;
\r
2844 if (trace === Trace.Verbose) {
\r
2845 if (message.error && message.error.data) {
\r
2846 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
2849 if (message.result) {
\r
2850 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
2852 else if (message.error === void 0) {
\r
2853 data = 'No result returned.\n\n';
\r
2857 if (responsePromise) {
\r
2858 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
\r
2859 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
\r
2862 tracer.log(`Received response ${message.id} without active response promise.`, data);
\r
2866 logLSPMessage('receive-response', message);
\r
2869 function logLSPMessage(type, message) {
\r
2870 if (!tracer || trace === Trace.Off) {
\r
2873 const lspMessage = {
\r
2874 isLSPMessage: true,
\r
2877 timestamp: Date.now()
\r
2879 tracer.log(lspMessage);
\r
2881 function throwIfClosedOrDisposed() {
\r
2883 throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
\r
2885 if (isDisposed()) {
\r
2886 throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
\r
2889 function throwIfListening() {
\r
2890 if (isListening()) {
\r
2891 throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
\r
2894 function throwIfNotListening() {
\r
2895 if (!isListening()) {
\r
2896 throw new Error('Call listen() first.');
\r
2899 function undefinedToNull(param) {
\r
2900 if (param === void 0) {
\r
2907 function computeMessageParams(type, params) {
\r
2909 let numberOfParams = type.numberOfParams;
\r
2910 switch (numberOfParams) {
\r
2915 result = undefinedToNull(params[0]);
\r
2919 for (let i = 0; i < params.length && i < numberOfParams; i++) {
\r
2920 result.push(undefinedToNull(params[i]));
\r
2922 if (params.length < numberOfParams) {
\r
2923 for (let i = params.length; i < numberOfParams; i++) {
\r
2924 result.push(null);
\r
2931 let connection = {
\r
2932 sendNotification: (type, ...params) => {
\r
2933 throwIfClosedOrDisposed();
\r
2935 let messageParams;
\r
2936 if (Is.string(type)) {
\r
2938 switch (params.length) {
\r
2940 messageParams = null;
\r
2943 messageParams = params[0];
\r
2946 messageParams = params;
\r
2951 method = type.method;
\r
2952 messageParams = computeMessageParams(type, params);
\r
2954 let notificationMessage = {
\r
2957 params: messageParams
\r
2959 traceSendingNotification(notificationMessage);
\r
2960 messageWriter.write(notificationMessage);
\r
2962 onNotification: (type, handler) => {
\r
2963 throwIfClosedOrDisposed();
\r
2964 if (Is.func(type)) {
\r
2965 starNotificationHandler = type;
\r
2967 else if (handler) {
\r
2968 if (Is.string(type)) {
\r
2969 notificationHandlers[type] = { type: undefined, handler };
\r
2972 notificationHandlers[type.method] = { type, handler };
\r
2976 onProgress: (_type, token, handler) => {
\r
2977 if (progressHandlers.has(token)) {
\r
2978 throw new Error(`Progress handler for token ${token} already registered`);
\r
2980 progressHandlers.set(token, handler);
\r
2983 progressHandlers.delete(token);
\r
2987 sendProgress: (_type, token, value) => {
\r
2988 connection.sendNotification(ProgressNotification.type, { token, value });
\r
2990 onUnhandledProgress: unhandledProgressEmitter.event,
\r
2991 sendRequest: (type, ...params) => {
\r
2992 throwIfClosedOrDisposed();
\r
2993 throwIfNotListening();
\r
2995 let messageParams;
\r
2996 let token = undefined;
\r
2997 if (Is.string(type)) {
\r
2999 switch (params.length) {
\r
3001 messageParams = null;
\r
3004 // The cancellation token is optional so it can also be undefined.
\r
3005 if (cancellation_1.CancellationToken.is(params[0])) {
\r
3006 messageParams = null;
\r
3007 token = params[0];
\r
3010 messageParams = undefinedToNull(params[0]);
\r
3014 const last = params.length - 1;
\r
3015 if (cancellation_1.CancellationToken.is(params[last])) {
\r
3016 token = params[last];
\r
3017 if (params.length === 2) {
\r
3018 messageParams = undefinedToNull(params[0]);
\r
3021 messageParams = params.slice(0, last).map(value => undefinedToNull(value));
\r
3025 messageParams = params.map(value => undefinedToNull(value));
\r
3031 method = type.method;
\r
3032 messageParams = computeMessageParams(type, params);
\r
3033 let numberOfParams = type.numberOfParams;
\r
3034 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
\r
3036 let id = sequenceNumber++;
\r
3037 let result = new Promise((resolve, reject) => {
\r
3038 let requestMessage = {
\r
3042 params: messageParams
\r
3044 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
\r
3045 traceSendingRequest(requestMessage);
\r
3047 messageWriter.write(requestMessage);
\r
3050 // Writing the message failed. So we need to reject the promise.
\r
3051 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
\r
3052 responsePromise = null;
\r
3054 if (responsePromise) {
\r
3055 responsePromises[String(id)] = responsePromise;
\r
3059 token.onCancellationRequested(() => {
\r
3060 connection.sendNotification(CancelNotification.type, { id });
\r
3065 onRequest: (type, handler) => {
\r
3066 throwIfClosedOrDisposed();
\r
3067 if (Is.func(type)) {
\r
3068 starRequestHandler = type;
\r
3070 else if (handler) {
\r
3071 if (Is.string(type)) {
\r
3072 requestHandlers[type] = { type: undefined, handler };
\r
3075 requestHandlers[type.method] = { type, handler };
\r
3079 trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
\r
3080 let _sendNotification = false;
\r
3081 let _traceFormat = TraceFormat.Text;
\r
3082 if (sendNotificationOrTraceOptions !== void 0) {
\r
3083 if (Is.boolean(sendNotificationOrTraceOptions)) {
\r
3084 _sendNotification = sendNotificationOrTraceOptions;
\r
3087 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
\r
3088 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
\r
3092 traceFormat = _traceFormat;
\r
3093 if (trace === Trace.Off) {
\r
3094 tracer = undefined;
\r
3099 if (_sendNotification && !isClosed() && !isDisposed()) {
\r
3100 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
\r
3103 onError: errorEmitter.event,
\r
3104 onClose: closeEmitter.event,
\r
3105 onUnhandledNotification: unhandledNotificationEmitter.event,
\r
3106 onDispose: disposeEmitter.event,
\r
3108 if (isDisposed()) {
\r
3111 state = ConnectionState.Disposed;
\r
3112 disposeEmitter.fire(undefined);
\r
3113 let error = new Error('Connection got disposed.');
\r
3114 Object.keys(responsePromises).forEach((key) => {
\r
3115 responsePromises[key].reject(error);
\r
3117 responsePromises = Object.create(null);
\r
3118 requestTokens = Object.create(null);
\r
3119 messageQueue = new linkedMap_1.LinkedMap();
\r
3120 // Test for backwards compatibility
\r
3121 if (Is.func(messageWriter.dispose)) {
\r
3122 messageWriter.dispose();
\r
3124 if (Is.func(messageReader.dispose)) {
\r
3125 messageReader.dispose();
\r
3129 throwIfClosedOrDisposed();
\r
3130 throwIfListening();
\r
3131 state = ConnectionState.Listening;
\r
3132 messageReader.listen(callback);
\r
3135 // eslint-disable-next-line no-console
\r
3136 console.log('inspect');
\r
3139 connection.onNotification(LogTraceNotification.type, (params) => {
\r
3140 if (trace === Trace.Off || !tracer) {
\r
3143 tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
\r
3145 connection.onNotification(ProgressNotification.type, (params) => {
\r
3146 const handler = progressHandlers.get(params.token);
\r
3148 handler(params.value);
\r
3151 unhandledProgressEmitter.fire(params);
\r
3154 return connection;
\r
3156 function isMessageReader(value) {
\r
3157 return value.listen !== void 0 && value.read === void 0;
\r
3159 function isMessageWriter(value) {
\r
3160 return value.write !== void 0 && value.end === void 0;
\r
3162 function createMessageConnection(input, output, logger, strategy) {
\r
3164 logger = exports.NullLogger;
\r
3166 let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
\r
3167 let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
\r
3168 return _createMessageConnection(reader, writer, logger, strategy);
\r
3170 exports.createMessageConnection = createMessageConnection;
\r
3175 /***/ ((__unused_webpack_module, exports) => {
3177 /* --------------------------------------------------------------------------------------------
\r
3178 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
3179 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
3180 * ------------------------------------------------------------------------------------------ */
\r
3182 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
3183 function boolean(value) {
\r
3184 return value === true || value === false;
\r
3186 exports.boolean = boolean;
\r
3187 function string(value) {
\r
3188 return typeof value === 'string' || value instanceof String;
\r
3190 exports.string = string;
\r
3191 function number(value) {
\r
3192 return typeof value === 'number' || value instanceof Number;
\r
3194 exports.number = number;
\r
3195 function error(value) {
\r
3196 return value instanceof Error;
\r
3198 exports.error = error;
\r
3199 function func(value) {
\r
3200 return typeof value === 'function';
\r
3202 exports.func = func;
\r
3203 function array(value) {
\r
3204 return Array.isArray(value);
\r
3206 exports.array = array;
\r
3207 function stringArray(value) {
\r
3208 return array(value) && value.every(elem => string(elem));
\r
3210 exports.stringArray = stringArray;
\r
3215 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3217 /* --------------------------------------------------------------------------------------------
\r
3218 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
3219 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
3220 * ------------------------------------------------------------------------------------------ */
\r
3222 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
3223 const is = __webpack_require__(10);
\r
3225 * Predefined error codes.
\r
3228 (function (ErrorCodes) {
\r
3229 // Defined by JSON RPC
\r
3230 ErrorCodes.ParseError = -32700;
\r
3231 ErrorCodes.InvalidRequest = -32600;
\r
3232 ErrorCodes.MethodNotFound = -32601;
\r
3233 ErrorCodes.InvalidParams = -32602;
\r
3234 ErrorCodes.InternalError = -32603;
\r
3235 ErrorCodes.serverErrorStart = -32099;
\r
3236 ErrorCodes.serverErrorEnd = -32000;
\r
3237 ErrorCodes.ServerNotInitialized = -32002;
\r
3238 ErrorCodes.UnknownErrorCode = -32001;
\r
3239 // Defined by the protocol.
\r
3240 ErrorCodes.RequestCancelled = -32800;
\r
3241 ErrorCodes.ContentModified = -32801;
\r
3242 // Defined by VSCode library.
\r
3243 ErrorCodes.MessageWriteError = 1;
\r
3244 ErrorCodes.MessageReadError = 2;
\r
3245 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
\r
3247 * An error object return in a response in case a request
\r
3250 class ResponseError extends Error {
\r
3251 constructor(code, message, data) {
\r
3253 this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
\r
3255 Object.setPrototypeOf(this, ResponseError.prototype);
\r
3260 message: this.message,
\r
3265 exports.ResponseError = ResponseError;
\r
3267 * An abstract implementation of a MessageType.
\r
3269 class AbstractMessageType {
\r
3270 constructor(_method, _numberOfParams) {
\r
3271 this._method = _method;
\r
3272 this._numberOfParams = _numberOfParams;
\r
3275 return this._method;
\r
3277 get numberOfParams() {
\r
3278 return this._numberOfParams;
\r
3281 exports.AbstractMessageType = AbstractMessageType;
\r
3283 * Classes to type request response pairs
\r
3285 * The type parameter RO will be removed in the next major version
\r
3286 * of the JSON RPC library since it is a LSP concept and doesn't
\r
3287 * belong here. For now it is tagged as default never.
\r
3289 class RequestType0 extends AbstractMessageType {
\r
3290 constructor(method) {
\r
3294 exports.RequestType0 = RequestType0;
\r
3295 class RequestType extends AbstractMessageType {
\r
3296 constructor(method) {
\r
3300 exports.RequestType = RequestType;
\r
3301 class RequestType1 extends AbstractMessageType {
\r
3302 constructor(method) {
\r
3306 exports.RequestType1 = RequestType1;
\r
3307 class RequestType2 extends AbstractMessageType {
\r
3308 constructor(method) {
\r
3312 exports.RequestType2 = RequestType2;
\r
3313 class RequestType3 extends AbstractMessageType {
\r
3314 constructor(method) {
\r
3318 exports.RequestType3 = RequestType3;
\r
3319 class RequestType4 extends AbstractMessageType {
\r
3320 constructor(method) {
\r
3324 exports.RequestType4 = RequestType4;
\r
3325 class RequestType5 extends AbstractMessageType {
\r
3326 constructor(method) {
\r
3330 exports.RequestType5 = RequestType5;
\r
3331 class RequestType6 extends AbstractMessageType {
\r
3332 constructor(method) {
\r
3336 exports.RequestType6 = RequestType6;
\r
3337 class RequestType7 extends AbstractMessageType {
\r
3338 constructor(method) {
\r
3342 exports.RequestType7 = RequestType7;
\r
3343 class RequestType8 extends AbstractMessageType {
\r
3344 constructor(method) {
\r
3348 exports.RequestType8 = RequestType8;
\r
3349 class RequestType9 extends AbstractMessageType {
\r
3350 constructor(method) {
\r
3354 exports.RequestType9 = RequestType9;
\r
3356 * The type parameter RO will be removed in the next major version
\r
3357 * of the JSON RPC library since it is a LSP concept and doesn't
\r
3358 * belong here. For now it is tagged as default never.
\r
3360 class NotificationType extends AbstractMessageType {
\r
3361 constructor(method) {
\r
3363 this._ = undefined;
\r
3366 exports.NotificationType = NotificationType;
\r
3367 class NotificationType0 extends AbstractMessageType {
\r
3368 constructor(method) {
\r
3372 exports.NotificationType0 = NotificationType0;
\r
3373 class NotificationType1 extends AbstractMessageType {
\r
3374 constructor(method) {
\r
3378 exports.NotificationType1 = NotificationType1;
\r
3379 class NotificationType2 extends AbstractMessageType {
\r
3380 constructor(method) {
\r
3384 exports.NotificationType2 = NotificationType2;
\r
3385 class NotificationType3 extends AbstractMessageType {
\r
3386 constructor(method) {
\r
3390 exports.NotificationType3 = NotificationType3;
\r
3391 class NotificationType4 extends AbstractMessageType {
\r
3392 constructor(method) {
\r
3396 exports.NotificationType4 = NotificationType4;
\r
3397 class NotificationType5 extends AbstractMessageType {
\r
3398 constructor(method) {
\r
3402 exports.NotificationType5 = NotificationType5;
\r
3403 class NotificationType6 extends AbstractMessageType {
\r
3404 constructor(method) {
\r
3408 exports.NotificationType6 = NotificationType6;
\r
3409 class NotificationType7 extends AbstractMessageType {
\r
3410 constructor(method) {
\r
3414 exports.NotificationType7 = NotificationType7;
\r
3415 class NotificationType8 extends AbstractMessageType {
\r
3416 constructor(method) {
\r
3420 exports.NotificationType8 = NotificationType8;
\r
3421 class NotificationType9 extends AbstractMessageType {
\r
3422 constructor(method) {
\r
3426 exports.NotificationType9 = NotificationType9;
\r
3428 * Tests if the given message is a request message
\r
3430 function isRequestMessage(message) {
\r
3431 let candidate = message;
\r
3432 return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
\r
3434 exports.isRequestMessage = isRequestMessage;
\r
3436 * Tests if the given message is a notification message
\r
3438 function isNotificationMessage(message) {
\r
3439 let candidate = message;
\r
3440 return candidate && is.string(candidate.method) && message.id === void 0;
\r
3442 exports.isNotificationMessage = isNotificationMessage;
\r
3444 * Tests if the given message is a response message
\r
3446 function isResponseMessage(message) {
\r
3447 let candidate = message;
\r
3448 return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
\r
3450 exports.isResponseMessage = isResponseMessage;
\r
3455 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3457 /* --------------------------------------------------------------------------------------------
\r
3458 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
3459 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
3460 * ------------------------------------------------------------------------------------------ */
\r
3462 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
3463 const events_1 = __webpack_require__(13);
\r
3464 const Is = __webpack_require__(10);
\r
3465 let DefaultSize = 8192;
\r
3466 let CR = Buffer.from('\r', 'ascii')[0];
\r
3467 let LF = Buffer.from('\n', 'ascii')[0];
\r
3468 let CRLF = '\r\n';
\r
3469 class MessageBuffer {
\r
3470 constructor(encoding = 'utf8') {
\r
3471 this.encoding = encoding;
\r
3473 this.buffer = Buffer.allocUnsafe(DefaultSize);
\r
3476 var toAppend = chunk;
\r
3477 if (typeof (chunk) === 'string') {
\r
3479 var bufferLen = Buffer.byteLength(str, this.encoding);
\r
3480 toAppend = Buffer.allocUnsafe(bufferLen);
\r
3481 toAppend.write(str, 0, bufferLen, this.encoding);
\r
3483 if (this.buffer.length - this.index >= toAppend.length) {
\r
3484 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
\r
3487 var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
\r
3488 if (this.index === 0) {
\r
3489 this.buffer = Buffer.allocUnsafe(newSize);
\r
3490 toAppend.copy(this.buffer, 0, 0, toAppend.length);
\r
3493 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
\r
3496 this.index += toAppend.length;
\r
3498 tryReadHeaders() {
\r
3499 let result = undefined;
\r
3501 while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
\r
3504 // No header / body separator found (e.g CRLFCRLF)
\r
3505 if (current + 3 >= this.index) {
\r
3508 result = Object.create(null);
\r
3509 let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
\r
3510 headers.forEach((header) => {
\r
3511 let index = header.indexOf(':');
\r
3512 if (index === -1) {
\r
3513 throw new Error('Message header must separate key and value using :');
\r
3515 let key = header.substr(0, index);
\r
3516 let value = header.substr(index + 1).trim();
\r
3517 result[key] = value;
\r
3519 let nextStart = current + 4;
\r
3520 this.buffer = this.buffer.slice(nextStart);
\r
3521 this.index = this.index - nextStart;
\r
3524 tryReadContent(length) {
\r
3525 if (this.index < length) {
\r
3528 let result = this.buffer.toString(this.encoding, 0, length);
\r
3529 let nextStart = length;
\r
3530 this.buffer.copy(this.buffer, 0, nextStart);
\r
3531 this.index = this.index - nextStart;
\r
3534 get numberOfBytes() {
\r
3535 return this.index;
\r
3538 var MessageReader;
\r
3539 (function (MessageReader) {
\r
3540 function is(value) {
\r
3541 let candidate = value;
\r
3542 return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
\r
3543 Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
\r
3545 MessageReader.is = is;
\r
3546 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
\r
3547 class AbstractMessageReader {
\r
3549 this.errorEmitter = new events_1.Emitter();
\r
3550 this.closeEmitter = new events_1.Emitter();
\r
3551 this.partialMessageEmitter = new events_1.Emitter();
\r
3554 this.errorEmitter.dispose();
\r
3555 this.closeEmitter.dispose();
\r
3558 return this.errorEmitter.event;
\r
3560 fireError(error) {
\r
3561 this.errorEmitter.fire(this.asError(error));
\r
3564 return this.closeEmitter.event;
\r
3567 this.closeEmitter.fire(undefined);
\r
3569 get onPartialMessage() {
\r
3570 return this.partialMessageEmitter.event;
\r
3572 firePartialMessage(info) {
\r
3573 this.partialMessageEmitter.fire(info);
\r
3576 if (error instanceof Error) {
\r
3580 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
3584 exports.AbstractMessageReader = AbstractMessageReader;
\r
3585 class StreamMessageReader extends AbstractMessageReader {
\r
3586 constructor(readable, encoding = 'utf8') {
\r
3588 this.readable = readable;
\r
3589 this.buffer = new MessageBuffer(encoding);
\r
3590 this._partialMessageTimeout = 10000;
\r
3592 set partialMessageTimeout(timeout) {
\r
3593 this._partialMessageTimeout = timeout;
\r
3595 get partialMessageTimeout() {
\r
3596 return this._partialMessageTimeout;
\r
3598 listen(callback) {
\r
3599 this.nextMessageLength = -1;
\r
3600 this.messageToken = 0;
\r
3601 this.partialMessageTimer = undefined;
\r
3602 this.callback = callback;
\r
3603 this.readable.on('data', (data) => {
\r
3604 this.onData(data);
\r
3606 this.readable.on('error', (error) => this.fireError(error));
\r
3607 this.readable.on('close', () => this.fireClose());
\r
3610 this.buffer.append(data);
\r
3612 if (this.nextMessageLength === -1) {
\r
3613 let headers = this.buffer.tryReadHeaders();
\r
3617 let contentLength = headers['Content-Length'];
\r
3618 if (!contentLength) {
\r
3619 throw new Error('Header must provide a Content-Length property.');
\r
3621 let length = parseInt(contentLength);
\r
3622 if (isNaN(length)) {
\r
3623 throw new Error('Content-Length value must be a number.');
\r
3625 this.nextMessageLength = length;
\r
3626 // Take the encoding form the header. For compatibility
\r
3627 // treat both utf-8 and utf8 as node utf8
\r
3629 var msg = this.buffer.tryReadContent(this.nextMessageLength);
\r
3630 if (msg === null) {
\r
3631 /** We haven't received the full message yet. */
\r
3632 this.setPartialMessageTimer();
\r
3635 this.clearPartialMessageTimer();
\r
3636 this.nextMessageLength = -1;
\r
3637 this.messageToken++;
\r
3638 var json = JSON.parse(msg);
\r
3639 this.callback(json);
\r
3642 clearPartialMessageTimer() {
\r
3643 if (this.partialMessageTimer) {
\r
3644 clearTimeout(this.partialMessageTimer);
\r
3645 this.partialMessageTimer = undefined;
\r
3648 setPartialMessageTimer() {
\r
3649 this.clearPartialMessageTimer();
\r
3650 if (this._partialMessageTimeout <= 0) {
\r
3653 this.partialMessageTimer = setTimeout((token, timeout) => {
\r
3654 this.partialMessageTimer = undefined;
\r
3655 if (token === this.messageToken) {
\r
3656 this.firePartialMessage({ messageToken: token, waitingTime: timeout });
\r
3657 this.setPartialMessageTimer();
\r
3659 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
\r
3662 exports.StreamMessageReader = StreamMessageReader;
\r
3663 class IPCMessageReader extends AbstractMessageReader {
\r
3664 constructor(process) {
\r
3666 this.process = process;
\r
3667 let eventEmitter = this.process;
\r
3668 eventEmitter.on('error', (error) => this.fireError(error));
\r
3669 eventEmitter.on('close', () => this.fireClose());
\r
3671 listen(callback) {
\r
3672 this.process.on('message', callback);
\r
3675 exports.IPCMessageReader = IPCMessageReader;
\r
3676 class SocketMessageReader extends StreamMessageReader {
\r
3677 constructor(socket, encoding = 'utf-8') {
\r
3678 super(socket, encoding);
\r
3681 exports.SocketMessageReader = SocketMessageReader;
\r
3686 /***/ ((__unused_webpack_module, exports) => {
3688 /* --------------------------------------------------------------------------------------------
\r
3689 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
3690 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
3691 * ------------------------------------------------------------------------------------------ */
\r
3693 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
3695 (function (Disposable) {
\r
3696 function create(func) {
\r
3701 Disposable.create = create;
\r
3702 })(Disposable = exports.Disposable || (exports.Disposable = {}));
\r
3704 (function (Event) {
\r
3705 const _disposable = { dispose() { } };
\r
3706 Event.None = function () { return _disposable; };
\r
3707 })(Event = exports.Event || (exports.Event = {}));
\r
3708 class CallbackList {
\r
3709 add(callback, context = null, bucket) {
\r
3710 if (!this._callbacks) {
\r
3711 this._callbacks = [];
\r
3712 this._contexts = [];
\r
3714 this._callbacks.push(callback);
\r
3715 this._contexts.push(context);
\r
3716 if (Array.isArray(bucket)) {
\r
3717 bucket.push({ dispose: () => this.remove(callback, context) });
\r
3720 remove(callback, context = null) {
\r
3721 if (!this._callbacks) {
\r
3724 var foundCallbackWithDifferentContext = false;
\r
3725 for (var i = 0, len = this._callbacks.length; i < len; i++) {
\r
3726 if (this._callbacks[i] === callback) {
\r
3727 if (this._contexts[i] === context) {
\r
3728 // callback & context match => remove it
\r
3729 this._callbacks.splice(i, 1);
\r
3730 this._contexts.splice(i, 1);
\r
3734 foundCallbackWithDifferentContext = true;
\r
3738 if (foundCallbackWithDifferentContext) {
\r
3739 throw new Error('When adding a listener with a context, you should remove it with the same context');
\r
3743 if (!this._callbacks) {
\r
3746 var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
\r
3747 for (var i = 0, len = callbacks.length; i < len; i++) {
\r
3749 ret.push(callbacks[i].apply(contexts[i], args));
\r
3752 // eslint-disable-next-line no-console
\r
3759 return !this._callbacks || this._callbacks.length === 0;
\r
3762 this._callbacks = undefined;
\r
3763 this._contexts = undefined;
\r
3767 constructor(_options) {
\r
3768 this._options = _options;
\r
3771 * For the public to allow to subscribe
\r
3772 * to events from this Emitter
\r
3775 if (!this._event) {
\r
3776 this._event = (listener, thisArgs, disposables) => {
\r
3777 if (!this._callbacks) {
\r
3778 this._callbacks = new CallbackList();
\r
3780 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
\r
3781 this._options.onFirstListenerAdd(this);
\r
3783 this._callbacks.add(listener, thisArgs);
\r
3787 this._callbacks.remove(listener, thisArgs);
\r
3788 result.dispose = Emitter._noop;
\r
3789 if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
\r
3790 this._options.onLastListenerRemove(this);
\r
3794 if (Array.isArray(disposables)) {
\r
3795 disposables.push(result);
\r
3800 return this._event;
\r
3803 * To be kept private to fire an event to
\r
3807 if (this._callbacks) {
\r
3808 this._callbacks.invoke.call(this._callbacks, event);
\r
3812 if (this._callbacks) {
\r
3813 this._callbacks.dispose();
\r
3814 this._callbacks = undefined;
\r
3818 exports.Emitter = Emitter;
\r
3819 Emitter._noop = function () { };
\r
3824 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3826 /* --------------------------------------------------------------------------------------------
\r
3827 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
3828 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
3829 * ------------------------------------------------------------------------------------------ */
\r
3831 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
3832 const events_1 = __webpack_require__(13);
\r
3833 const Is = __webpack_require__(10);
\r
3834 let ContentLength = 'Content-Length: ';
\r
3835 let CRLF = '\r\n';
\r
3836 var MessageWriter;
\r
3837 (function (MessageWriter) {
\r
3838 function is(value) {
\r
3839 let candidate = value;
\r
3840 return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
\r
3841 Is.func(candidate.onError) && Is.func(candidate.write);
\r
3843 MessageWriter.is = is;
\r
3844 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
\r
3845 class AbstractMessageWriter {
\r
3847 this.errorEmitter = new events_1.Emitter();
\r
3848 this.closeEmitter = new events_1.Emitter();
\r
3851 this.errorEmitter.dispose();
\r
3852 this.closeEmitter.dispose();
\r
3855 return this.errorEmitter.event;
\r
3857 fireError(error, message, count) {
\r
3858 this.errorEmitter.fire([this.asError(error), message, count]);
\r
3861 return this.closeEmitter.event;
\r
3864 this.closeEmitter.fire(undefined);
\r
3867 if (error instanceof Error) {
\r
3871 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
3875 exports.AbstractMessageWriter = AbstractMessageWriter;
\r
3876 class StreamMessageWriter extends AbstractMessageWriter {
\r
3877 constructor(writable, encoding = 'utf8') {
\r
3879 this.writable = writable;
\r
3880 this.encoding = encoding;
\r
3881 this.errorCount = 0;
\r
3882 this.writable.on('error', (error) => this.fireError(error));
\r
3883 this.writable.on('close', () => this.fireClose());
\r
3886 let json = JSON.stringify(msg);
\r
3887 let contentLength = Buffer.byteLength(json, this.encoding);
\r
3889 ContentLength, contentLength.toString(), CRLF,
\r
3893 // Header must be written in ASCII encoding
\r
3894 this.writable.write(headers.join(''), 'ascii');
\r
3895 // Now write the content. This can be written in any encoding
\r
3896 this.writable.write(json, this.encoding);
\r
3897 this.errorCount = 0;
\r
3900 this.errorCount++;
\r
3901 this.fireError(error, msg, this.errorCount);
\r
3905 exports.StreamMessageWriter = StreamMessageWriter;
\r
3906 class IPCMessageWriter extends AbstractMessageWriter {
\r
3907 constructor(process) {
\r
3909 this.process = process;
\r
3910 this.errorCount = 0;
\r
3912 this.sending = false;
\r
3913 let eventEmitter = this.process;
\r
3914 eventEmitter.on('error', (error) => this.fireError(error));
\r
3915 eventEmitter.on('close', () => this.fireClose);
\r
3918 if (!this.sending && this.queue.length === 0) {
\r
3919 // See https://github.com/nodejs/node/issues/7657
\r
3920 this.doWriteMessage(msg);
\r
3923 this.queue.push(msg);
\r
3926 doWriteMessage(msg) {
\r
3928 if (this.process.send) {
\r
3929 this.sending = true;
\r
3930 this.process.send(msg, undefined, undefined, (error) => {
\r
3931 this.sending = false;
\r
3933 this.errorCount++;
\r
3934 this.fireError(error, msg, this.errorCount);
\r
3937 this.errorCount = 0;
\r
3939 if (this.queue.length > 0) {
\r
3940 this.doWriteMessage(this.queue.shift());
\r
3946 this.errorCount++;
\r
3947 this.fireError(error, msg, this.errorCount);
\r
3951 exports.IPCMessageWriter = IPCMessageWriter;
\r
3952 class SocketMessageWriter extends AbstractMessageWriter {
\r
3953 constructor(socket, encoding = 'utf8') {
\r
3955 this.socket = socket;
\r
3957 this.sending = false;
\r
3958 this.encoding = encoding;
\r
3959 this.errorCount = 0;
\r
3960 this.socket.on('error', (error) => this.fireError(error));
\r
3961 this.socket.on('close', () => this.fireClose());
\r
3965 this.socket.destroy();
\r
3968 if (!this.sending && this.queue.length === 0) {
\r
3969 // See https://github.com/nodejs/node/issues/7657
\r
3970 this.doWriteMessage(msg);
\r
3973 this.queue.push(msg);
\r
3976 doWriteMessage(msg) {
\r
3977 let json = JSON.stringify(msg);
\r
3978 let contentLength = Buffer.byteLength(json, this.encoding);
\r
3980 ContentLength, contentLength.toString(), CRLF,
\r
3984 // Header must be written in ASCII encoding
\r
3985 this.sending = true;
\r
3986 this.socket.write(headers.join(''), 'ascii', (error) => {
\r
3988 this.handleError(error, msg);
\r
3991 // Now write the content. This can be written in any encoding
\r
3992 this.socket.write(json, this.encoding, (error) => {
\r
3993 this.sending = false;
\r
3995 this.handleError(error, msg);
\r
3998 this.errorCount = 0;
\r
4000 if (this.queue.length > 0) {
\r
4001 this.doWriteMessage(this.queue.shift());
\r
4006 this.handleError(error, msg);
\r
4011 this.handleError(error, msg);
\r
4014 handleError(error, msg) {
\r
4015 this.errorCount++;
\r
4016 this.fireError(error, msg, this.errorCount);
\r
4019 exports.SocketMessageWriter = SocketMessageWriter;
\r
4024 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4026 /*---------------------------------------------------------------------------------------------
\r
4027 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4028 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4029 *--------------------------------------------------------------------------------------------*/
\r
4031 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
4032 const events_1 = __webpack_require__(13);
\r
4033 const Is = __webpack_require__(10);
\r
4034 var CancellationToken;
\r
4035 (function (CancellationToken) {
\r
4036 CancellationToken.None = Object.freeze({
\r
4037 isCancellationRequested: false,
\r
4038 onCancellationRequested: events_1.Event.None
\r
4040 CancellationToken.Cancelled = Object.freeze({
\r
4041 isCancellationRequested: true,
\r
4042 onCancellationRequested: events_1.Event.None
\r
4044 function is(value) {
\r
4045 let candidate = value;
\r
4046 return candidate && (candidate === CancellationToken.None
\r
4047 || candidate === CancellationToken.Cancelled
\r
4048 || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
\r
4050 CancellationToken.is = is;
\r
4051 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
\r
4052 const shortcutEvent = Object.freeze(function (callback, context) {
\r
4053 let handle = setTimeout(callback.bind(context), 0);
\r
4054 return { dispose() { clearTimeout(handle); } };
\r
4056 class MutableToken {
\r
4058 this._isCancelled = false;
\r
4061 if (!this._isCancelled) {
\r
4062 this._isCancelled = true;
\r
4063 if (this._emitter) {
\r
4064 this._emitter.fire(undefined);
\r
4069 get isCancellationRequested() {
\r
4070 return this._isCancelled;
\r
4072 get onCancellationRequested() {
\r
4073 if (this._isCancelled) {
\r
4074 return shortcutEvent;
\r
4076 if (!this._emitter) {
\r
4077 this._emitter = new events_1.Emitter();
\r
4079 return this._emitter.event;
\r
4082 if (this._emitter) {
\r
4083 this._emitter.dispose();
\r
4084 this._emitter = undefined;
\r
4088 class CancellationTokenSource {
\r
4090 if (!this._token) {
\r
4091 // be lazy and create the token only when
\r
4092 // actually needed
\r
4093 this._token = new MutableToken();
\r
4095 return this._token;
\r
4098 if (!this._token) {
\r
4099 // save an object by returning the default
\r
4100 // cancelled token when cancellation happens
\r
4101 // before someone asks for the token
\r
4102 this._token = CancellationToken.Cancelled;
\r
4105 this._token.cancel();
\r
4109 if (!this._token) {
\r
4110 // ensure to initialize with an empty token if we had none
\r
4111 this._token = CancellationToken.None;
\r
4113 else if (this._token instanceof MutableToken) {
\r
4114 // actually dispose
\r
4115 this._token.dispose();
\r
4119 exports.CancellationTokenSource = CancellationTokenSource;
\r
4124 /***/ ((__unused_webpack_module, exports) => {
4127 /*---------------------------------------------------------------------------------------------
\r
4128 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4129 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4130 *--------------------------------------------------------------------------------------------*/
\r
4131 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
4133 (function (Touch) {
\r
4137 })(Touch = exports.Touch || (exports.Touch = {}));
\r
4140 this._map = new Map();
\r
4141 this._head = undefined;
\r
4142 this._tail = undefined;
\r
4146 this._map.clear();
\r
4147 this._head = undefined;
\r
4148 this._tail = undefined;
\r
4152 return !this._head && !this._tail;
\r
4155 return this._size;
\r
4158 return this._map.has(key);
\r
4161 const item = this._map.get(key);
\r
4165 return item.value;
\r
4167 set(key, value, touch = Touch.None) {
\r
4168 let item = this._map.get(key);
\r
4170 item.value = value;
\r
4171 if (touch !== Touch.None) {
\r
4172 this.touch(item, touch);
\r
4176 item = { key, value, next: undefined, previous: undefined };
\r
4179 this.addItemLast(item);
\r
4182 this.addItemFirst(item);
\r
4185 this.addItemLast(item);
\r
4188 this.addItemLast(item);
\r
4191 this._map.set(key, item);
\r
4196 const item = this._map.get(key);
\r
4200 this._map.delete(key);
\r
4201 this.removeItem(item);
\r
4206 if (!this._head && !this._tail) {
\r
4209 if (!this._head || !this._tail) {
\r
4210 throw new Error('Invalid list');
\r
4212 const item = this._head;
\r
4213 this._map.delete(item.key);
\r
4214 this.removeItem(item);
\r
4216 return item.value;
\r
4218 forEach(callbackfn, thisArg) {
\r
4219 let current = this._head;
\r
4222 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
4225 callbackfn(current.value, current.key, this);
\r
4227 current = current.next;
\r
4230 forEachReverse(callbackfn, thisArg) {
\r
4231 let current = this._tail;
\r
4234 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
4237 callbackfn(current.value, current.key, this);
\r
4239 current = current.previous;
\r
4244 let current = this._head;
\r
4246 result.push(current.value);
\r
4247 current = current.next;
\r
4253 let current = this._head;
\r
4255 result.push(current.key);
\r
4256 current = current.next;
\r
4260 /* JSON RPC run on es5 which has no Symbol.iterator
\r
4261 public keys(): IterableIterator<K> {
\r
4262 let current = this._head;
\r
4263 let iterator: IterableIterator<K> = {
\r
4264 [Symbol.iterator]() {
\r
4267 next():IteratorResult<K> {
\r
4269 let result = { value: current.key, done: false };
\r
4270 current = current.next;
\r
4273 return { value: undefined, done: true };
\r
4280 public values(): IterableIterator<V> {
\r
4281 let current = this._head;
\r
4282 let iterator: IterableIterator<V> = {
\r
4283 [Symbol.iterator]() {
\r
4286 next():IteratorResult<V> {
\r
4288 let result = { value: current.value, done: false };
\r
4289 current = current.next;
\r
4292 return { value: undefined, done: true };
\r
4299 addItemFirst(item) {
\r
4300 // First time Insert
\r
4301 if (!this._head && !this._tail) {
\r
4302 this._tail = item;
\r
4304 else if (!this._head) {
\r
4305 throw new Error('Invalid list');
\r
4308 item.next = this._head;
\r
4309 this._head.previous = item;
\r
4311 this._head = item;
\r
4313 addItemLast(item) {
\r
4314 // First time Insert
\r
4315 if (!this._head && !this._tail) {
\r
4316 this._head = item;
\r
4318 else if (!this._tail) {
\r
4319 throw new Error('Invalid list');
\r
4322 item.previous = this._tail;
\r
4323 this._tail.next = item;
\r
4325 this._tail = item;
\r
4327 removeItem(item) {
\r
4328 if (item === this._head && item === this._tail) {
\r
4329 this._head = undefined;
\r
4330 this._tail = undefined;
\r
4332 else if (item === this._head) {
\r
4333 this._head = item.next;
\r
4335 else if (item === this._tail) {
\r
4336 this._tail = item.previous;
\r
4339 const next = item.next;
\r
4340 const previous = item.previous;
\r
4341 if (!next || !previous) {
\r
4342 throw new Error('Invalid list');
\r
4344 next.previous = previous;
\r
4345 previous.next = next;
\r
4348 touch(item, touch) {
\r
4349 if (!this._head || !this._tail) {
\r
4350 throw new Error('Invalid list');
\r
4352 if ((touch !== Touch.First && touch !== Touch.Last)) {
\r
4355 if (touch === Touch.First) {
\r
4356 if (item === this._head) {
\r
4359 const next = item.next;
\r
4360 const previous = item.previous;
\r
4361 // Unlink the item
\r
4362 if (item === this._tail) {
\r
4363 // previous must be defined since item was not head but is tail
\r
4364 // So there are more than on item in the map
\r
4365 previous.next = undefined;
\r
4366 this._tail = previous;
\r
4369 // Both next and previous are not undefined since item was neither head nor tail.
\r
4370 next.previous = previous;
\r
4371 previous.next = next;
\r
4373 // Insert the node at head
\r
4374 item.previous = undefined;
\r
4375 item.next = this._head;
\r
4376 this._head.previous = item;
\r
4377 this._head = item;
\r
4379 else if (touch === Touch.Last) {
\r
4380 if (item === this._tail) {
\r
4383 const next = item.next;
\r
4384 const previous = item.previous;
\r
4385 // Unlink the item.
\r
4386 if (item === this._head) {
\r
4387 // next must be defined since item was not tail but is head
\r
4388 // So there are more than on item in the map
\r
4389 next.previous = undefined;
\r
4390 this._head = next;
\r
4393 // Both next and previous are not undefined since item was neither head nor tail.
\r
4394 next.previous = previous;
\r
4395 previous.next = next;
\r
4397 item.next = undefined;
\r
4398 item.previous = this._tail;
\r
4399 this._tail.next = item;
\r
4400 this._tail = item;
\r
4404 exports.LinkedMap = LinkedMap;
\r
4409 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4411 /* --------------------------------------------------------------------------------------------
\r
4412 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4413 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4414 * ------------------------------------------------------------------------------------------ */
\r
4416 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
4417 const path_1 = __webpack_require__(4);
\r
4418 const os_1 = __webpack_require__(3);
\r
4419 const crypto_1 = __webpack_require__(18);
\r
4420 const net_1 = __webpack_require__(19);
\r
4421 const messageReader_1 = __webpack_require__(12);
\r
4422 const messageWriter_1 = __webpack_require__(14);
\r
4423 function generateRandomPipeName() {
\r
4424 const randomSuffix = crypto_1.randomBytes(21).toString('hex');
\r
4425 if (process.platform === 'win32') {
\r
4426 return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
\r
4429 // Mac/Unix: use socket file
\r
4430 return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
\r
4433 exports.generateRandomPipeName = generateRandomPipeName;
\r
4434 function createClientPipeTransport(pipeName, encoding = 'utf-8') {
\r
4435 let connectResolve;
\r
4436 let connected = new Promise((resolve, _reject) => {
\r
4437 connectResolve = resolve;
\r
4439 return new Promise((resolve, reject) => {
\r
4440 let server = net_1.createServer((socket) => {
\r
4443 new messageReader_1.SocketMessageReader(socket, encoding),
\r
4444 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
4447 server.on('error', reject);
\r
4448 server.listen(pipeName, () => {
\r
4449 server.removeListener('error', reject);
\r
4451 onConnected: () => { return connected; }
\r
4456 exports.createClientPipeTransport = createClientPipeTransport;
\r
4457 function createServerPipeTransport(pipeName, encoding = 'utf-8') {
\r
4458 const socket = net_1.createConnection(pipeName);
\r
4460 new messageReader_1.SocketMessageReader(socket, encoding),
\r
4461 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
4464 exports.createServerPipeTransport = createServerPipeTransport;
\r
4469 /***/ ((module) => {
4471 module.exports = require("crypto");;
4475 /***/ ((module) => {
4477 module.exports = require("net");;
4481 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4483 /* --------------------------------------------------------------------------------------------
\r
4484 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4485 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4486 * ------------------------------------------------------------------------------------------ */
\r
4488 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
4489 const net_1 = __webpack_require__(19);
\r
4490 const messageReader_1 = __webpack_require__(12);
\r
4491 const messageWriter_1 = __webpack_require__(14);
\r
4492 function createClientSocketTransport(port, encoding = 'utf-8') {
\r
4493 let connectResolve;
\r
4494 let connected = new Promise((resolve, _reject) => {
\r
4495 connectResolve = resolve;
\r
4497 return new Promise((resolve, reject) => {
\r
4498 let server = net_1.createServer((socket) => {
\r
4501 new messageReader_1.SocketMessageReader(socket, encoding),
\r
4502 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
4505 server.on('error', reject);
\r
4506 server.listen(port, '127.0.0.1', () => {
\r
4507 server.removeListener('error', reject);
\r
4509 onConnected: () => { return connected; }
\r
4514 exports.createClientSocketTransport = createClientSocketTransport;
\r
4515 function createServerSocketTransport(port, encoding = 'utf-8') {
\r
4516 const socket = net_1.createConnection(port, '127.0.0.1');
\r
4518 new messageReader_1.SocketMessageReader(socket, encoding),
\r
4519 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
4522 exports.createServerSocketTransport = createServerSocketTransport;
\r
4527 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4529 /* --------------------------------------------------------------------------------------------
\r
4530 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4531 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4532 * ------------------------------------------------------------------------------------------ */
\r
4534 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
4535 const Is = __webpack_require__(22);
\r
4536 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
4537 const messages_1 = __webpack_require__(23);
\r
4538 const protocol_implementation_1 = __webpack_require__(24);
\r
4539 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
\r
4540 const protocol_typeDefinition_1 = __webpack_require__(25);
\r
4541 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
\r
4542 const protocol_workspaceFolders_1 = __webpack_require__(26);
\r
4543 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
\r
4544 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
\r
4545 const protocol_configuration_1 = __webpack_require__(27);
\r
4546 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
\r
4547 const protocol_colorProvider_1 = __webpack_require__(28);
\r
4548 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
\r
4549 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
\r
4550 const protocol_foldingRange_1 = __webpack_require__(29);
\r
4551 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
\r
4552 const protocol_declaration_1 = __webpack_require__(30);
\r
4553 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
\r
4554 const protocol_selectionRange_1 = __webpack_require__(31);
\r
4555 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
\r
4556 const protocol_progress_1 = __webpack_require__(32);
\r
4557 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
\r
4558 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
\r
4559 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
\r
4560 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4561 let __noDynamicImport;
\r
4563 * The DocumentFilter namespace provides helper functions to work with
\r
4564 * [DocumentFilter](#DocumentFilter) literals.
\r
4566 var DocumentFilter;
\r
4567 (function (DocumentFilter) {
\r
4568 function is(value) {
\r
4569 const candidate = value;
\r
4570 return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
\r
4572 DocumentFilter.is = is;
\r
4573 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
\r
4575 * The DocumentSelector namespace provides helper functions to work with
\r
4576 * [DocumentSelector](#DocumentSelector)s.
\r
4578 var DocumentSelector;
\r
4579 (function (DocumentSelector) {
\r
4580 function is(value) {
\r
4581 if (!Array.isArray(value)) {
\r
4584 for (let elem of value) {
\r
4585 if (!Is.string(elem) && !DocumentFilter.is(elem)) {
\r
4591 DocumentSelector.is = is;
\r
4592 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
\r
4594 * The `client/registerCapability` request is sent from the server to the client to register a new capability
\r
4595 * handler on the client side.
\r
4597 var RegistrationRequest;
\r
4598 (function (RegistrationRequest) {
\r
4599 RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
\r
4600 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
\r
4602 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
\r
4603 * handler on the client side.
\r
4605 var UnregistrationRequest;
\r
4606 (function (UnregistrationRequest) {
\r
4607 UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
\r
4608 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
\r
4609 var ResourceOperationKind;
\r
4610 (function (ResourceOperationKind) {
\r
4612 * Supports creating new files and folders.
\r
4614 ResourceOperationKind.Create = 'create';
\r
4616 * Supports renaming existing files and folders.
\r
4618 ResourceOperationKind.Rename = 'rename';
\r
4620 * Supports deleting existing files and folders.
\r
4622 ResourceOperationKind.Delete = 'delete';
\r
4623 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
\r
4624 var FailureHandlingKind;
\r
4625 (function (FailureHandlingKind) {
\r
4627 * Applying the workspace change is simply aborted if one of the changes provided
\r
4628 * fails. All operations executed before the failing operation stay executed.
\r
4630 FailureHandlingKind.Abort = 'abort';
\r
4632 * All operations are executed transactional. That means they either all
\r
4633 * succeed or no changes at all are applied to the workspace.
\r
4635 FailureHandlingKind.Transactional = 'transactional';
\r
4637 * If the workspace edit contains only textual file changes they are executed transactional.
\r
4638 * If resource changes (create, rename or delete file) are part of the change the failure
\r
4639 * handling startegy is abort.
\r
4641 FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
\r
4643 * The client tries to undo the operations already executed. But there is no
\r
4644 * guarantee that this is succeeding.
\r
4646 FailureHandlingKind.Undo = 'undo';
\r
4647 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
\r
4649 * The StaticRegistrationOptions namespace provides helper functions to work with
\r
4650 * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
\r
4652 var StaticRegistrationOptions;
\r
4653 (function (StaticRegistrationOptions) {
\r
4654 function hasId(value) {
\r
4655 const candidate = value;
\r
4656 return candidate && Is.string(candidate.id) && candidate.id.length > 0;
\r
4658 StaticRegistrationOptions.hasId = hasId;
\r
4659 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
\r
4661 * The TextDocumentRegistrationOptions namespace provides helper functions to work with
\r
4662 * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
\r
4664 var TextDocumentRegistrationOptions;
\r
4665 (function (TextDocumentRegistrationOptions) {
\r
4666 function is(value) {
\r
4667 const candidate = value;
\r
4668 return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
\r
4670 TextDocumentRegistrationOptions.is = is;
\r
4671 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
\r
4673 * The WorkDoneProgressOptions namespace provides helper functions to work with
\r
4674 * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
\r
4676 var WorkDoneProgressOptions;
\r
4677 (function (WorkDoneProgressOptions) {
\r
4678 function is(value) {
\r
4679 const candidate = value;
\r
4680 return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
\r
4682 WorkDoneProgressOptions.is = is;
\r
4683 function hasWorkDoneProgress(value) {
\r
4684 const candidate = value;
\r
4685 return candidate && Is.boolean(candidate.workDoneProgress);
\r
4687 WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
\r
4688 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
\r
4690 * The initialize request is sent from the client to the server.
\r
4691 * It is sent once as the request after starting up the server.
\r
4692 * The requests parameter is of type [InitializeParams](#InitializeParams)
\r
4693 * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
\r
4694 * resolves to such.
\r
4696 var InitializeRequest;
\r
4697 (function (InitializeRequest) {
\r
4698 InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
\r
4699 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
\r
4701 * Known error codes for an `InitializeError`;
\r
4703 var InitializeError;
\r
4704 (function (InitializeError) {
\r
4706 * If the protocol version provided by the client can't be handled by the server.
\r
4707 * @deprecated This initialize error got replaced by client capabilities. There is
\r
4708 * no version handshake in version 3.0x
\r
4710 InitializeError.unknownProtocolVersion = 1;
\r
4711 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
\r
4713 * The intialized notification is sent from the client to the
\r
4714 * server after the client is fully initialized and the server
\r
4715 * is allowed to send requests from the server to the client.
\r
4717 var InitializedNotification;
\r
4718 (function (InitializedNotification) {
\r
4719 InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
\r
4720 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
\r
4721 //---- Shutdown Method ----
\r
4723 * A shutdown request is sent from the client to the server.
\r
4724 * It is sent once when the client decides to shutdown the
\r
4725 * server. The only notification that is sent after a shutdown request
\r
4726 * is the exit event.
\r
4728 var ShutdownRequest;
\r
4729 (function (ShutdownRequest) {
\r
4730 ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
\r
4731 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
\r
4732 //---- Exit Notification ----
\r
4734 * The exit event is sent from the client to the server to
\r
4735 * ask the server to exit its process.
\r
4737 var ExitNotification;
\r
4738 (function (ExitNotification) {
\r
4739 ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
\r
4740 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
\r
4742 * The configuration change notification is sent from the client to the server
\r
4743 * when the client's configuration has changed. The notification contains
\r
4744 * the changed configuration as defined by the language client.
\r
4746 var DidChangeConfigurationNotification;
\r
4747 (function (DidChangeConfigurationNotification) {
\r
4748 DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
\r
4749 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
\r
4750 //---- Message show and log notifications ----
\r
4752 * The message type
\r
4755 (function (MessageType) {
\r
4757 * An error message.
\r
4759 MessageType.Error = 1;
\r
4761 * A warning message.
\r
4763 MessageType.Warning = 2;
\r
4765 * An information message.
\r
4767 MessageType.Info = 3;
\r
4771 MessageType.Log = 4;
\r
4772 })(MessageType = exports.MessageType || (exports.MessageType = {}));
\r
4774 * The show message notification is sent from a server to a client to ask
\r
4775 * the client to display a particular message in the user interface.
\r
4777 var ShowMessageNotification;
\r
4778 (function (ShowMessageNotification) {
\r
4779 ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
\r
4780 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
\r
4782 * The show message request is sent from the server to the client to show a message
\r
4783 * and a set of options actions to the user.
\r
4785 var ShowMessageRequest;
\r
4786 (function (ShowMessageRequest) {
\r
4787 ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
\r
4788 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
\r
4790 * The log message notification is sent from the server to the client to ask
\r
4791 * the client to log a particular message.
\r
4793 var LogMessageNotification;
\r
4794 (function (LogMessageNotification) {
\r
4795 LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
\r
4796 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
\r
4797 //---- Telemetry notification
\r
4799 * The telemetry event notification is sent from the server to the client to ask
\r
4800 * the client to log telemetry data.
\r
4802 var TelemetryEventNotification;
\r
4803 (function (TelemetryEventNotification) {
\r
4804 TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
\r
4805 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
\r
4807 * Defines how the host (editor) should sync
\r
4808 * document changes to the language server.
\r
4810 var TextDocumentSyncKind;
\r
4811 (function (TextDocumentSyncKind) {
\r
4813 * Documents should not be synced at all.
\r
4815 TextDocumentSyncKind.None = 0;
\r
4817 * Documents are synced by always sending the full content
\r
4818 * of the document.
\r
4820 TextDocumentSyncKind.Full = 1;
\r
4822 * Documents are synced by sending the full content on open.
\r
4823 * After that only incremental updates to the document are
\r
4826 TextDocumentSyncKind.Incremental = 2;
\r
4827 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
\r
4829 * The document open notification is sent from the client to the server to signal
\r
4830 * newly opened text documents. The document's truth is now managed by the client
\r
4831 * and the server must not try to read the document's truth using the document's
\r
4832 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
\r
4833 * mean that its content is presented in an editor. An open notification must not
\r
4834 * be sent more than once without a corresponding close notification send before.
\r
4835 * This means open and close notification must be balanced and the max open count
\r
4838 var DidOpenTextDocumentNotification;
\r
4839 (function (DidOpenTextDocumentNotification) {
\r
4840 DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
\r
4841 DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
\r
4842 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
\r
4844 * The document change notification is sent from the client to the server to signal
\r
4845 * changes to a text document.
\r
4847 var DidChangeTextDocumentNotification;
\r
4848 (function (DidChangeTextDocumentNotification) {
\r
4849 DidChangeTextDocumentNotification.method = 'textDocument/didChange';
\r
4850 DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
\r
4851 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
\r
4853 * The document close notification is sent from the client to the server when
\r
4854 * the document got closed in the client. The document's truth now exists where
\r
4855 * the document's uri points to (e.g. if the document's uri is a file uri the
\r
4856 * truth now exists on disk). As with the open notification the close notification
\r
4857 * is about managing the document's content. Receiving a close notification
\r
4858 * doesn't mean that the document was open in an editor before. A close
\r
4859 * notification requires a previous open notification to be sent.
\r
4861 var DidCloseTextDocumentNotification;
\r
4862 (function (DidCloseTextDocumentNotification) {
\r
4863 DidCloseTextDocumentNotification.method = 'textDocument/didClose';
\r
4864 DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
\r
4865 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
\r
4867 * The document save notification is sent from the client to the server when
\r
4868 * the document got saved in the client.
\r
4870 var DidSaveTextDocumentNotification;
\r
4871 (function (DidSaveTextDocumentNotification) {
\r
4872 DidSaveTextDocumentNotification.method = 'textDocument/didSave';
\r
4873 DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
\r
4874 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
\r
4876 * Represents reasons why a text document is saved.
\r
4878 var TextDocumentSaveReason;
\r
4879 (function (TextDocumentSaveReason) {
\r
4881 * Manually triggered, e.g. by the user pressing save, by starting debugging,
\r
4882 * or by an API call.
\r
4884 TextDocumentSaveReason.Manual = 1;
\r
4886 * Automatic after a delay.
\r
4888 TextDocumentSaveReason.AfterDelay = 2;
\r
4890 * When the editor lost focus.
\r
4892 TextDocumentSaveReason.FocusOut = 3;
\r
4893 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
\r
4895 * A document will save notification is sent from the client to the server before
\r
4896 * the document is actually saved.
\r
4898 var WillSaveTextDocumentNotification;
\r
4899 (function (WillSaveTextDocumentNotification) {
\r
4900 WillSaveTextDocumentNotification.method = 'textDocument/willSave';
\r
4901 WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
\r
4902 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
\r
4904 * A document will save request is sent from the client to the server before
\r
4905 * the document is actually saved. The request can return an array of TextEdits
\r
4906 * which will be applied to the text document before it is saved. Please note that
\r
4907 * clients might drop results if computing the text edits took too long or if a
\r
4908 * server constantly fails on this request. This is done to keep the save fast and
\r
4911 var WillSaveTextDocumentWaitUntilRequest;
\r
4912 (function (WillSaveTextDocumentWaitUntilRequest) {
\r
4913 WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
\r
4914 WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
\r
4915 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
\r
4917 * The watched files notification is sent from the client to the server when
\r
4918 * the client detects changes to file watched by the language client.
\r
4920 var DidChangeWatchedFilesNotification;
\r
4921 (function (DidChangeWatchedFilesNotification) {
\r
4922 DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
\r
4923 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
\r
4925 * The file event type
\r
4927 var FileChangeType;
\r
4928 (function (FileChangeType) {
\r
4930 * The file got created.
\r
4932 FileChangeType.Created = 1;
\r
4934 * The file got changed.
\r
4936 FileChangeType.Changed = 2;
\r
4938 * The file got deleted.
\r
4940 FileChangeType.Deleted = 3;
\r
4941 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
\r
4943 (function (WatchKind) {
\r
4945 * Interested in create events.
\r
4947 WatchKind.Create = 1;
\r
4949 * Interested in change events
\r
4951 WatchKind.Change = 2;
\r
4953 * Interested in delete events
\r
4955 WatchKind.Delete = 4;
\r
4956 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
\r
4958 * Diagnostics notification are sent from the server to the client to signal
\r
4959 * results of validation runs.
\r
4961 var PublishDiagnosticsNotification;
\r
4962 (function (PublishDiagnosticsNotification) {
\r
4963 PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
\r
4964 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
\r
4966 * How a completion was triggered
\r
4968 var CompletionTriggerKind;
\r
4969 (function (CompletionTriggerKind) {
\r
4971 * Completion was triggered by typing an identifier (24x7 code
\r
4972 * complete), manual invocation (e.g Ctrl+Space) or via API.
\r
4974 CompletionTriggerKind.Invoked = 1;
\r
4976 * Completion was triggered by a trigger character specified by
\r
4977 * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
\r
4979 CompletionTriggerKind.TriggerCharacter = 2;
\r
4981 * Completion was re-triggered as current completion list is incomplete
\r
4983 CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
\r
4984 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
\r
4986 * Request to request completion at a given text document position. The request's
\r
4987 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
\r
4988 * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
\r
4989 * or a Thenable that resolves to such.
\r
4991 * The request can delay the computation of the [`detail`](#CompletionItem.detail)
\r
4992 * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
\r
4993 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
\r
4994 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
\r
4996 var CompletionRequest;
\r
4997 (function (CompletionRequest) {
\r
4998 CompletionRequest.method = 'textDocument/completion';
\r
4999 CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
\r
5000 /** @deprecated Use CompletionRequest.type */
\r
5001 CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5002 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
\r
5004 * Request to resolve additional information for a given completion item.The request's
\r
5005 * parameter is of type [CompletionItem](#CompletionItem) the response
\r
5006 * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
\r
5008 var CompletionResolveRequest;
\r
5009 (function (CompletionResolveRequest) {
\r
5010 CompletionResolveRequest.method = 'completionItem/resolve';
\r
5011 CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
\r
5012 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
\r
5014 * Request to request hover information at a given text document position. The request's
\r
5015 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
\r
5016 * type [Hover](#Hover) or a Thenable that resolves to such.
\r
5019 (function (HoverRequest) {
\r
5020 HoverRequest.method = 'textDocument/hover';
\r
5021 HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
\r
5022 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
\r
5024 * How a signature help was triggered.
\r
5028 var SignatureHelpTriggerKind;
\r
5029 (function (SignatureHelpTriggerKind) {
\r
5031 * Signature help was invoked manually by the user or by a command.
\r
5033 SignatureHelpTriggerKind.Invoked = 1;
\r
5035 * Signature help was triggered by a trigger character.
\r
5037 SignatureHelpTriggerKind.TriggerCharacter = 2;
\r
5039 * Signature help was triggered by the cursor moving or by the document content changing.
\r
5041 SignatureHelpTriggerKind.ContentChange = 3;
\r
5042 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
\r
5043 var SignatureHelpRequest;
\r
5044 (function (SignatureHelpRequest) {
\r
5045 SignatureHelpRequest.method = 'textDocument/signatureHelp';
\r
5046 SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
\r
5047 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
\r
5049 * A request to resolve the definition location of a symbol at a given text
\r
5050 * document position. The request's parameter is of type [TextDocumentPosition]
\r
5051 * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
\r
5052 * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
\r
5055 var DefinitionRequest;
\r
5056 (function (DefinitionRequest) {
\r
5057 DefinitionRequest.method = 'textDocument/definition';
\r
5058 DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
\r
5059 /** @deprecated Use DefinitionRequest.type */
\r
5060 DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5061 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
\r
5063 * A request to resolve project-wide references for the symbol denoted
\r
5064 * by the given text document position. The request's parameter is of
\r
5065 * type [ReferenceParams](#ReferenceParams) the response is of type
\r
5066 * [Location[]](#Location) or a Thenable that resolves to such.
\r
5068 var ReferencesRequest;
\r
5069 (function (ReferencesRequest) {
\r
5070 ReferencesRequest.method = 'textDocument/references';
\r
5071 ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
\r
5072 /** @deprecated Use ReferencesRequest.type */
\r
5073 ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5074 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
\r
5076 * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
\r
5077 * text document position. The request's parameter is of type [TextDocumentPosition]
\r
5078 * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
\r
5079 * (#DocumentHighlight) or a Thenable that resolves to such.
\r
5081 var DocumentHighlightRequest;
\r
5082 (function (DocumentHighlightRequest) {
\r
5083 DocumentHighlightRequest.method = 'textDocument/documentHighlight';
\r
5084 DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
\r
5085 /** @deprecated Use DocumentHighlightRequest.type */
\r
5086 DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5087 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
\r
5089 * A request to list all symbols found in a given text document. The request's
\r
5090 * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
\r
5091 * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
\r
5092 * that resolves to such.
\r
5094 var DocumentSymbolRequest;
\r
5095 (function (DocumentSymbolRequest) {
\r
5096 DocumentSymbolRequest.method = 'textDocument/documentSymbol';
\r
5097 DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
\r
5098 /** @deprecated Use DocumentSymbolRequest.type */
\r
5099 DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5100 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
\r
5102 * A request to provide commands for the given text document and range.
\r
5104 var CodeActionRequest;
\r
5105 (function (CodeActionRequest) {
\r
5106 CodeActionRequest.method = 'textDocument/codeAction';
\r
5107 CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
\r
5108 /** @deprecated Use CodeActionRequest.type */
\r
5109 CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5110 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
\r
5112 * A request to list project-wide symbols matching the query string given
\r
5113 * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
\r
5114 * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
\r
5115 * resolves to such.
\r
5117 var WorkspaceSymbolRequest;
\r
5118 (function (WorkspaceSymbolRequest) {
\r
5119 WorkspaceSymbolRequest.method = 'workspace/symbol';
\r
5120 WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
\r
5121 /** @deprecated Use WorkspaceSymbolRequest.type */
\r
5122 WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5123 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
\r
5125 * A request to provide code lens for the given text document.
\r
5127 var CodeLensRequest;
\r
5128 (function (CodeLensRequest) {
\r
5129 CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
\r
5130 /** @deprecated Use CodeLensRequest.type */
\r
5131 CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5132 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
\r
5134 * A request to resolve a command for a given code lens.
\r
5136 var CodeLensResolveRequest;
\r
5137 (function (CodeLensResolveRequest) {
\r
5138 CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
\r
5139 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
\r
5141 * A request to provide document links
\r
5143 var DocumentLinkRequest;
\r
5144 (function (DocumentLinkRequest) {
\r
5145 DocumentLinkRequest.method = 'textDocument/documentLink';
\r
5146 DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
\r
5147 /** @deprecated Use DocumentLinkRequest.type */
\r
5148 DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5149 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
\r
5151 * Request to resolve additional information for a given document link. The request's
\r
5152 * parameter is of type [DocumentLink](#DocumentLink) the response
\r
5153 * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
\r
5155 var DocumentLinkResolveRequest;
\r
5156 (function (DocumentLinkResolveRequest) {
\r
5157 DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
\r
5158 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
\r
5160 * A request to to format a whole document.
\r
5162 var DocumentFormattingRequest;
\r
5163 (function (DocumentFormattingRequest) {
\r
5164 DocumentFormattingRequest.method = 'textDocument/formatting';
\r
5165 DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
\r
5166 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
\r
5168 * A request to to format a range in a document.
\r
5170 var DocumentRangeFormattingRequest;
\r
5171 (function (DocumentRangeFormattingRequest) {
\r
5172 DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
\r
5173 DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
\r
5174 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
\r
5176 * A request to format a document on type.
\r
5178 var DocumentOnTypeFormattingRequest;
\r
5179 (function (DocumentOnTypeFormattingRequest) {
\r
5180 DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
\r
5181 DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
\r
5182 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
\r
5184 * A request to rename a symbol.
\r
5186 var RenameRequest;
\r
5187 (function (RenameRequest) {
\r
5188 RenameRequest.method = 'textDocument/rename';
\r
5189 RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
\r
5190 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
\r
5192 * A request to test and perform the setup necessary for a rename.
\r
5194 var PrepareRenameRequest;
\r
5195 (function (PrepareRenameRequest) {
\r
5196 PrepareRenameRequest.method = 'textDocument/prepareRename';
\r
5197 PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
\r
5198 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
\r
5200 * A request send from the client to the server to execute a command. The request might return
\r
5201 * a workspace edit which the client will apply to the workspace.
\r
5203 var ExecuteCommandRequest;
\r
5204 (function (ExecuteCommandRequest) {
\r
5205 ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
\r
5206 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
\r
5208 * A request sent from the server to the client to modified certain resources.
\r
5210 var ApplyWorkspaceEditRequest;
\r
5211 (function (ApplyWorkspaceEditRequest) {
\r
5212 ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
\r
5213 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
\r
5218 /***/ ((__unused_webpack_module, exports) => {
5220 /* --------------------------------------------------------------------------------------------
\r
5221 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5222 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5223 * ------------------------------------------------------------------------------------------ */
\r
5225 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5226 function boolean(value) {
\r
5227 return value === true || value === false;
\r
5229 exports.boolean = boolean;
\r
5230 function string(value) {
\r
5231 return typeof value === 'string' || value instanceof String;
\r
5233 exports.string = string;
\r
5234 function number(value) {
\r
5235 return typeof value === 'number' || value instanceof Number;
\r
5237 exports.number = number;
\r
5238 function error(value) {
\r
5239 return value instanceof Error;
\r
5241 exports.error = error;
\r
5242 function func(value) {
\r
5243 return typeof value === 'function';
\r
5245 exports.func = func;
\r
5246 function array(value) {
\r
5247 return Array.isArray(value);
\r
5249 exports.array = array;
\r
5250 function stringArray(value) {
\r
5251 return array(value) && value.every(elem => string(elem));
\r
5253 exports.stringArray = stringArray;
\r
5254 function typedArray(value, check) {
\r
5255 return Array.isArray(value) && value.every(check);
\r
5257 exports.typedArray = typedArray;
\r
5258 function objectLiteral(value) {
\r
5259 // Strictly speaking class instances pass this check as well. Since the LSP
\r
5260 // doesn't use classes we ignore this for now. If we do we need to add something
\r
5261 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
5262 return value !== null && typeof value === 'object';
\r
5264 exports.objectLiteral = objectLiteral;
\r
5269 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5271 /* --------------------------------------------------------------------------------------------
\r
5272 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5273 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5274 * ------------------------------------------------------------------------------------------ */
\r
5276 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5277 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5278 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
\r
5279 constructor(method) {
\r
5283 exports.ProtocolRequestType0 = ProtocolRequestType0;
\r
5284 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
\r
5285 constructor(method) {
\r
5289 exports.ProtocolRequestType = ProtocolRequestType;
\r
5290 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
\r
5291 constructor(method) {
\r
5295 exports.ProtocolNotificationType = ProtocolNotificationType;
\r
5296 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
\r
5297 constructor(method) {
\r
5301 exports.ProtocolNotificationType0 = ProtocolNotificationType0;
\r
5306 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5308 /* --------------------------------------------------------------------------------------------
\r
5309 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5310 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5311 * ------------------------------------------------------------------------------------------ */
\r
5313 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5314 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5315 const messages_1 = __webpack_require__(23);
\r
5316 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5317 let __noDynamicImport;
\r
5319 * A request to resolve the implementation locations of a symbol at a given text
\r
5320 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5321 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5322 * Thenable that resolves to such.
\r
5324 var ImplementationRequest;
\r
5325 (function (ImplementationRequest) {
\r
5326 ImplementationRequest.method = 'textDocument/implementation';
\r
5327 ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
\r
5328 /** @deprecated Use ImplementationRequest.type */
\r
5329 ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5330 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
\r
5335 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5337 /* --------------------------------------------------------------------------------------------
\r
5338 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5339 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5340 * ------------------------------------------------------------------------------------------ */
\r
5342 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5343 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5344 const messages_1 = __webpack_require__(23);
\r
5345 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5346 let __noDynamicImport;
\r
5348 * A request to resolve the type definition locations of a symbol at a given text
\r
5349 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5350 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5351 * Thenable that resolves to such.
\r
5353 var TypeDefinitionRequest;
\r
5354 (function (TypeDefinitionRequest) {
\r
5355 TypeDefinitionRequest.method = 'textDocument/typeDefinition';
\r
5356 TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
\r
5357 /** @deprecated Use TypeDefinitionRequest.type */
\r
5358 TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5359 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
\r
5364 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5366 /* --------------------------------------------------------------------------------------------
\r
5367 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5368 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5369 * ------------------------------------------------------------------------------------------ */
\r
5371 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5372 const messages_1 = __webpack_require__(23);
\r
5374 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
\r
5376 var WorkspaceFoldersRequest;
\r
5377 (function (WorkspaceFoldersRequest) {
\r
5378 WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
\r
5379 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
\r
5381 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
\r
5382 * folder configuration changes.
\r
5384 var DidChangeWorkspaceFoldersNotification;
\r
5385 (function (DidChangeWorkspaceFoldersNotification) {
\r
5386 DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
\r
5387 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
\r
5392 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5394 /* --------------------------------------------------------------------------------------------
\r
5395 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5396 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5397 * ------------------------------------------------------------------------------------------ */
\r
5399 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5400 const messages_1 = __webpack_require__(23);
\r
5402 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
\r
5403 * configuration setting.
\r
5405 * This pull model replaces the old push model were the client signaled configuration change via an
\r
5406 * event. If the server still needs to react to configuration changes (since the server caches the
\r
5407 * result of `workspace/configuration` requests) the server should register for an empty configuration
\r
5408 * change event and empty the cache if such an event is received.
\r
5410 var ConfigurationRequest;
\r
5411 (function (ConfigurationRequest) {
\r
5412 ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
\r
5413 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
\r
5418 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5420 /* --------------------------------------------------------------------------------------------
\r
5421 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5422 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5423 * ------------------------------------------------------------------------------------------ */
\r
5425 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5426 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5427 const messages_1 = __webpack_require__(23);
\r
5429 * A request to list all color symbols found in a given text document. The request's
\r
5430 * parameter is of type [DocumentColorParams](#DocumentColorParams) the
\r
5431 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5432 * that resolves to such.
\r
5434 var DocumentColorRequest;
\r
5435 (function (DocumentColorRequest) {
\r
5436 DocumentColorRequest.method = 'textDocument/documentColor';
\r
5437 DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
\r
5438 /** @deprecated Use DocumentColorRequest.type */
\r
5439 DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5440 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
\r
5442 * A request to list all presentation for a color. The request's
\r
5443 * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
\r
5444 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5445 * that resolves to such.
\r
5447 var ColorPresentationRequest;
\r
5448 (function (ColorPresentationRequest) {
\r
5449 ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
\r
5450 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
\r
5455 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5458 /*---------------------------------------------------------------------------------------------
\r
5459 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5460 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5461 *--------------------------------------------------------------------------------------------*/
\r
5462 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5463 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5464 const messages_1 = __webpack_require__(23);
\r
5466 * Enum of known range kinds
\r
5468 var FoldingRangeKind;
\r
5469 (function (FoldingRangeKind) {
\r
5471 * Folding range for a comment
\r
5473 FoldingRangeKind["Comment"] = "comment";
\r
5475 * Folding range for a imports or includes
\r
5477 FoldingRangeKind["Imports"] = "imports";
\r
5479 * Folding range for a region (e.g. `#region`)
\r
5481 FoldingRangeKind["Region"] = "region";
\r
5482 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
\r
5484 * A request to provide folding ranges in a document. The request's
\r
5485 * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
\r
5486 * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
\r
5487 * that resolves to such.
\r
5489 var FoldingRangeRequest;
\r
5490 (function (FoldingRangeRequest) {
\r
5491 FoldingRangeRequest.method = 'textDocument/foldingRange';
\r
5492 FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
\r
5493 /** @deprecated Use FoldingRangeRequest.type */
\r
5494 FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5495 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
\r
5500 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5502 /* --------------------------------------------------------------------------------------------
\r
5503 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5504 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5505 * ------------------------------------------------------------------------------------------ */
\r
5507 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5508 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5509 const messages_1 = __webpack_require__(23);
\r
5510 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5511 let __noDynamicImport;
\r
5513 * A request to resolve the type definition locations of a symbol at a given text
\r
5514 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5515 * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
\r
5516 * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
\r
5519 var DeclarationRequest;
\r
5520 (function (DeclarationRequest) {
\r
5521 DeclarationRequest.method = 'textDocument/declaration';
\r
5522 DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
\r
5523 /** @deprecated Use DeclarationRequest.type */
\r
5524 DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5525 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
\r
5530 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5533 /*---------------------------------------------------------------------------------------------
\r
5534 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5535 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5536 *--------------------------------------------------------------------------------------------*/
\r
5537 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5538 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5539 const messages_1 = __webpack_require__(23);
\r
5541 * A request to provide selection ranges in a document. The request's
\r
5542 * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
\r
5543 * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
\r
5544 * that resolves to such.
\r
5546 var SelectionRangeRequest;
\r
5547 (function (SelectionRangeRequest) {
\r
5548 SelectionRangeRequest.method = 'textDocument/selectionRange';
\r
5549 SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
\r
5550 /** @deprecated Use SelectionRangeRequest.type */
\r
5551 SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5552 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
\r
5557 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5559 /* --------------------------------------------------------------------------------------------
\r
5560 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5561 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5562 * ------------------------------------------------------------------------------------------ */
\r
5564 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5565 const vscode_jsonrpc_1 = __webpack_require__(9);
\r
5566 const messages_1 = __webpack_require__(23);
\r
5567 var WorkDoneProgress;
\r
5568 (function (WorkDoneProgress) {
\r
5569 WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
\r
5570 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
\r
5572 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
\r
5573 * reporting from the server.
\r
5575 var WorkDoneProgressCreateRequest;
\r
5576 (function (WorkDoneProgressCreateRequest) {
\r
5577 WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
\r
5578 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
\r
5580 * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
\r
5581 * initiated on the server side.
\r
5583 var WorkDoneProgressCancelNotification;
\r
5584 (function (WorkDoneProgressCancelNotification) {
\r
5585 WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
\r
5586 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
\r
5591 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5593 /* --------------------------------------------------------------------------------------------
\r
5594 * Copyright (c) TypeFox and others. All rights reserved.
\r
5595 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5596 * ------------------------------------------------------------------------------------------ */
\r
5598 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5599 const messages_1 = __webpack_require__(23);
\r
5601 * A request to result a `CallHierarchyItem` in a document at a given position.
\r
5602 * Can be used as an input to a incoming or outgoing call hierarchy.
\r
5604 * @since 3.16.0 - Proposed state
\r
5606 var CallHierarchyPrepareRequest;
\r
5607 (function (CallHierarchyPrepareRequest) {
\r
5608 CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
\r
5609 CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
\r
5610 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
\r
5612 * A request to resolve the incoming calls for a given `CallHierarchyItem`.
\r
5614 * @since 3.16.0 - Proposed state
\r
5616 var CallHierarchyIncomingCallsRequest;
\r
5617 (function (CallHierarchyIncomingCallsRequest) {
\r
5618 CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
\r
5619 CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
\r
5620 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
\r
5622 * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
\r
5624 * @since 3.16.0 - Proposed state
\r
5626 var CallHierarchyOutgoingCallsRequest;
\r
5627 (function (CallHierarchyOutgoingCallsRequest) {
\r
5628 CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
\r
5629 CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
\r
5630 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
\r
5635 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5637 /* --------------------------------------------------------------------------------------------
\r
5638 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5639 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5640 * ------------------------------------------------------------------------------------------ */
\r
5642 Object.defineProperty(exports, "__esModule", ({ value: true }));
\r
5643 const messages_1 = __webpack_require__(23);
\r
5645 * A set of predefined token types. This set is not fixed
\r
5646 * an clients can specify additional token types via the
\r
5647 * corresponding client capabilities.
\r
5649 * @since 3.16.0 - Proposed state
\r
5651 var SemanticTokenTypes;
\r
5652 (function (SemanticTokenTypes) {
\r
5653 SemanticTokenTypes["comment"] = "comment";
\r
5654 SemanticTokenTypes["keyword"] = "keyword";
\r
5655 SemanticTokenTypes["string"] = "string";
\r
5656 SemanticTokenTypes["number"] = "number";
\r
5657 SemanticTokenTypes["regexp"] = "regexp";
\r
5658 SemanticTokenTypes["operator"] = "operator";
\r
5659 SemanticTokenTypes["namespace"] = "namespace";
\r
5660 SemanticTokenTypes["type"] = "type";
\r
5661 SemanticTokenTypes["struct"] = "struct";
\r
5662 SemanticTokenTypes["class"] = "class";
\r
5663 SemanticTokenTypes["interface"] = "interface";
\r
5664 SemanticTokenTypes["enum"] = "enum";
\r
5665 SemanticTokenTypes["typeParameter"] = "typeParameter";
\r
5666 SemanticTokenTypes["function"] = "function";
\r
5667 SemanticTokenTypes["member"] = "member";
\r
5668 SemanticTokenTypes["property"] = "property";
\r
5669 SemanticTokenTypes["macro"] = "macro";
\r
5670 SemanticTokenTypes["variable"] = "variable";
\r
5671 SemanticTokenTypes["parameter"] = "parameter";
\r
5672 SemanticTokenTypes["label"] = "label";
\r
5673 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
\r
5675 * A set of predefined token modifiers. This set is not fixed
\r
5676 * an clients can specify additional token types via the
\r
5677 * corresponding client capabilities.
\r
5679 * @since 3.16.0 - Proposed state
\r
5681 var SemanticTokenModifiers;
\r
5682 (function (SemanticTokenModifiers) {
\r
5683 SemanticTokenModifiers["documentation"] = "documentation";
\r
5684 SemanticTokenModifiers["declaration"] = "declaration";
\r
5685 SemanticTokenModifiers["definition"] = "definition";
\r
5686 SemanticTokenModifiers["reference"] = "reference";
\r
5687 SemanticTokenModifiers["static"] = "static";
\r
5688 SemanticTokenModifiers["abstract"] = "abstract";
\r
5689 SemanticTokenModifiers["deprecated"] = "deprecated";
\r
5690 SemanticTokenModifiers["async"] = "async";
\r
5691 SemanticTokenModifiers["volatile"] = "volatile";
\r
5692 SemanticTokenModifiers["readonly"] = "readonly";
\r
5693 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
\r
5695 * @since 3.16.0 - Proposed state
\r
5697 var SemanticTokens;
\r
5698 (function (SemanticTokens) {
\r
5699 function is(value) {
\r
5700 const candidate = value;
\r
5701 return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
\r
5702 Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
\r
5704 SemanticTokens.is = is;
\r
5705 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
\r
5707 * @since 3.16.0 - Proposed state
\r
5709 var SemanticTokensRequest;
\r
5710 (function (SemanticTokensRequest) {
\r
5711 SemanticTokensRequest.method = 'textDocument/semanticTokens';
\r
5712 SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
\r
5713 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
\r
5715 * @since 3.16.0 - Proposed state
\r
5717 var SemanticTokensEditsRequest;
\r
5718 (function (SemanticTokensEditsRequest) {
\r
5719 SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
\r
5720 SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
\r
5721 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
\r
5723 * @since 3.16.0 - Proposed state
\r
5725 var SemanticTokensRangeRequest;
\r
5726 (function (SemanticTokensRangeRequest) {
\r
5727 SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
\r
5728 SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
\r
5729 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
\r
5734 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
5737 var __importDefault = (this && this.__importDefault) || function (mod) {
5738 return (mod && mod.__esModule) ? mod : { "default": mod };
5740 Object.defineProperty(exports, "__esModule", ({ value: true }));
5741 exports.markdownBlock = exports.getRegexText = exports.wait = exports.convertRegex = exports.distinct = exports.trimQuote = exports.memorize = exports.headTail = exports.readdirAsync = exports.readFileAsync = exports.writeFileAsync = exports.statAsync = exports.flatten = exports.replaceText = exports.uid = void 0;
5742 /******************************************************************
5743 MIT License http://www.opensource.org/licenses/mit-license.php
5744 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
5745 *******************************************************************/
5746 const pify_1 = __importDefault(__webpack_require__(36));
5747 const fs_1 = __importDefault(__webpack_require__(2));
5748 const crypto_1 = __importDefault(__webpack_require__(18));
5749 const BASE64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
5750 function tostr(bytes) {
5753 for (i = 0; i < bytes.length; i++) {
5754 r.push(BASE64[bytes[i] % 64]);
5759 return tostr(crypto_1.default.randomBytes(10));
5762 function replaceText(content, items) {
5764 items.sort((a, b) => a.index - b.index);
5765 let item = items.shift();
5766 for (let i = 0; i < content.length; i++) {
5767 let idx = item ? item.index : null;
5768 if (idx == null || i != idx) {
5769 res = res + content[i];
5772 res = res + item.newText;
5773 i = i + item.length;
5777 exports.replaceText = replaceText;
5778 function flatten(arr) {
5779 return arr.reduce((p, curr) => p.concat(curr), []);
5781 exports.flatten = flatten;
5782 async function statAsync(filepath) {
5784 return await pify_1.default(fs_1.default.stat)(filepath);
5790 exports.statAsync = statAsync;
5791 async function writeFileAsync(fullpath, content) {
5792 await pify_1.default(fs_1.default.writeFile)(fullpath, content, 'utf8');
5794 exports.writeFileAsync = writeFileAsync;
5795 async function readFileAsync(fullpath, encoding = 'utf8') {
5796 return await pify_1.default(fs_1.default.readFile)(fullpath, encoding);
5798 exports.readFileAsync = readFileAsync;
5799 async function readdirAsync(filepath) {
5801 return await pify_1.default(fs_1.default.readdir)(filepath);
5807 exports.readdirAsync = readdirAsync;
5808 function headTail(line) {
5810 let ms = line.match(/^(\S+)\s+(.*)/);
5813 return [ms[1], ms[2]];
5815 exports.headTail = headTail;
5816 function memorize(_target, key, descriptor) {
5817 let fn = descriptor.get;
5818 if (typeof fn !== 'function')
5820 let memoKey = '$' + key;
5821 descriptor.get = function (...args) {
5822 if (this.hasOwnProperty(memoKey))
5823 return Promise.resolve(this[memoKey]);
5824 return new Promise((resolve, reject) => {
5825 Promise.resolve(fn.apply(this, args)).then(res => {
5826 this[memoKey] = res;
5834 exports.memorize = memorize;
5835 function trimQuote(str) {
5836 if (str.startsWith('"') || str.startsWith("'"))
5837 return str.slice(1, -1);
5840 exports.trimQuote = trimQuote;
5841 function distinct(array, keyFn) {
5843 return array.filter((element, position) => {
5844 return array.indexOf(element) === position;
5847 const seen = Object.create(null);
5848 return array.filter(elem => {
5849 const key = keyFn(elem);
5857 exports.distinct = distinct;
5858 const conditionRe = /\(\?\(\?:\w+\).+\|/;
5859 const bellRe = /\\a/;
5860 const commentRe = /\(\?#.*?\)/;
5861 const stringStartRe = /\\A/;
5862 const namedCaptureRe = /\(\?P<\w+>.*?\)/;
5863 const namedReferenceRe = /\(\?P=(\w+)\)/;
5864 const braceRe = /\^\]/;
5865 const regex = new RegExp(`${bellRe.source}|${commentRe.source}|${stringStartRe.source}|${namedCaptureRe.source}|${namedReferenceRe.source}|${braceRe}`, 'g');
5867 * Convert python regex to javascript regex,
5868 * throw error when unsupported pattern found
5871 * @param {string} str
5874 function convertRegex(str) {
5875 if (str.indexOf('\\z') !== -1) {
5876 throw new Error('pattern \\z not supported');
5878 if (str.indexOf('(?s)') !== -1) {
5879 throw new Error('pattern (?s) not supported');
5881 if (str.indexOf('(?x)') !== -1) {
5882 throw new Error('pattern (?x) not supported');
5884 if (str.indexOf('\n') !== -1) {
5885 throw new Error('multiple line pattern not supported');
5887 if (conditionRe.test(str)) {
5888 throw new Error('condition pattern not supported');
5890 return str.replace(regex, (match, p1) => {
5895 if (match.startsWith('(?#'))
5899 if (match.startsWith('(?P<'))
5900 return '(?' + match.slice(3);
5901 if (match.startsWith('(?P='))
5902 return `\\k<${p1}>`;
5906 exports.convertRegex = convertRegex;
5908 return new Promise(resolve => {
5914 exports.wait = wait;
5915 function getRegexText(prefix) {
5916 if (prefix.startsWith('^'))
5917 prefix = prefix.slice(1);
5918 if (prefix.endsWith('$'))
5919 prefix = prefix.slice(0, -1);
5920 let content = prefix.replace(/\(.*\)\??/g, '');
5921 content = content.replace(/\\/g, '');
5924 exports.getRegexText = getRegexText;
5925 function markdownBlock(code, filetype) {
5926 filetype = filetype == 'javascriptreact' ? 'javascript' : filetype;
5927 filetype = filetype == 'typescriptreact' ? 'typescript' : filetype;
5928 return '``` ' + filetype + '\n' + code + '\n```';
5930 exports.markdownBlock = markdownBlock;
5935 /***/ ((module) => {
5939 const processFn = (fn, options, proxy, unwrapped) => function (...arguments_) {
5940 const P = options.promiseModule;
5942 return new P((resolve, reject) => {
5943 if (options.multiArgs) {
5944 arguments_.push((...result) => {
5945 if (options.errorFirst) {
5956 } else if (options.errorFirst) {
5957 arguments_.push((error, result) => {
5965 arguments_.push(resolve);
5968 const self = this === proxy ? unwrapped : this;
5969 Reflect.apply(fn, self, arguments_);
5973 const filterCache = new WeakMap();
5975 module.exports = (input, options) => {
5977 exclude: [/.+(?:Sync|Stream)$/],
5979 promiseModule: Promise,
5983 const objectType = typeof input;
5984 if (!(input !== null && (objectType === 'object' || objectType === 'function'))) {
5985 throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objectType}\``);
5988 const filter = (target, key) => {
5989 let cached = filterCache.get(target);
5993 filterCache.set(target, cached);
5996 if (key in cached) {
6000 const match = pattern => (typeof pattern === 'string' || typeof key === 'symbol') ? key === pattern : pattern.test(key);
6001 const desc = Reflect.getOwnPropertyDescriptor(target, key);
6002 const writableOrConfigurableOwn = (desc === undefined || desc.writable || desc.configurable);
6003 const included = options.include ? options.include.some(match) : !options.exclude.some(match);
6004 const shouldFilter = included && writableOrConfigurableOwn;
6005 cached[key] = shouldFilter;
6006 return shouldFilter;
6009 const cache = new WeakMap();
6011 const proxy = new Proxy(input, {
6012 apply(target, thisArg, args) {
6013 const cached = cache.get(target);
6016 return Reflect.apply(cached, thisArg, args);
6019 const pified = options.excludeMain ? target : processFn(target, options, proxy, target);
6020 cache.set(target, pified);
6021 return Reflect.apply(pified, thisArg, args);
6025 const property = target[key];
6027 // eslint-disable-next-line no-use-extend-native/no-use-extend-native
6028 if (!filter(target, key) || property === Function.prototype[key]) {
6032 const cached = cache.get(property);
6038 if (typeof property === 'function') {
6039 const pified = processFn(property, options, proxy, target);
6040 cache.set(property, pified);
6054 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6057 var __importDefault = (this && this.__importDefault) || function (mod) {
6058 return (mod && mod.__esModule) ? mod : { "default": mod };
6060 Object.defineProperty(exports, "__esModule", ({ value: true }));
6061 /******************************************************************
6062 MIT License http://www.opensource.org/licenses/mit-license.php
6063 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
6064 *******************************************************************/
6065 const coc_nvim_1 = __webpack_require__(1);
6066 const vscode_languageserver_protocol_1 = __webpack_require__(8);
6067 const os_1 = __importDefault(__webpack_require__(3));
6068 class SnippetsList extends coc_nvim_1.BasicList {
6069 constructor(nvim, manager, mru) {
6071 this.manager = manager;
6073 this.name = 'snippets';
6074 this.description = 'snippets list';
6075 this.addLocationActions();
6077 async loadItems(context) {
6078 let { window } = context;
6079 let valid = await window.valid;
6082 let buf = await window.buffer;
6083 let doc = coc_nvim_1.workspace.getDocument(buf.id);
6086 let snippets = await this.manager.getSnippets(doc.filetype);
6088 let recents = await this.mru.load();
6089 for (let snip of snippets) {
6090 let pos = vscode_languageserver_protocol_1.Position.create(snip.lnum, 0);
6091 let location = vscode_languageserver_protocol_1.Location.create(coc_nvim_1.Uri.file(snip.filepath).toString(), vscode_languageserver_protocol_1.Range.create(pos, pos));
6092 let prefix = snip.prefix;
6093 if (prefix.length < 20) {
6094 prefix = `${prefix}${' '.repeat(20 - prefix.length)}`;
6096 let idx = recents.indexOf(snip.prefix);
6098 label: `${prefix}\t${snip.description}\t${snip.filepath.replace(os_1.default.homedir(), '~')}`,
6099 filterText: `${snip.prefix} ${snip.description}`,
6101 recentScore: idx == -1 ? -1 : recents.length - idx
6106 async doHighlight() {
6107 let { nvim } = coc_nvim_1.workspace;
6108 nvim.pauseNotification();
6109 nvim.command('syntax match CocSnippetsPrefix /\\v^\\S+/ contained containedin=CocSnippetsLine', true);
6110 nvim.command('syntax match CocSnippetsFile /\\v\\t\\S+$/ contained containedin=CocSnippetsLine', true);
6111 nvim.command('highlight default link CocSnippetsPrefix Identifier', true);
6112 nvim.command('highlight default link CocSnippetsFile Comment', true);
6113 await nvim.resumeNotification();
6116 exports.default = SnippetsList;
6121 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6124 var __importDefault = (this && this.__importDefault) || function (mod) {
6125 return (mod && mod.__esModule) ? mod : { "default": mod };
6127 Object.defineProperty(exports, "__esModule", ({ value: true }));
6128 exports.characterIndex = exports.ProviderManager = void 0;
6129 /******************************************************************
6130 MIT License http://www.opensource.org/licenses/mit-license.php
6131 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
6132 *******************************************************************/
6133 const coc_nvim_1 = __webpack_require__(1);
6134 const path_1 = __importDefault(__webpack_require__(4));
6135 const vscode_languageserver_protocol_1 = __webpack_require__(8);
6136 const types_1 = __webpack_require__(39);
6137 const util_1 = __webpack_require__(35);
6138 class ProviderManager {
6140 this.providers = new Map();
6142 regist(provider, name) {
6143 this.providers.set(name, provider);
6144 return vscode_languageserver_protocol_1.Disposable.create(() => {
6145 this.providers.delete(name);
6149 return this.providers.size > 0;
6152 let providers = Array.from(this.providers.values());
6153 await Promise.all(providers.map(provider => {
6154 return provider.init();
6157 async getSnippets(filetype) {
6158 let names = Array.from(this.providers.keys());
6160 for (let name of names) {
6161 let provider = this.providers.get(name);
6162 let snippets = await provider.getSnippets(filetype);
6163 snippets.map(s => s.provider = name);
6164 list.push(...snippets);
6168 async getSnippetFiles(filetype) {
6170 for (let provider of this.providers.values()) {
6171 let res = await provider.getSnippetFiles(filetype);
6172 files = files.concat(res);
6176 async getTriggerSnippets(autoTrigger = false) {
6177 let bufnr = await coc_nvim_1.workspace.nvim.call('bufnr', '%');
6178 let doc = coc_nvim_1.workspace.getDocument(bufnr);
6181 await doc.patchChange();
6182 let position = await coc_nvim_1.workspace.getCursorPosition();
6183 let names = Array.from(this.providers.keys());
6185 for (let name of names) {
6186 let provider = this.providers.get(name);
6187 let items = await provider.getTriggerSnippets(doc, position, autoTrigger);
6188 for (let item of items) {
6189 if (list.findIndex(o => o.prefix == item.prefix) == -1) {
6194 list.sort((a, b) => b.priority - a.priority);
6195 if (list.length > 1 && list[0].priority > 0) {
6196 list = list.filter(o => o.priority > 0);
6200 async provideCompletionItems(document, position, _token, context) {
6201 let doc = coc_nvim_1.workspace.getDocument(document.uri);
6204 let snippets = await this.getSnippets(doc.filetype);
6205 let currline = doc.getline(position.line, true);
6206 let { input, col } = context.option;
6207 let character = characterIndex(currline, col);
6208 let before_content = currline.slice(0, character);
6210 let contextPrefixes = [];
6211 for (let snip of snippets) {
6212 let contentBehind = before_content;
6213 if (contextPrefixes.indexOf(snip.prefix) !== -1)
6215 if (snip.regex != null && snip.prefix == '')
6218 let provider = this.providers.get(snip.provider);
6219 let valid = await provider.checkContext(snip.context);
6222 contextPrefixes.push(snip.prefix);
6224 let head = this.getPrefixHead(doc, snip.prefix);
6225 if (input.length == 0 && !before_content.endsWith(snip.prefix))
6229 kind: vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
6230 filterText: snip.prefix,
6231 detail: snip.description,
6232 insertTextFormat: vscode_languageserver_protocol_1.InsertTextFormat.Snippet
6236 provider: snip.provider,
6237 filepath: `${path_1.default.basename(snip.filepath)}:${snip.lnum}`
6240 if (!input.length || snip.prefix && input[0] != snip.prefix[0])
6242 let content = before_content + snip.prefix;
6243 let ms = content.match(snip.regex);
6247 else if (head && before_content.endsWith(head)) {
6248 contentBehind = before_content.slice(0, -head.length);
6249 let prefix = snip.prefix.slice(head.length);
6250 Object.assign(item, {
6252 range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character: character - head.length }, position),
6257 else if (input.length == 0) {
6258 let { prefix } = snip;
6259 contentBehind = before_content.slice(0, -prefix.length);
6260 Object.assign(item, {
6263 range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character: character - prefix.length }, position),
6268 if (snip.triggerKind == types_1.TriggerKind.LineBegin && contentBehind.trim().length)
6270 if (snip.triggerKind == types_1.TriggerKind.SpaceBefore) {
6271 if (contentBehind.length && !/\s/.test(contentBehind[contentBehind.length - 1])) {
6275 if (!item.textEdit) {
6277 range: vscode_languageserver_protocol_1.Range.create({ line: position.line, character }, position),
6281 item.data.location = `${snip.filepath}:${snip.lnum}`;
6282 item.data.line = contentBehind + snip.prefix;
6287 async resolveCompletionItem(item) {
6288 let provider = this.providers.get(item.data.provider);
6290 let filetype = await coc_nvim_1.workspace.nvim.eval('&filetype');
6291 let insertSnippet = await provider.resolveSnippetBody(item.data.snip, item.textEdit.range, item.data.line);
6292 item.textEdit.newText = insertSnippet;
6293 if (coc_nvim_1.snippetManager) {
6294 let snip = await Promise.resolve(coc_nvim_1.snippetManager.resolveSnippet(insertSnippet));
6295 item.documentation = {
6297 value: util_1.markdownBlock(snip.toString(), filetype)
6303 getPrefixHead(doc, prefix) {
6305 for (let idx = prefix.length - 1; idx >= 0; idx--) {
6306 if (!doc.isWord(prefix[idx])) {
6311 return res == 0 ? '' : prefix.slice(0, res + 1);
6314 exports.ProviderManager = ProviderManager;
6315 function characterIndex(content, byteIndex) {
6316 let buf = Buffer.from(content, 'utf8');
6317 return buf.slice(0, byteIndex).toString('utf8').length;
6319 exports.characterIndex = characterIndex;
6324 /***/ ((__unused_webpack_module, exports) => {
6327 Object.defineProperty(exports, "__esModule", ({ value: true }));
6328 exports.TriggerKind = void 0;
6330 (function (TriggerKind) {
6331 TriggerKind[TriggerKind["SpaceBefore"] = 0] = "SpaceBefore";
6332 TriggerKind[TriggerKind["LineBegin"] = 1] = "LineBegin";
6333 TriggerKind[TriggerKind["WordBoundary"] = 2] = "WordBoundary";
6334 TriggerKind[TriggerKind["InWord"] = 3] = "InWord";
6335 })(TriggerKind = exports.TriggerKind || (exports.TriggerKind = {}));
6340 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6343 var __importDefault = (this && this.__importDefault) || function (mod) {
6344 return (mod && mod.__esModule) ? mod : { "default": mod };
6346 Object.defineProperty(exports, "__esModule", ({ value: true }));
6347 exports.SnipmateProvider = void 0;
6348 /******************************************************************
6349 MIT License http://www.opensource.org/licenses/mit-license.php
6350 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
6351 *******************************************************************/
6352 const coc_nvim_1 = __webpack_require__(1);
6353 const fs_1 = __importDefault(__webpack_require__(2));
6354 const path_1 = __importDefault(__webpack_require__(4));
6355 const readline_1 = __importDefault(__webpack_require__(41));
6356 const vscode_languageserver_types_1 = __webpack_require__(6);
6357 const baseProvider_1 = __importDefault(__webpack_require__(42));
6358 const types_1 = __webpack_require__(39);
6359 const util_1 = __webpack_require__(35);
6360 const parser_1 = __importDefault(__webpack_require__(43));
6361 class SnipmateProvider extends baseProvider_1.default {
6362 constructor(channel, trace, config) {
6364 this.channel = channel;
6366 this.snippetFiles = [];
6367 this.disposables = [];
6368 coc_nvim_1.workspace.onDidSaveTextDocument(async (doc) => {
6369 let uri = coc_nvim_1.Uri.parse(doc.uri);
6370 if (uri.scheme != 'file')
6372 let filepath = uri.fsPath;
6373 if (!fs_1.default.existsSync(filepath))
6375 let snippetFile = this.snippetFiles.find(s => s.filepath == filepath);
6377 await this.loadSnippetsFromFile(snippetFile.filetype, snippetFile.directory, filepath);
6378 }, null, this.disposables);
6381 let arr = await this.getAllSnippetFiles();
6382 let { nvim } = coc_nvim_1.workspace;
6383 let author = await nvim.getVar('snips_author');
6385 await nvim.setVar('snips_author', this.config.author);
6386 await Promise.all(arr.map(({ filepath, directory, filetype }) => {
6387 return this.loadSnippetsFromFile(filetype, directory, filepath);
6390 async loadSnippetsFromFile(filetype, directory, filepath) {
6391 let snippets = await this.parseSnippetsFile(filepath);
6392 let idx = this.snippetFiles.findIndex(o => o.filepath == filepath);
6394 this.snippetFiles.splice(idx, 1);
6395 this.snippetFiles.push({
6401 this.channel.appendLine(`[Info ${(new Date()).toISOString()}] Loaded ${snippets.length} snipmate snippets from: ${filepath}`);
6404 * Resolve snippet body to inserted text.
6407 * @param {Snippet} snippet
6408 * @param {Range} _range
6409 * @param {string} _line
6410 * @returns {Promise<string>}
6412 async resolveSnippetBody(snippet, _range, _line) {
6413 let parser = new parser_1.default(snippet.body);
6415 let { nvim } = coc_nvim_1.workspace;
6416 while (!parser.eof()) {
6417 if (parser.curr == '`') {
6418 let idx = parser.nextIndex('`', true, false);
6420 resolved = resolved + parser.eatTo(parser.len);
6423 let code = parser.eatTo(idx + 1);
6424 code = code.slice(1, -1);
6425 if (code.startsWith('Filename')) {
6426 resolved = resolved + await nvim.call('expand', '%:p:t');
6430 resolved = resolved + await nvim.eval(code);
6433 this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Error on eval: ${code}`);
6438 parser.iterate(ch => {
6443 resolved = resolved + ch;
6451 * Parse snippets from snippets file.
6454 * @param {string} filepath
6455 * @returns {Promise<Snippet[]>}
6457 parseSnippetsFile(filepath) {
6459 const rl = readline_1.default.createInterface({
6460 input: fs_1.default.createReadStream(filepath, 'utf8'),
6466 let description = '';
6467 rl.on('line', line => {
6469 if (line.startsWith('#'))
6471 if (line.startsWith('snippet')) {
6472 line = line.replace(/\s*$/, '');
6473 if (lines.length && prefix) {
6476 lnum: lnum - lines.length - 1,
6477 body: lines.join('\n').replace(/\s+$/, ''),
6480 triggerKind: types_1.TriggerKind.SpaceBefore
6484 let ms = line.match(/^snippet\s+(\S+)(?:\s(.+))?$/);
6487 this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] Broken line on ${filepath}:${lnum}`);
6491 description = ms[2] || '';
6495 if (line.indexOf('VISUAL') !== -1) {
6496 line = line.replace(/\$(\{?)VISUAL\b(:[^\}])?(\}?)/g, '$$$1TM_SELECTED_TEXT$2$3');
6498 if (line.startsWith('\t')) {
6499 lines.push(line.slice(1));
6506 return new Promise(resolve => {
6507 rl.on('close', async () => {
6511 lnum: lnum - lines.length - 1,
6512 body: lines.join('\n'),
6515 triggerKind: types_1.TriggerKind.SpaceBefore
6522 async getTriggerSnippets(document, position, autoTrigger) {
6525 let snippets = await this.getSnippets(document.filetype);
6526 let line = document.getline(position.line);
6527 line = line.slice(0, position.character);
6528 if (!line || line[line.length - 1] == ' ')
6530 snippets = snippets.filter(s => {
6532 if (!line.endsWith(prefix))
6534 let pre = line.slice(0, line.length - prefix.length);
6535 return pre.length == 0 || /\s/.test(pre[pre.length - 1]);
6538 for (let s of snippets) {
6539 let character = position.character - s.prefix.length;
6540 let range = vscode_languageserver_types_1.Range.create(position.line, character, position.line, position.character);
6541 let newText = await this.resolveSnippetBody(s, range, line);
6544 description: s.description,
6545 location: s.filepath,
6553 async getSnippetFiles(filetype) {
6554 let filetypes = this.getFiletypes(filetype);
6556 for (let s of this.snippetFiles) {
6557 if (filetypes.indexOf(s.filetype) !== -1) {
6558 res.push(s.filepath);
6563 async getSnippets(filetype) {
6564 let filetypes = this.getFiletypes(filetype);
6565 filetypes.push('_');
6566 let snippetFiles = this.snippetFiles.filter(o => filetypes.indexOf(o.filetype) !== -1);
6568 snippetFiles.sort((a, b) => {
6569 if (a.filetype == b.filetype)
6571 if (a.filetype == filetype)
6575 for (let file of snippetFiles) {
6576 let { snippets } = file;
6577 for (let snip of snippets) {
6583 async getAllSnippetFiles() {
6584 let { nvim } = coc_nvim_1.workspace;
6585 let opt = await nvim.eval('&rtp');
6586 let rtps = opt.split(',');
6588 for (let rtp of rtps) {
6589 let items = await this.getSnippetFileItems(path_1.default.join(rtp, 'snippets'));
6594 async getSnippetFileItems(directory) {
6596 let stat = await util_1.statAsync(directory);
6597 if (stat && stat.isDirectory()) {
6598 let files = await util_1.readdirAsync(directory);
6600 for (let f of files) {
6601 let file = path_1.default.join(directory, f);
6602 if (file.endsWith('.snippets')) {
6603 let basename = path_1.default.basename(f, '.snippets');
6604 let filetype = basename.split('-', 2)[0];
6605 res.push({ filepath: file, directory, filetype });
6608 let stat = await util_1.statAsync(file);
6609 if (stat && stat.isDirectory()) {
6610 let files = await util_1.readdirAsync(file);
6611 for (let filename of files) {
6612 if (filename.endsWith('.snippets')) {
6613 res.push({ filepath: path_1.default.join(file, filename), directory, filetype: f });
6624 exports.SnipmateProvider = SnipmateProvider;
6629 /***/ ((module) => {
6631 module.exports = require("readline");;
6635 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
6638 Object.defineProperty(exports, "__esModule", ({ value: true }));
6639 const coc_nvim_1 = __webpack_require__(1);
6640 const util_1 = __webpack_require__(35);
6641 class BaseProvider {
6642 constructor(config) {
6643 this.config = config;
6645 async checkContext(_context) {
6648 getExtendsFiletypes(filetype, exists = new Set()) {
6649 if (exists.has(filetype))
6651 let extend = this.config.extends ? this.config.extends[filetype] : null;
6652 exists.add(filetype);
6653 if (!extend || extend.length == 0)
6655 return extend.reduce((arr, curr) => {
6656 return arr.concat([curr], this.getExtendsFiletypes(curr, exists));
6659 getFiletypes(filetype) {
6660 let filetypes = [filetype];
6661 if (filetype.indexOf('.') !== -1) {
6662 filetypes.push(...filetype.split('.'));
6664 if (filetype == 'javascript.jsx')
6665 filetypes.push('javascriptreact');
6666 if (filetype == 'typescript.jsx' || filetype == 'typescript.tsx')
6667 filetypes.push('typescriptreact');
6668 let map = coc_nvim_1.workspace.env.filetypeMap;
6669 if (map && map[filetype]) {
6670 filetypes.push(map[filetype]);
6672 let extendFiletypes = filetypes.reduce((arr, curr) => {
6673 return arr.concat(this.getExtendsFiletypes(curr));
6675 filetypes.push(...extendFiletypes);
6676 filetypes.reverse();
6677 return util_1.distinct(filetypes);
6680 exports.default = BaseProvider;
6685 /***/ ((__unused_webpack_module, exports) => {
6688 /******************************************************************
6689 MIT License http://www.opensource.org/licenses/mit-license.php
6690 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
6691 *******************************************************************/
6692 Object.defineProperty(exports, "__esModule", ({ value: true }));
6694 * A very basic parser
6699 constructor(_content) {
6700 this._content = _content;
6704 return this._curr >= this._content.length;
6707 for (let i = this._curr; i <= this._content.length; i++) {
6708 let ch = this._content[i];
6709 if (!ch || /\S/.test(ch)) {
6719 return this._content[this._curr] || '';
6722 return this._content.length;
6725 return this._content.slice(this._curr + 1, this._curr + 1 + count);
6727 nextIndex(character, checkEscape = true, allowEnd = true) {
6728 if (this._curr >= this.len - 1)
6729 return allowEnd ? this.len - 1 : -1;
6730 let i = this._curr + 1;
6731 let pre = this.curr || '';
6732 while (i != this.len - 1) {
6733 let ch = this._content[i];
6734 if (ch == character && (!checkEscape || pre !== '\\')) {
6740 if (!allowEnd && i == this.len - 1 && character != this._content[i]) {
6746 return this._content[this._curr - 1] || '';
6749 while (this._curr < this._content.length) {
6750 let fine = fn(this.curr, this._curr);
6751 if (fine === false) {
6754 this._curr = this._curr + 1;
6758 let end = this._curr + count;
6759 end = Math.min(end, this.len);
6760 let str = this._content.slice(this._curr, end);
6764 // make curr to index, return contnet between curr (inclusive) and index (exclusive)
6766 if (index == this._curr)
6768 let str = this._content.slice(this._curr, index);
6773 exports.default = Parser;
6778 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
6781 var __importDefault = (this && this.__importDefault) || function (mod) {
6782 return (mod && mod.__esModule) ? mod : { "default": mod };
6784 Object.defineProperty(exports, "__esModule", ({ value: true }));
6785 exports.TextmateProvider = void 0;
6786 const coc_nvim_1 = __webpack_require__(1);
6787 const fs_1 = __importDefault(__webpack_require__(2));
6788 const jsonc_parser_1 = __webpack_require__(45);
6789 const os_1 = __importDefault(__webpack_require__(3));
6790 const path_1 = __importDefault(__webpack_require__(4));
6791 const util_1 = __importDefault(__webpack_require__(5));
6792 const vscode_languageserver_types_1 = __webpack_require__(6);
6793 const baseProvider_1 = __importDefault(__webpack_require__(42));
6794 const types_1 = __webpack_require__(39);
6795 const util_2 = __webpack_require__(35);
6796 class TextmateProvider extends baseProvider_1.default {
6797 constructor(channel, trace, config) {
6799 this.channel = channel;
6801 this._snippetCache = {};
6802 this._userSnippets = {};
6803 if (config.loadFromExtensions) {
6804 coc_nvim_1.extensions.onDidLoadExtension(extension => {
6805 this.loadSnippetsFromExtension(extension).catch(e => {
6806 channel.appendLine(`[Error] ${e.message}`);
6809 coc_nvim_1.extensions.onDidUnloadExtension(id => {
6810 delete this._snippetCache[id];
6815 if (this.config.loadFromExtensions) {
6816 for (let extension of coc_nvim_1.extensions.all) {
6817 await this.loadSnippetsFromExtension(extension);
6820 let paths = this.config.snippetsRoots;
6821 if (paths && paths.length) {
6822 for (let dir of paths) {
6823 await this.loadSnippetsFromRoot(dir);
6827 async getSnippetFiles(filetype) {
6828 let filetypes = this.getFiletypes(filetype);
6830 if (this.config.loadFromExtensions) {
6831 for (let key of Object.keys(this._snippetCache)) {
6832 let cache = this._snippetCache[key];
6833 for (let filetype of filetypes) {
6834 let snippets = cache[filetype];
6835 if (snippets && snippets.length) {
6836 filepaths.push(snippets[0].filepath);
6841 for (let filetype of filetypes) {
6842 let snippets = this._userSnippets[filetype];
6843 if (snippets && snippets.length) {
6844 for (let snip of snippets) {
6845 let { filepath } = snip;
6846 if (filepaths.indexOf(filepath) == -1) {
6847 filepaths.push(filepath);
6852 return util_2.distinct(filepaths);
6854 async getTriggerSnippets(document, position, autoTrigger) {
6857 let line = document.getline(position.line);
6858 line = line.slice(0, position.character);
6859 let snippets = await this.getSnippets(document.filetype);
6860 if (!snippets || !snippets.length)
6863 for (let snip of snippets) {
6864 let { prefix } = snip;
6865 if (!line.endsWith(prefix))
6867 let pre = line.slice(0, line.length - prefix.length);
6868 // not allowed after word
6869 if (pre.length && /\w/.test(pre[pre.length - 1]))
6873 range: vscode_languageserver_types_1.Range.create(position.line, position.character - prefix.length, position.line, position.character),
6875 location: snip.filepath,
6876 description: snip.description,
6882 async getSnippets(filetype) {
6884 let filetypes = this.getFiletypes(filetype);
6885 let added = new Set();
6886 for (let key of Object.keys(this._snippetCache)) {
6887 let cache = this._snippetCache[key];
6888 for (let filetype of filetypes) {
6889 let snippets = cache[filetype];
6891 for (let snip of snippets) {
6892 if (!added.has(snip.prefix)) {
6893 added.add(snip.prefix);
6900 for (let filetype of filetypes) {
6901 let snippets = this._userSnippets[filetype];
6902 if (snippets && snippets.length) {
6903 for (let snip of snippets) {
6904 if (!added.has(snip.prefix)) {
6905 added.add(snip.prefix);
6913 async resolveSnippetBody(snip, _range) {
6916 async loadSnippetsFromExtension(extension) {
6917 let { packageJSON } = extension;
6918 if (packageJSON.contributes && packageJSON.contributes.snippets) {
6919 let { snippets } = packageJSON.contributes;
6921 extensionId: extension.id,
6924 for (let item of snippets) {
6925 let p = path_1.default.join(extension.extensionPath, item.path);
6926 let { language } = item;
6928 languageId: language,
6932 if (snippets && snippets.length) {
6933 await this.loadSnippetsFromDefinition(def);
6937 async loadSnippetsFromRoot(root) {
6938 let { _userSnippets } = this;
6939 if (root.startsWith('~'))
6940 root = root.replace(/^~/, os_1.default.homedir());
6941 let files = await util_1.default.promisify(fs_1.default.readdir)(root, 'utf8');
6942 files = files.filter(f => f.endsWith('.json') || f.endsWith('.code-snippets'));
6943 await Promise.all(files.map(file => {
6944 file = path_1.default.join(root, file);
6945 let basename = path_1.default.basename(file, '.json');
6946 basename = basename.replace(/\.code-snippets$/, '');
6947 return this.loadSnippetsFromFile(file).then(snippets => {
6948 _userSnippets[basename] = snippets;
6952 async loadSnippetsFromDefinition(def) {
6953 let { extensionId, snippets } = def;
6954 let cache = this._snippetCache[extensionId] = {};
6955 for (let item of snippets) {
6956 let { languageId } = item;
6957 if (!fs_1.default.existsSync(item.filepath))
6959 let arr = await this.loadSnippetsFromFile(item.filepath);
6960 let exists = cache[languageId] || [];
6961 cache[languageId] = [...exists, ...arr];
6964 async loadSnippetsFromFile(snippetFilePath) {
6965 const contents = await new Promise((resolve, reject) => {
6966 fs_1.default.readFile(snippetFilePath, "utf8", (err, data) => {
6972 const snippets = this.loadSnippetsFromText(snippetFilePath, contents);
6973 this.channel.appendLine(`[Info ${(new Date()).toISOString()}] Loaded ${snippets.length} textmate snippets from ${snippetFilePath}`);
6976 loadSnippetsFromText(filepath, contents) {
6980 let snippetObject = jsonc_parser_1.parse(contents, errors, { allowTrailingComma: true });
6981 if (errors.length) {
6982 this.channel.appendLine(`[Error ${(new Date()).toLocaleDateString()}] parser error of ${filepath}: ${JSON.stringify(errors, null, 2)}`);
6984 if (snippetObject) {
6985 for (let key of Object.keys(snippetObject)) {
6986 snippets.push(snippetObject[key]);
6991 this.channel.appendLine(`[Error ${(new Date()).toLocaleDateString()}] ${ex.stack}`);
6994 const normalizedSnippets = snippets.map((snip) => {
6995 let prefix = Array.isArray(snip.prefix) ? snip.prefix[0] : snip.prefix;
6999 body: typeof snip.body === 'string' ? snip.body : snip.body.join('\n'),
7001 description: typeof snip.description === 'string' ? snip.description : typeof snip.description !== 'undefined' ? snip.description.join('\n') : '',
7002 triggerKind: types_1.TriggerKind.WordBoundary
7005 return normalizedSnippets;
7008 exports.TextmateProvider = TextmateProvider;
7013 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
7015 __webpack_require__.r(__webpack_exports__);
7016 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7017 /* harmony export */ "createScanner": () => /* binding */ createScanner,
7018 /* harmony export */ "getLocation": () => /* binding */ getLocation,
7019 /* harmony export */ "parse": () => /* binding */ parse,
7020 /* harmony export */ "parseTree": () => /* binding */ parseTree,
7021 /* harmony export */ "findNodeAtLocation": () => /* binding */ findNodeAtLocation,
7022 /* harmony export */ "findNodeAtOffset": () => /* binding */ findNodeAtOffset,
7023 /* harmony export */ "getNodePath": () => /* binding */ getNodePath,
7024 /* harmony export */ "getNodeValue": () => /* binding */ getNodeValue,
7025 /* harmony export */ "visit": () => /* binding */ visit,
7026 /* harmony export */ "stripComments": () => /* binding */ stripComments,
7027 /* harmony export */ "printParseErrorCode": () => /* binding */ printParseErrorCode,
7028 /* harmony export */ "format": () => /* binding */ format,
7029 /* harmony export */ "modify": () => /* binding */ modify,
7030 /* harmony export */ "applyEdits": () => /* binding */ applyEdits
7031 /* harmony export */ });
7032 /* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
7033 /* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48);
7034 /* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(47);
7035 /* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(49);
7036 /*---------------------------------------------------------------------------------------------
7037 * Copyright (c) Microsoft Corporation. All rights reserved.
7038 * Licensed under the MIT License. See License.txt in the project root for license information.
7039 *--------------------------------------------------------------------------------------------*/
7046 * Creates a JSON scanner on the given text.
7047 * If ignoreTrivia is set, whitespaces or comments are ignored.
7049 var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_3__.createScanner;
7051 * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
7053 var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.getLocation;
7055 * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
7056 * Therefore, always check the errors list to find out if the input was valid.
7058 var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.parse;
7060 * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
7062 var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.parseTree;
7064 * Finds the node at the given path in a JSON DOM.
7066 var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.findNodeAtLocation;
7068 * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
7070 var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.findNodeAtOffset;
7072 * Gets the JSON path of the given JSON DOM node
7074 var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.getNodePath;
7076 * Evaluates the JavaScript object of the given JSON DOM node
7078 var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.getNodeValue;
7080 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
7082 var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.visit;
7084 * Takes JSON with JavaScript-style comments and remove
7085 * them. Optionally replaces every none-newline character
7086 * of comments with a replaceCharacter
7088 var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_2__.stripComments;
7089 function printParseErrorCode(code) {
7091 case 1 /* InvalidSymbol */: return 'InvalidSymbol';
7092 case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
7093 case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
7094 case 4 /* ValueExpected */: return 'ValueExpected';
7095 case 5 /* ColonExpected */: return 'ColonExpected';
7096 case 6 /* CommaExpected */: return 'CommaExpected';
7097 case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
7098 case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
7099 case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
7100 case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
7101 case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
7102 case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
7103 case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
7104 case 14 /* InvalidUnicode */: return 'InvalidUnicode';
7105 case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
7106 case 16 /* InvalidCharacter */: return 'InvalidCharacter';
7108 return '<unknown ParseErrorCode>';
7111 * Computes the edits needed to format a JSON document.
7113 * @param documentText The input text
7114 * @param range The range to format or `undefined` to format the full content
7115 * @param options The formatting options
7116 * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
7117 * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
7118 * text in the original document. However, multiple edits can have
7119 * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
7120 * To apply edits to an input, you can use `applyEdits`.
7122 function format(documentText, range, options) {
7123 return _impl_format__WEBPACK_IMPORTED_MODULE_0__.format(documentText, range, options);
7126 * Computes the edits needed to modify a value in the JSON document.
7128 * @param documentText The input text
7129 * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
7130 * If the path points to an non-existing property or item, it will be created.
7131 * @param value The new value for the specified property or item. If the value is undefined,
7132 * the property or item will be removed.
7133 * @param options Options
7134 * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
7135 * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
7136 * text in the original document. However, multiple edits can have
7137 * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
7138 * To apply edits to an input, you can use `applyEdits`.
7140 function modify(text, path, value, options) {
7141 return _impl_edit__WEBPACK_IMPORTED_MODULE_1__.setProperty(text, path, value, options);
7144 * Applies edits to a input string.
7146 function applyEdits(text, edits) {
7147 for (var i = edits.length - 1; i >= 0; i--) {
7148 text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__.applyEdit(text, edits[i]);
7156 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
7158 __webpack_require__.r(__webpack_exports__);
7159 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7160 /* harmony export */ "format": () => /* binding */ format,
7161 /* harmony export */ "isEOL": () => /* binding */ isEOL
7162 /* harmony export */ });
7163 /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47);
7164 /*---------------------------------------------------------------------------------------------
7165 * Copyright (c) Microsoft Corporation. All rights reserved.
7166 * Licensed under the MIT License. See License.txt in the project root for license information.
7167 *--------------------------------------------------------------------------------------------*/
7170 function format(documentText, range, options) {
7171 var initialIndentLevel;
7173 var formatTextStart;
7177 rangeStart = range.offset;
7178 rangeEnd = rangeStart + range.length;
7179 formatTextStart = rangeStart;
7180 while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
7183 var endOffset = rangeEnd;
7184 while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
7187 formatText = documentText.substring(formatTextStart, endOffset);
7188 initialIndentLevel = computeIndentLevel(formatText, options);
7191 formatText = documentText;
7192 initialIndentLevel = 0;
7193 formatTextStart = 0;
7195 rangeEnd = documentText.length;
7197 var eol = getEOL(options, documentText);
7198 var lineBreak = false;
7199 var indentLevel = 0;
7201 if (options.insertSpaces) {
7202 indentValue = repeat(' ', options.tabSize || 4);
7207 var scanner = (0,_scanner__WEBPACK_IMPORTED_MODULE_0__.createScanner)(formatText, false);
7208 var hasError = false;
7209 function newLineAndIndent() {
7210 return eol + repeat(indentValue, initialIndentLevel + indentLevel);
7212 function scanNext() {
7213 var token = scanner.scan();
7215 while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
7216 lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
7217 token = scanner.scan();
7219 hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
7222 var editOperations = [];
7223 function addEdit(text, startOffset, endOffset) {
7224 if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
7225 editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
7228 var firstToken = scanNext();
7229 if (firstToken !== 17 /* EOF */) {
7230 var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
7231 var initialIndent = repeat(indentValue, initialIndentLevel);
7232 addEdit(initialIndent, formatTextStart, firstTokenStart);
7234 while (firstToken !== 17 /* EOF */) {
7235 var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
7236 var secondToken = scanNext();
7237 var replaceContent = '';
7238 while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
7239 // comments on the same line: keep them on the same line, but ignore them otherwise
7240 var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
7241 addEdit(' ', firstTokenEnd, commentTokenStart);
7242 firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
7243 replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
7244 secondToken = scanNext();
7246 if (secondToken === 2 /* CloseBraceToken */) {
7247 if (firstToken !== 1 /* OpenBraceToken */) {
7249 replaceContent = newLineAndIndent();
7252 else if (secondToken === 4 /* CloseBracketToken */) {
7253 if (firstToken !== 3 /* OpenBracketToken */) {
7255 replaceContent = newLineAndIndent();
7259 switch (firstToken) {
7260 case 3 /* OpenBracketToken */:
7261 case 1 /* OpenBraceToken */:
7263 replaceContent = newLineAndIndent();
7265 case 5 /* CommaToken */:
7266 case 12 /* LineCommentTrivia */:
7267 replaceContent = newLineAndIndent();
7269 case 13 /* BlockCommentTrivia */:
7271 replaceContent = newLineAndIndent();
7274 // symbol following comment on the same line: keep on same line, separate with ' '
7275 replaceContent = ' ';
7278 case 6 /* ColonToken */:
7279 replaceContent = ' ';
7281 case 10 /* StringLiteral */:
7282 if (secondToken === 6 /* ColonToken */) {
7283 replaceContent = '';
7287 case 7 /* NullKeyword */:
7288 case 8 /* TrueKeyword */:
7289 case 9 /* FalseKeyword */:
7290 case 11 /* NumericLiteral */:
7291 case 2 /* CloseBraceToken */:
7292 case 4 /* CloseBracketToken */:
7293 if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
7294 replaceContent = ' ';
7296 else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
7300 case 16 /* Unknown */:
7304 if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
7305 replaceContent = newLineAndIndent();
7308 var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
7309 addEdit(replaceContent, firstTokenEnd, secondTokenStart);
7310 firstToken = secondToken;
7312 return editOperations;
7314 function repeat(s, count) {
7316 for (var i = 0; i < count; i++) {
7321 function computeIndentLevel(content, options) {
7324 var tabSize = options.tabSize || 4;
7325 while (i < content.length) {
7326 var ch = content.charAt(i);
7330 else if (ch === '\t') {
7338 return Math.floor(nChars / tabSize);
7340 function getEOL(options, text) {
7341 for (var i = 0; i < text.length; i++) {
7342 var ch = text.charAt(i);
7344 if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
7349 else if (ch === '\n') {
7353 return (options && options.eol) || '\n';
7355 function isEOL(text, offset) {
7356 return '\r\n'.indexOf(text.charAt(offset)) !== -1;
7362 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
7364 __webpack_require__.r(__webpack_exports__);
7365 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7366 /* harmony export */ "createScanner": () => /* binding */ createScanner
7367 /* harmony export */ });
7368 /*---------------------------------------------------------------------------------------------
7369 * Copyright (c) Microsoft Corporation. All rights reserved.
7370 * Licensed under the MIT License. See License.txt in the project root for license information.
7371 *--------------------------------------------------------------------------------------------*/
7374 * Creates a JSON scanner on the given text.
7375 * If ignoreTrivia is set, whitespaces or comments are ignored.
7377 function createScanner(text, ignoreTrivia) {
7378 if (ignoreTrivia === void 0) { ignoreTrivia = false; }
7379 var len = text.length;
7380 var pos = 0, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
7381 function scanHexDigits(count, exact) {
7384 while (digits < count || !exact) {
7385 var ch = text.charCodeAt(pos);
7386 if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
7387 value = value * 16 + ch - 48 /* _0 */;
7389 else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
7390 value = value * 16 + ch - 65 /* A */ + 10;
7392 else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
7393 value = value * 16 + ch - 97 /* a */ + 10;
7401 if (digits < count) {
7406 function setPosition(newPosition) {
7410 token = 16 /* Unknown */;
7411 scanError = 0 /* None */;
7413 function scanNumber() {
7415 if (text.charCodeAt(pos) === 48 /* _0 */) {
7420 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
7424 if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
7426 if (pos < text.length && isDigit(text.charCodeAt(pos))) {
7428 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
7433 scanError = 3 /* UnexpectedEndOfNumber */;
7434 return text.substring(start, pos);
7438 if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
7440 if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
7443 if (pos < text.length && isDigit(text.charCodeAt(pos))) {
7445 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
7451 scanError = 3 /* UnexpectedEndOfNumber */;
7454 return text.substring(start, end);
7456 function scanString() {
7457 var result = '', start = pos;
7460 result += text.substring(start, pos);
7461 scanError = 2 /* UnexpectedEndOfString */;
7464 var ch = text.charCodeAt(pos);
7465 if (ch === 34 /* doubleQuote */) {
7466 result += text.substring(start, pos);
7470 if (ch === 92 /* backslash */) {
7471 result += text.substring(start, pos);
7474 scanError = 2 /* UnexpectedEndOfString */;
7477 var ch2 = text.charCodeAt(pos++);
7479 case 34 /* doubleQuote */:
7482 case 92 /* backslash */:
7485 case 47 /* slash */:
7504 var ch3 = scanHexDigits(4, true);
7506 result += String.fromCharCode(ch3);
7509 scanError = 4 /* InvalidUnicode */;
7513 scanError = 5 /* InvalidEscapeCharacter */;
7518 if (ch >= 0 && ch <= 0x1f) {
7519 if (isLineBreak(ch)) {
7520 result += text.substring(start, pos);
7521 scanError = 2 /* UnexpectedEndOfString */;
7525 scanError = 6 /* InvalidCharacter */;
7526 // mark as error but continue with string
7533 function scanNext() {
7535 scanError = 0 /* None */;
7537 lineStartOffset = lineNumber;
7538 prevTokenLineStartOffset = tokenLineStartOffset;
7542 return token = 17 /* EOF */;
7544 var code = text.charCodeAt(pos);
7545 // trivia: whitespace
7546 if (isWhiteSpace(code)) {
7549 value += String.fromCharCode(code);
7550 code = text.charCodeAt(pos);
7551 } while (isWhiteSpace(code));
7552 return token = 15 /* Trivia */;
7555 if (isLineBreak(code)) {
7557 value += String.fromCharCode(code);
7558 if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
7563 tokenLineStartOffset = pos;
7564 return token = 14 /* LineBreakTrivia */;
7568 case 123 /* openBrace */:
7570 return token = 1 /* OpenBraceToken */;
7571 case 125 /* closeBrace */:
7573 return token = 2 /* CloseBraceToken */;
7574 case 91 /* openBracket */:
7576 return token = 3 /* OpenBracketToken */;
7577 case 93 /* closeBracket */:
7579 return token = 4 /* CloseBracketToken */;
7580 case 58 /* colon */:
7582 return token = 6 /* ColonToken */;
7583 case 44 /* comma */:
7585 return token = 5 /* CommaToken */;
7587 case 34 /* doubleQuote */:
7589 value = scanString();
7590 return token = 10 /* StringLiteral */;
7592 case 47 /* slash */:
7593 var start = pos - 1;
7594 // Single-line comment
7595 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
7598 if (isLineBreak(text.charCodeAt(pos))) {
7603 value = text.substring(start, pos);
7604 return token = 12 /* LineCommentTrivia */;
7606 // Multi-line comment
7607 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
7609 var safeLength = len - 1; // For lookahead.
7610 var commentClosed = false;
7611 while (pos < safeLength) {
7612 var ch = text.charCodeAt(pos);
7613 if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
7615 commentClosed = true;
7619 if (isLineBreak(ch)) {
7620 if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
7624 tokenLineStartOffset = pos;
7627 if (!commentClosed) {
7629 scanError = 1 /* UnexpectedEndOfComment */;
7631 value = text.substring(start, pos);
7632 return token = 13 /* BlockCommentTrivia */;
7634 // just a single slash
7635 value += String.fromCharCode(code);
7637 return token = 16 /* Unknown */;
7639 case 45 /* minus */:
7640 value += String.fromCharCode(code);
7642 if (pos === len || !isDigit(text.charCodeAt(pos))) {
7643 return token = 16 /* Unknown */;
7645 // found a minus, followed by a number so
7646 // we fall through to proceed with scanning
7658 value += scanNumber();
7659 return token = 11 /* NumericLiteral */;
7660 // literals and unknown symbols
7662 // is a literal? Read the full word.
7663 while (pos < len && isUnknownContentCharacter(code)) {
7665 code = text.charCodeAt(pos);
7667 if (tokenOffset !== pos) {
7668 value = text.substring(tokenOffset, pos);
7669 // keywords: true, false, null
7671 case 'true': return token = 8 /* TrueKeyword */;
7672 case 'false': return token = 9 /* FalseKeyword */;
7673 case 'null': return token = 7 /* NullKeyword */;
7675 return token = 16 /* Unknown */;
7678 value += String.fromCharCode(code);
7680 return token = 16 /* Unknown */;
7683 function isUnknownContentCharacter(code) {
7684 if (isWhiteSpace(code) || isLineBreak(code)) {
7688 case 125 /* closeBrace */:
7689 case 93 /* closeBracket */:
7690 case 123 /* openBrace */:
7691 case 91 /* openBracket */:
7692 case 34 /* doubleQuote */:
7693 case 58 /* colon */:
7694 case 44 /* comma */:
7695 case 47 /* slash */:
7700 function scanNextNonTrivia() {
7703 result = scanNext();
7704 } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
7708 setPosition: setPosition,
7709 getPosition: function () { return pos; },
7710 scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
7711 getToken: function () { return token; },
7712 getTokenValue: function () { return value; },
7713 getTokenOffset: function () { return tokenOffset; },
7714 getTokenLength: function () { return pos - tokenOffset; },
7715 getTokenStartLine: function () { return lineStartOffset; },
7716 getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
7717 getTokenError: function () { return scanError; },
7720 function isWhiteSpace(ch) {
7721 return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
7722 ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
7723 ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
7725 function isLineBreak(ch) {
7726 return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
7728 function isDigit(ch) {
7729 return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
7735 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
7737 __webpack_require__.r(__webpack_exports__);
7738 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7739 /* harmony export */ "removeProperty": () => /* binding */ removeProperty,
7740 /* harmony export */ "setProperty": () => /* binding */ setProperty,
7741 /* harmony export */ "applyEdit": () => /* binding */ applyEdit,
7742 /* harmony export */ "isWS": () => /* binding */ isWS
7743 /* harmony export */ });
7744 /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
7745 /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49);
7746 /*---------------------------------------------------------------------------------------------
7747 * Copyright (c) Microsoft Corporation. All rights reserved.
7748 * Licensed under the MIT License. See License.txt in the project root for license information.
7749 *--------------------------------------------------------------------------------------------*/
7753 function removeProperty(text, path, options) {
7754 return setProperty(text, path, void 0, options);
7756 function setProperty(text, originalPath, value, options) {
7758 var path = originalPath.slice();
7760 var root = (0,_parser__WEBPACK_IMPORTED_MODULE_1__.parseTree)(text, errors);
7761 var parent = void 0;
7762 var lastSegment = void 0;
7763 while (path.length > 0) {
7764 lastSegment = path.pop();
7765 parent = (0,_parser__WEBPACK_IMPORTED_MODULE_1__.findNodeAtLocation)(root, path);
7766 if (parent === void 0 && value !== void 0) {
7767 if (typeof lastSegment === 'string') {
7768 value = (_a = {}, _a[lastSegment] = value, _a);
7780 if (value === void 0) { // delete
7781 throw new Error('Can not delete in empty document');
7783 return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
7785 else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
7786 var existing = (0,_parser__WEBPACK_IMPORTED_MODULE_1__.findNodeAtLocation)(parent, [lastSegment]);
7787 if (existing !== void 0) {
7788 if (value === void 0) { // delete
7789 if (!existing.parent) {
7790 throw new Error('Malformed AST');
7792 var propertyIndex = parent.children.indexOf(existing.parent);
7793 var removeBegin = void 0;
7794 var removeEnd = existing.parent.offset + existing.parent.length;
7795 if (propertyIndex > 0) {
7796 // remove the comma of the previous node
7797 var previous = parent.children[propertyIndex - 1];
7798 removeBegin = previous.offset + previous.length;
7801 removeBegin = parent.offset + 1;
7802 if (parent.children.length > 1) {
7803 // remove the comma of the next node
7804 var next = parent.children[1];
7805 removeEnd = next.offset;
7808 return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);
7811 // set value of existing property
7812 return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
7816 if (value === void 0) { // delete
7817 return []; // property does not exist, nothing to do
7819 var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
7820 var index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
7823 var previous = parent.children[index - 1];
7824 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
7826 else if (parent.children.length === 0) {
7827 edit = { offset: parent.offset + 1, length: 0, content: newProperty };
7830 edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
7832 return withFormatting(text, edit, options);
7835 else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
7836 var insertIndex = lastSegment;
7837 if (insertIndex === -1) {
7839 var newProperty = "" + JSON.stringify(value);
7841 if (parent.children.length === 0) {
7842 edit = { offset: parent.offset + 1, length: 0, content: newProperty };
7845 var previous = parent.children[parent.children.length - 1];
7846 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
7848 return withFormatting(text, edit, options);
7850 else if (value === void 0 && parent.children.length >= 0) {
7852 var removalIndex = lastSegment;
7853 var toRemove = parent.children[removalIndex];
7855 if (parent.children.length === 1) {
7857 edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
7859 else if (parent.children.length - 1 === removalIndex) {
7861 var previous = parent.children[removalIndex - 1];
7862 var offset = previous.offset + previous.length;
7863 var parentEndOffset = parent.offset + parent.length;
7864 edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
7867 edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
7869 return withFormatting(text, edit, options);
7871 else if (value !== void 0) {
7873 var newProperty = "" + JSON.stringify(value);
7874 if (!options.isArrayInsertion && parent.children.length > lastSegment) {
7875 var toModify = parent.children[lastSegment];
7876 edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
7878 else if (parent.children.length === 0 || lastSegment === 0) {
7879 edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };
7882 var index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
7883 var previous = parent.children[index - 1];
7884 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
7886 return withFormatting(text, edit, options);
7889 throw new Error("Can not " + (value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')) + " Array index " + insertIndex + " as length is not sufficient");
7893 throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
7896 function withFormatting(text, edit, options) {
7897 if (!options.formattingOptions) {
7901 var newText = applyEdit(text, edit);
7902 // format the new text
7903 var begin = edit.offset;
7904 var end = edit.offset + edit.content.length;
7905 if (edit.length === 0 || edit.content.length === 0) { // insert or remove
7906 while (begin > 0 && !(0,_format__WEBPACK_IMPORTED_MODULE_0__.isEOL)(newText, begin - 1)) {
7909 while (end < newText.length && !(0,_format__WEBPACK_IMPORTED_MODULE_0__.isEOL)(newText, end)) {
7913 var edits = (0,_format__WEBPACK_IMPORTED_MODULE_0__.format)(newText, { offset: begin, length: end - begin }, options.formattingOptions);
7914 // apply the formatting edits and track the begin and end offsets of the changes
7915 for (var i = edits.length - 1; i >= 0; i--) {
7916 var edit_1 = edits[i];
7917 newText = applyEdit(newText, edit_1);
7918 begin = Math.min(begin, edit_1.offset);
7919 end = Math.max(end, edit_1.offset + edit_1.length);
7920 end += edit_1.content.length - edit_1.length;
7922 // create a single edit with all changes
7923 var editLength = text.length - (newText.length - end) - begin;
7924 return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
7926 function applyEdit(text, edit) {
7927 return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
7929 function isWS(text, offset) {
7930 return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
7936 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
7938 __webpack_require__.r(__webpack_exports__);
7939 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7940 /* harmony export */ "getLocation": () => /* binding */ getLocation,
7941 /* harmony export */ "parse": () => /* binding */ parse,
7942 /* harmony export */ "parseTree": () => /* binding */ parseTree,
7943 /* harmony export */ "findNodeAtLocation": () => /* binding */ findNodeAtLocation,
7944 /* harmony export */ "getNodePath": () => /* binding */ getNodePath,
7945 /* harmony export */ "getNodeValue": () => /* binding */ getNodeValue,
7946 /* harmony export */ "contains": () => /* binding */ contains,
7947 /* harmony export */ "findNodeAtOffset": () => /* binding */ findNodeAtOffset,
7948 /* harmony export */ "visit": () => /* binding */ visit,
7949 /* harmony export */ "stripComments": () => /* binding */ stripComments,
7950 /* harmony export */ "getNodeType": () => /* binding */ getNodeType
7951 /* harmony export */ });
7952 /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47);
7953 /*---------------------------------------------------------------------------------------------
7954 * Copyright (c) Microsoft Corporation. All rights reserved.
7955 * Licensed under the MIT License. See License.txt in the project root for license information.
7956 *--------------------------------------------------------------------------------------------*/
7960 (function (ParseOptions) {
7961 ParseOptions.DEFAULT = {
7962 allowTrailingComma: false
7964 })(ParseOptions || (ParseOptions = {}));
7966 * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
7968 function getLocation(text, position) {
7969 var segments = []; // strings or numbers
7970 var earlyReturnException = new Object();
7971 var previousNode = undefined;
7972 var previousNodeInst = {
7979 var isAtPropertyKey = false;
7980 function setPreviousNode(value, offset, length, type) {
7981 previousNodeInst.value = value;
7982 previousNodeInst.offset = offset;
7983 previousNodeInst.length = length;
7984 previousNodeInst.type = type;
7985 previousNodeInst.colonOffset = undefined;
7986 previousNode = previousNodeInst;
7990 onObjectBegin: function (offset, length) {
7991 if (position <= offset) {
7992 throw earlyReturnException;
7994 previousNode = undefined;
7995 isAtPropertyKey = position > offset;
7996 segments.push(''); // push a placeholder (will be replaced)
7998 onObjectProperty: function (name, offset, length) {
7999 if (position < offset) {
8000 throw earlyReturnException;
8002 setPreviousNode(name, offset, length, 'property');
8003 segments[segments.length - 1] = name;
8004 if (position <= offset + length) {
8005 throw earlyReturnException;
8008 onObjectEnd: function (offset, length) {
8009 if (position <= offset) {
8010 throw earlyReturnException;
8012 previousNode = undefined;
8015 onArrayBegin: function (offset, length) {
8016 if (position <= offset) {
8017 throw earlyReturnException;
8019 previousNode = undefined;
8022 onArrayEnd: function (offset, length) {
8023 if (position <= offset) {
8024 throw earlyReturnException;
8026 previousNode = undefined;
8029 onLiteralValue: function (value, offset, length) {
8030 if (position < offset) {
8031 throw earlyReturnException;
8033 setPreviousNode(value, offset, length, getNodeType(value));
8034 if (position <= offset + length) {
8035 throw earlyReturnException;
8038 onSeparator: function (sep, offset, length) {
8039 if (position <= offset) {
8040 throw earlyReturnException;
8042 if (sep === ':' && previousNode && previousNode.type === 'property') {
8043 previousNode.colonOffset = offset;
8044 isAtPropertyKey = false;
8045 previousNode = undefined;
8047 else if (sep === ',') {
8048 var last = segments[segments.length - 1];
8049 if (typeof last === 'number') {
8050 segments[segments.length - 1] = last + 1;
8053 isAtPropertyKey = true;
8054 segments[segments.length - 1] = '';
8056 previousNode = undefined;
8062 if (e !== earlyReturnException) {
8068 previousNode: previousNode,
8069 isAtPropertyKey: isAtPropertyKey,
8070 matches: function (pattern) {
8072 for (var i = 0; k < pattern.length && i < segments.length; i++) {
8073 if (pattern[k] === segments[i] || pattern[k] === '*') {
8076 else if (pattern[k] !== '**') {
8080 return k === pattern.length;
8085 * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
8086 * Therefore always check the errors list to find out if the input was valid.
8088 function parse(text, errors, options) {
8089 if (errors === void 0) { errors = []; }
8090 if (options === void 0) { options = ParseOptions.DEFAULT; }
8091 var currentProperty = null;
8092 var currentParent = [];
8093 var previousParents = [];
8094 function onValue(value) {
8095 if (Array.isArray(currentParent)) {
8096 currentParent.push(value);
8098 else if (currentProperty !== null) {
8099 currentParent[currentProperty] = value;
8103 onObjectBegin: function () {
8106 previousParents.push(currentParent);
8107 currentParent = object;
8108 currentProperty = null;
8110 onObjectProperty: function (name) {
8111 currentProperty = name;
8113 onObjectEnd: function () {
8114 currentParent = previousParents.pop();
8116 onArrayBegin: function () {
8119 previousParents.push(currentParent);
8120 currentParent = array;
8121 currentProperty = null;
8123 onArrayEnd: function () {
8124 currentParent = previousParents.pop();
8126 onLiteralValue: onValue,
8127 onError: function (error, offset, length) {
8128 errors.push({ error: error, offset: offset, length: length });
8131 visit(text, visitor, options);
8132 return currentParent[0];
8135 * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
8137 function parseTree(text, errors, options) {
8138 if (errors === void 0) { errors = []; }
8139 if (options === void 0) { options = ParseOptions.DEFAULT; }
8140 var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root
8141 function ensurePropertyComplete(endOffset) {
8142 if (currentParent.type === 'property') {
8143 currentParent.length = endOffset - currentParent.offset;
8144 currentParent = currentParent.parent;
8147 function onValue(valueNode) {
8148 currentParent.children.push(valueNode);
8152 onObjectBegin: function (offset) {
8153 currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
8155 onObjectProperty: function (name, offset, length) {
8156 currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
8157 currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
8159 onObjectEnd: function (offset, length) {
8160 ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete
8161 currentParent.length = offset + length - currentParent.offset;
8162 currentParent = currentParent.parent;
8163 ensurePropertyComplete(offset + length);
8165 onArrayBegin: function (offset, length) {
8166 currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
8168 onArrayEnd: function (offset, length) {
8169 currentParent.length = offset + length - currentParent.offset;
8170 currentParent = currentParent.parent;
8171 ensurePropertyComplete(offset + length);
8173 onLiteralValue: function (value, offset, length) {
8174 onValue({ type: getNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
8175 ensurePropertyComplete(offset + length);
8177 onSeparator: function (sep, offset, length) {
8178 if (currentParent.type === 'property') {
8180 currentParent.colonOffset = offset;
8182 else if (sep === ',') {
8183 ensurePropertyComplete(offset);
8187 onError: function (error, offset, length) {
8188 errors.push({ error: error, offset: offset, length: length });
8191 visit(text, visitor, options);
8192 var result = currentParent.children[0];
8194 delete result.parent;
8199 * Finds the node at the given path in a JSON DOM.
8201 function findNodeAtLocation(root, path) {
8206 for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
8207 var segment = path_1[_i];
8208 if (typeof segment === 'string') {
8209 if (node.type !== 'object' || !Array.isArray(node.children)) {
8213 for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
8214 var propertyNode = _b[_a];
8215 if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
8216 node = propertyNode.children[1];
8226 var index = segment;
8227 if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
8230 node = node.children[index];
8236 * Gets the JSON path of the given JSON DOM node
8238 function getNodePath(node) {
8239 if (!node.parent || !node.parent.children) {
8242 var path = getNodePath(node.parent);
8243 if (node.parent.type === 'property') {
8244 var key = node.parent.children[0].value;
8247 else if (node.parent.type === 'array') {
8248 var index = node.parent.children.indexOf(node);
8256 * Evaluates the JavaScript object of the given JSON DOM node
8258 function getNodeValue(node) {
8259 switch (node.type) {
8261 return node.children.map(getNodeValue);
8263 var obj = Object.create(null);
8264 for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
8266 var valueNode = prop.children[1];
8268 obj[prop.children[0].value] = getNodeValue(valueNode);
8281 function contains(node, offset, includeRightBound) {
8282 if (includeRightBound === void 0) { includeRightBound = false; }
8283 return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
8286 * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
8288 function findNodeAtOffset(node, offset, includeRightBound) {
8289 if (includeRightBound === void 0) { includeRightBound = false; }
8290 if (contains(node, offset, includeRightBound)) {
8291 var children = node.children;
8292 if (Array.isArray(children)) {
8293 for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
8294 var item = findNodeAtOffset(children[i], offset, includeRightBound);
8305 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
8307 function visit(text, visitor, options) {
8308 if (options === void 0) { options = ParseOptions.DEFAULT; }
8309 var _scanner = (0,_scanner__WEBPACK_IMPORTED_MODULE_0__.createScanner)(text, false);
8310 function toNoArgVisit(visitFunction) {
8311 return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
8313 function toOneArgVisit(visitFunction) {
8314 return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
8316 var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
8317 var disallowComments = options && options.disallowComments;
8318 var allowTrailingComma = options && options.allowTrailingComma;
8319 function scanNext() {
8321 var token = _scanner.scan();
8322 switch (_scanner.getTokenError()) {
8323 case 4 /* InvalidUnicode */:
8324 handleError(14 /* InvalidUnicode */);
8326 case 5 /* InvalidEscapeCharacter */:
8327 handleError(15 /* InvalidEscapeCharacter */);
8329 case 3 /* UnexpectedEndOfNumber */:
8330 handleError(13 /* UnexpectedEndOfNumber */);
8332 case 1 /* UnexpectedEndOfComment */:
8333 if (!disallowComments) {
8334 handleError(11 /* UnexpectedEndOfComment */);
8337 case 2 /* UnexpectedEndOfString */:
8338 handleError(12 /* UnexpectedEndOfString */);
8340 case 6 /* InvalidCharacter */:
8341 handleError(16 /* InvalidCharacter */);
8345 case 12 /* LineCommentTrivia */:
8346 case 13 /* BlockCommentTrivia */:
8347 if (disallowComments) {
8348 handleError(10 /* InvalidCommentToken */);
8354 case 16 /* Unknown */:
8355 handleError(1 /* InvalidSymbol */);
8357 case 15 /* Trivia */:
8358 case 14 /* LineBreakTrivia */:
8365 function handleError(error, skipUntilAfter, skipUntil) {
8366 if (skipUntilAfter === void 0) { skipUntilAfter = []; }
8367 if (skipUntil === void 0) { skipUntil = []; }
8369 if (skipUntilAfter.length + skipUntil.length > 0) {
8370 var token = _scanner.getToken();
8371 while (token !== 17 /* EOF */) {
8372 if (skipUntilAfter.indexOf(token) !== -1) {
8376 else if (skipUntil.indexOf(token) !== -1) {
8383 function parseString(isValue) {
8384 var value = _scanner.getTokenValue();
8386 onLiteralValue(value);
8389 onObjectProperty(value);
8394 function parseLiteral() {
8395 switch (_scanner.getToken()) {
8396 case 11 /* NumericLiteral */:
8397 var tokenValue = _scanner.getTokenValue();
8398 var value = Number(tokenValue);
8400 handleError(2 /* InvalidNumberFormat */);
8403 onLiteralValue(value);
8405 case 7 /* NullKeyword */:
8406 onLiteralValue(null);
8408 case 8 /* TrueKeyword */:
8409 onLiteralValue(true);
8411 case 9 /* FalseKeyword */:
8412 onLiteralValue(false);
8420 function parseProperty() {
8421 if (_scanner.getToken() !== 10 /* StringLiteral */) {
8422 handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
8426 if (_scanner.getToken() === 6 /* ColonToken */) {
8428 scanNext(); // consume colon
8429 if (!parseValue()) {
8430 handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
8434 handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
8438 function parseObject() {
8440 scanNext(); // consume open brace
8441 var needsComma = false;
8442 while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
8443 if (_scanner.getToken() === 5 /* CommaToken */) {
8445 handleError(4 /* ValueExpected */, [], []);
8448 scanNext(); // consume comma
8449 if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
8453 else if (needsComma) {
8454 handleError(6 /* CommaExpected */, [], []);
8456 if (!parseProperty()) {
8457 handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
8462 if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
8463 handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
8466 scanNext(); // consume close brace
8470 function parseArray() {
8472 scanNext(); // consume open bracket
8473 var needsComma = false;
8474 while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
8475 if (_scanner.getToken() === 5 /* CommaToken */) {
8477 handleError(4 /* ValueExpected */, [], []);
8480 scanNext(); // consume comma
8481 if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
8485 else if (needsComma) {
8486 handleError(6 /* CommaExpected */, [], []);
8488 if (!parseValue()) {
8489 handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
8494 if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
8495 handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
8498 scanNext(); // consume close bracket
8502 function parseValue() {
8503 switch (_scanner.getToken()) {
8504 case 3 /* OpenBracketToken */:
8505 return parseArray();
8506 case 1 /* OpenBraceToken */:
8507 return parseObject();
8508 case 10 /* StringLiteral */:
8509 return parseString(true);
8511 return parseLiteral();
8515 if (_scanner.getToken() === 17 /* EOF */) {
8516 if (options.allowEmptyContent) {
8519 handleError(4 /* ValueExpected */, [], []);
8522 if (!parseValue()) {
8523 handleError(4 /* ValueExpected */, [], []);
8526 if (_scanner.getToken() !== 17 /* EOF */) {
8527 handleError(9 /* EndOfFileExpected */, [], []);
8532 * Takes JSON with JavaScript-style comments and remove
8533 * them. Optionally replaces every none-newline character
8534 * of comments with a replaceCharacter
8536 function stripComments(text, replaceCh) {
8537 var _scanner = (0,_scanner__WEBPACK_IMPORTED_MODULE_0__.createScanner)(text), parts = [], kind, offset = 0, pos;
8539 pos = _scanner.getPosition();
8540 kind = _scanner.scan();
8542 case 12 /* LineCommentTrivia */:
8543 case 13 /* BlockCommentTrivia */:
8545 if (offset !== pos) {
8546 parts.push(text.substring(offset, pos));
8548 if (replaceCh !== undefined) {
8549 parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
8551 offset = _scanner.getPosition();
8554 } while (kind !== 17 /* EOF */);
8555 return parts.join('');
8557 function getNodeType(value) {
8558 switch (typeof value) {
8559 case 'boolean': return 'boolean';
8560 case 'number': return 'number';
8561 case 'string': return 'string';
8566 else if (Array.isArray(value)) {
8571 default: return 'null';
8578 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
8581 var __importDefault = (this && this.__importDefault) || function (mod) {
8582 return (mod && mod.__esModule) ? mod : { "default": mod };
8584 Object.defineProperty(exports, "__esModule", ({ value: true }));
8585 exports.UltiSnippetsProvider = void 0;
8586 /******************************************************************
8587 MIT License http://www.opensource.org/licenses/mit-license.php
8588 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
8589 *******************************************************************/
8590 const coc_nvim_1 = __webpack_require__(1);
8591 const fs_1 = __importDefault(__webpack_require__(2));
8592 const os_1 = __importDefault(__webpack_require__(3));
8593 const path_1 = __importDefault(__webpack_require__(4));
8594 const vscode_languageserver_types_1 = __webpack_require__(6);
8595 const baseProvider_1 = __importDefault(__webpack_require__(42));
8596 const types_1 = __webpack_require__(39);
8597 const ultisnipsParser_1 = __importDefault(__webpack_require__(51));
8598 const util_1 = __webpack_require__(35);
8599 const pythonCodes = new Map();
8600 class UltiSnippetsProvider extends baseProvider_1.default {
8601 constructor(channel, trace, config, context) {
8603 this.channel = channel;
8605 this.config = config;
8606 this.context = context;
8607 this.snippetFiles = [];
8608 this.disposables = [];
8609 this.directories = [];
8610 this.runtimeDirs = [];
8611 this.runtimeDirs = coc_nvim_1.workspace.env.runtimepath.split(',');
8612 coc_nvim_1.workspace.watchOption('runtimepath', async (_, newValue) => {
8613 let parts = newValue.split(',');
8614 let subFolders = await this.getSubFolders();
8616 for (let dir of parts) {
8617 if (this.runtimeDirs.indexOf(dir) == -1) {
8618 this.runtimeDirs.push(dir);
8619 let res = await this.getSnippetsFromPlugin(dir, subFolders);
8624 await Promise.all(items.map(({ filepath, directory, filetype }) => {
8625 return this.loadSnippetsFromFile(filetype, directory, filepath);
8627 let files = items.map(o => o.filepath);
8628 let pythonCode = '';
8629 for (let file of files) {
8630 let code = pythonCodes.get(file);
8632 pythonCode += `# ${file}\n` + code + '\n';
8636 pythonCodes.clear();
8637 await this.executePythonCode(pythonCode);
8640 }, this.disposables);
8642 checkLoaded(filepath) {
8643 return this.snippetFiles.findIndex(o => o.filepath == filepath) !== -1;
8646 let { nvim, env } = coc_nvim_1.workspace;
8647 let { runtimepath } = env;
8648 let { config } = this;
8649 for (let dir of config.directories) {
8650 if (dir.startsWith('~') || dir.indexOf('$') !== -1) {
8651 let res = await coc_nvim_1.workspace.nvim.call('expand', [dir]);
8652 this.directories.push(res);
8655 this.directories.push(dir);
8658 this.channel.appendLine(`[Info ${(new Date()).toISOString()}] Using ultisnips directories: ${this.directories.join(' ')}`);
8659 let hasPythonx = await nvim.call('has', ['pythonx']);
8660 let pythonCode = await util_1.readFileAsync(this.context.asAbsolutePath('python/ultisnips.py'), 'utf8');
8661 if (hasPythonx && config.usePythonx) {
8662 this.pyMethod = 'pyx';
8665 this.pyMethod = config.pythonVersion == 3 ? 'py3' : 'py';
8667 this.channel.appendLine(`[Info ${(new Date()).toLocaleTimeString()}] Using ultisnips python command: ${this.pyMethod}`);
8668 this.parser = new ultisnipsParser_1.default(this.pyMethod, this.channel, this.trace);
8669 let arr = await this.getAllSnippetFiles(runtimepath);
8670 let files = arr.map(o => o.filepath);
8671 await Promise.all(arr.map(({ filepath, directory, filetype }) => {
8672 return this.loadSnippetsFromFile(filetype, directory, filepath);
8674 for (let file of files) {
8675 let code = pythonCodes.get(file);
8677 pythonCode += `\n# ${file}\n` + code + '\n';
8680 await this.executePythonCode(pythonCode);
8681 coc_nvim_1.workspace.onDidSaveTextDocument(async (doc) => {
8682 let uri = coc_nvim_1.Uri.parse(doc.uri);
8683 if (uri.scheme != 'file' || !doc.uri.endsWith('.snippets'))
8685 let filepath = uri.fsPath;
8686 if (!fs_1.default.existsSync(filepath))
8688 let snippetFile = this.snippetFiles.find(s => s.filepath == filepath);
8690 await this.loadSnippetsFromFile(snippetFile.filetype, snippetFile.directory, filepath);
8693 let filetype = path_1.default.basename(filepath, '.snippets');
8694 await this.loadSnippetsFromFile(filetype, path_1.default.dirname(filepath), filepath);
8696 }, null, this.disposables);
8698 async loadSnippetsFromFile(filetype, directory, filepath) {
8699 let { snippets, pythonCode, extendFiletypes, clearsnippets } = await this.parser.parseUltisnipsFile(filepath);
8700 let idx = this.snippetFiles.findIndex(o => o.filepath == filepath);
8702 this.snippetFiles.splice(idx, 1);
8703 this.snippetFiles.push({
8711 if (extendFiletypes) {
8712 let filetypes = this.config.extends[filetype] || [];
8713 filetypes = filetypes.concat(extendFiletypes);
8714 this.config.extends[filetype] = util_1.distinct(filetypes);
8716 this.channel.appendLine(`[Info ${(new Date()).toISOString()}] Loaded ${snippets.length} UltiSnip snippets from: ${filepath}`);
8717 pythonCodes.set(filepath, pythonCode);
8719 async resolveSnippetBody(snippet, range, line) {
8720 let { nvim } = coc_nvim_1.workspace;
8721 let { body, context, originRegex } = snippet;
8722 let buf = await nvim.buffer;
8723 let filepath = await buf.name;
8724 let indentCount = await nvim.call('indent', '.');
8725 let ind = ' '.repeat(indentCount);
8726 if (body.indexOf('`!p') !== -1) {
8727 let values = new Map();
8728 let re = /\$\{(\d+)(?::([^}]+))?\}/g;
8730 // tslint:disable-next-line: no-conditional-assignment
8731 while (r = re.exec(body)) {
8732 let idx = parseInt(r[1], 10);
8733 let val = r[2] || '';
8734 let exists = values.get(idx);
8735 if (exists == null || (val && exists == "''")) {
8736 if (/^`!\w/.test(val) && val.endsWith('`')) {
8737 let code = val.slice(1).slice(0, -1);
8738 // not execute python code since we don't have snip yet.
8739 if (code.startsWith('!p')) {
8743 val = await this.parser.execute(code, this.pyMethod, ind);
8746 val = val.replace(/'/g, "\\'").replace(/\n/g, '\\n');
8747 values.set(idx, "'" + val + "'");
8751 // tslint:disable-next-line: no-conditional-assignment
8752 while (r = re.exec(body)) {
8753 let idx = parseInt(r[1], 10);
8754 if (!values.has(idx)) {
8755 values.set(idx, "''");
8758 let len = values.size == 0 ? 0 : Math.max.apply(null, Array.from(values.keys()));
8759 let vals = (new Array(len)).fill('""');
8760 for (let [idx, val] of values.entries()) {
8764 pyCodes.push('import re, os, vim, string, random');
8765 pyCodes.push(`t = ('', ${vals.join(',')})`);
8766 pyCodes.push(`fn = '${path_1.default.basename(filepath)}'`);
8767 pyCodes.push(`path = '${filepath}'`);
8769 pyCodes.push(`snip = ContextSnippet()`);
8770 pyCodes.push(`context = ${context}`);
8773 pyCodes.push(`context = {}`);
8775 let start = `(${range.start.line},${Buffer.byteLength(line.slice(0, range.start.character))})`;
8776 let end = `(${range.end.line},${Buffer.byteLength(line.slice(0, range.end.character))})`;
8777 pyCodes.push(`snip = SnippetUtil('${ind}', ${start}, ${end}, context)`);
8779 pyCodes.push(`pattern = re.compile(r"${originRegex.replace(/"/g, '\\"')}")`);
8780 pyCodes.push(`match = pattern.search("${line.replace(/"/g, '\\"')}")`);
8783 await nvim.command(`${this.pyMethod} ${pyCodes.join('\n')}`);
8786 this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}]: ${e.message}`);
8787 this.channel.appendLine(`code: ${pyCodes.join('\n')}`);
8790 return this.parser.resolveUltisnipsBody(body);
8792 async checkContext(context) {
8793 let { nvim } = coc_nvim_1.workspace;
8795 pyCodes.push('import re, os, vim, string, random');
8796 pyCodes.push(`snip = ContextSnippet()`);
8797 pyCodes.push(`context = ${context}`);
8798 await nvim.command(`${this.pyMethod} ${pyCodes.join('\n')}`);
8799 let res = await nvim.call(`${this.pyMethod}eval`, 'True if context else False');
8802 async getTriggerSnippets(document, position, autoTrigger) {
8803 let snippets = await this.getSnippets(document.filetype);
8804 let line = document.getline(position.line);
8805 line = line.slice(0, position.character);
8806 if (!line || line[line.length - 1] == ' ')
8808 snippets = snippets.filter(s => {
8809 let { prefix, regex } = s;
8810 if (autoTrigger && !s.autoTrigger)
8813 let ms = line.match(regex);
8818 if (!line.endsWith(prefix))
8820 if (s.triggerKind == types_1.TriggerKind.InWord)
8822 let pre = line.slice(0, line.length - prefix.length);
8823 if (s.triggerKind == types_1.TriggerKind.LineBegin)
8824 return pre.trim() == '';
8825 if (s.triggerKind == types_1.TriggerKind.SpaceBefore)
8826 return pre.length == 0 || /\s/.test(pre[pre.length - 1]);
8827 if (s.triggerKind == types_1.TriggerKind.WordBoundary)
8828 return pre.length == 0 || !document.isWord(pre[pre.length - 1]);
8831 snippets.sort((a, b) => {
8832 if (a.context && !b.context)
8834 if (b.context && !a.context)
8839 let contextPrefixes = [];
8840 for (let s of snippets) {
8843 let valid = await this.checkContext(s.context);
8846 contextPrefixes.push(s.context);
8848 else if (contextPrefixes.indexOf(s.prefix) !== -1) {
8851 if (s.regex == null) {
8852 character = position.character - s.prefix.length;
8855 let len = line.match(s.regex)[0].length;
8856 character = position.character - len;
8858 let range = vscode_languageserver_types_1.Range.create(position.line, character, position.line, position.character);
8859 let newText = await this.resolveSnippetBody(s, range, line);
8862 description: s.description,
8863 location: s.filepath,
8864 priority: s.priority,
8871 async getSnippetFiles(filetype) {
8872 let filetypes = this.getFiletypes(filetype);
8874 for (let s of this.snippetFiles) {
8875 if (filetypes.indexOf(s.filetype) !== -1) {
8876 res.push(s.filepath);
8881 async getSnippets(filetype) {
8882 let filetypes = this.getFiletypes(filetype);
8883 filetypes.push('all');
8884 let snippetFiles = this.snippetFiles.filter(o => filetypes.indexOf(o.filetype) !== -1);
8887 snippetFiles.sort((a, b) => {
8888 if (a.filetype == b.filetype)
8890 if (a.filetype == filetype)
8894 for (let file of snippetFiles) {
8895 let { snippets, clearsnippets } = file;
8896 if (typeof clearsnippets == 'number') {
8897 min = min ? Math.max(min, clearsnippets) : clearsnippets;
8899 for (let snip of snippets) {
8900 if (snip.regex || snip.context) {
8904 let idx = result.findIndex(o => o.prefix == snip.prefix && o.triggerKind == snip.triggerKind);
8909 let item = result[idx];
8910 if (snip.priority > item.priority) {
8918 result = result.filter(o => o.priority >= min);
8919 result.sort((a, b) => {
8920 if (a.context && !b.context)
8922 if (b.context && !a.context)
8928 async getAllSnippetFiles(runtimepath) {
8929 let { directories } = this;
8931 for (let directory of directories) {
8932 if (path_1.default.isAbsolute(directory)) {
8933 let items = await this.getSnippetFileItems(directory);
8937 let subFolders = await this.getSubFolders();
8938 let rtps = runtimepath.split(',');
8939 this.runtimeDirs = rtps;
8940 for (let rtp of rtps) {
8941 let items = await this.getSnippetsFromPlugin(rtp, subFolders);
8946 async getSubFolders() {
8947 let { directories } = this;
8948 directories = directories.filter(s => !path_1.default.isAbsolute(s));
8949 // use UltiSnipsSnippetDirectories
8950 let dirs = await coc_nvim_1.workspace.nvim.eval('get(g:, "UltiSnipsSnippetDirectories", [])');
8951 for (let dir of dirs) {
8952 if (directories.indexOf(dir) == -1) {
8953 directories.push(dir);
8958 async getSnippetsFromPlugin(directory, subFolders) {
8960 for (let folder of subFolders) {
8961 let items = await this.getSnippetFileItems(path_1.default.join(directory, folder));
8966 async getSnippetFileItems(directory) {
8968 let stat = await util_1.statAsync(directory);
8969 if (stat && stat.isDirectory()) {
8970 let files = await util_1.readdirAsync(directory);
8972 for (let f of files) {
8973 let file = path_1.default.join(directory, f);
8974 if (file.endsWith('.snippets')) {
8975 let basename = path_1.default.basename(f, '.snippets');
8976 let filetype = basename.split('_', 2)[0];
8977 res.push({ filepath: file, directory, filetype });
8980 let stat = await util_1.statAsync(file);
8981 if (stat && stat.isDirectory()) {
8982 let files = await util_1.readdirAsync(file);
8983 for (let filename of files) {
8984 if (filename.endsWith('.snippets')) {
8985 res.push({ filepath: path_1.default.join(file, filename), directory, filetype: f });
8995 async executePythonCode(pythonCode) {
8997 let dir = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`);
8998 if (!fs_1.default.existsSync(dir))
8999 fs_1.default.mkdirSync(dir);
9000 let tmpfile = path_1.default.join(os_1.default.tmpdir(), `coc.nvim-${process.pid}`, `coc-ultisnips-${util_1.uid()}.py`);
9001 fs_1.default.writeFileSync(tmpfile, '# -*- coding: utf-8 -*-\n' + pythonCode, 'utf8');
9002 await coc_nvim_1.workspace.nvim.command(`exe '${this.pyMethod}file '.fnameescape('${tmpfile}')`);
9003 pythonCodes.clear();
9006 this.channel.appendLine(`Error on execute python script:`);
9007 this.channel.append(e.message);
9008 coc_nvim_1.workspace.showMessage(`Error on execute python script: ${e.message}`, 'error');
9012 coc_nvim_1.disposeAll(this.disposables);
9015 exports.UltiSnippetsProvider = UltiSnippetsProvider;
9020 /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
9023 var __importDefault = (this && this.__importDefault) || function (mod) {
9024 return (mod && mod.__esModule) ? mod : { "default": mod };
9026 Object.defineProperty(exports, "__esModule", ({ value: true }));
9027 /******************************************************************
9028 MIT License http://www.opensource.org/licenses/mit-license.php
9029 Author Qiming Zhao <chemzqm@gmail> (https://github.com/chemzqm)
9030 *******************************************************************/
9031 const child_process_1 = __webpack_require__(52);
9032 const coc_nvim_1 = __webpack_require__(1);
9033 const fs_1 = __importDefault(__webpack_require__(2));
9034 const pify_1 = __importDefault(__webpack_require__(36));
9035 const readline_1 = __importDefault(__webpack_require__(41));
9036 const parser_1 = __importDefault(__webpack_require__(43));
9037 const types_1 = __webpack_require__(39);
9038 const util_1 = __webpack_require__(35);
9039 class UltiSnipsParser {
9040 constructor(pyMethod, channel, trace = 'error') {
9041 this.pyMethod = pyMethod;
9042 this.channel = channel;
9045 parseUltisnipsFile(filepath) {
9046 const rl = readline_1.default.createInterface({
9047 input: fs_1.default.createReadStream(filepath, 'utf8'),
9057 let clearsnippets = null;
9058 let parsedContext = null;
9059 let extendFiletypes = [];
9060 rl.on('line', line => {
9062 if (!block && (line.startsWith('#') || line.length == 0))
9064 const [head, tail] = util_1.headTail(line);
9068 let n = parseInt(tail.trim(), 10);
9073 let fts = tail.trim().split(/,\s+/);
9074 for (let ft of fts) {
9075 if (extendFiletypes.indexOf(ft) == -1) {
9076 extendFiletypes.push(ft);
9080 case 'clearsnippets':
9081 clearsnippets = priority;
9084 parsedContext = tail.replace(/^"(.+)"$/, '$1');
9094 if (head == 'endglobal' && block == 'global') {
9096 pycodes.push(...preLines);
9100 if (head == 'endsnippet' && block == 'snippet') {
9104 let body = preLines.join('\n');
9105 // convert placeholder regex to javascript regex
9106 body = body.replace(/((?:[^\\]?\$\{\w+?)\/)([^\n]*?[^\\])(?=\/)/g, (_match, p1, p2) => {
9107 return p1 + util_1.convertRegex(p2);
9109 let ms = first.match(/^(.+?)(?:\s+(?:"(.*?)")?(?:\s+"(.*?)")?(?:\s+(\w+))?)?\s*$/);
9111 let description = ms[2] || '';
9112 let context = ms[3];
9113 let option = ms[4] || '';
9114 if (prefix.length > 2 && prefix[1] != prefix[0] && prefix[0] == prefix[prefix.length - 1] && !/\w/.test(prefix[0])) {
9115 prefix = prefix.slice(1, prefix.length - 1);
9117 let isExpression = option.indexOf('r') !== -1;
9120 originRegex = prefix;
9121 prefix = util_1.convertRegex(prefix);
9122 prefix = prefix.endsWith('$') ? prefix : prefix + '$';
9124 regex = new RegExp(prefix);
9125 // get the real text
9126 prefix = util_1.getRegexText(prefix);
9129 this.error(`Convert regex error for: ${prefix}`);
9132 if (parsedContext) {
9133 context = parsedContext;
9135 else if (option.indexOf('e') == -1) {
9142 autoTrigger: option.indexOf('A') !== -1,
9143 lnum: lnum - preLines.length - 2,
9144 triggerKind: getTriggerKind(option),
9151 snippets.push(snippet);
9154 this.error(`Create snippet error on: ${filepath}:${lnum - preLines.length - 1} ${e.message}`);
9157 parsedContext = null;
9161 if (block == 'snippet' || block == 'global') {
9162 preLines.push(line);
9166 return new Promise(resolve => {
9167 rl.on('close', async () => {
9168 resolve({ snippets, clearsnippets, pythonCode: pycodes.join('\n'), extendFiletypes });
9172 async resolveUltisnipsBody(body) {
9173 let { pyMethod } = this;
9174 let parser = new parser_1.default(body);
9176 while (!parser.eof()) {
9177 let p = parser.prev();
9178 if (parser.curr == '`' && (!p || p != '\\')) {
9179 let idx = parser.nextIndex('`', true, false);
9181 resolved = resolved + parser.eatTo(parser.len);
9184 let code = parser.eatTo(idx + 1);
9185 code = code.slice(1, -1);
9186 let indent = resolved.split(/\n/).slice(-1)[0].match(/^\s*/)[0];
9187 resolved = resolved + await this.execute(code, pyMethod, indent);
9190 else if (parser.curr == '$') {
9191 let text = parser.next(7);
9192 if (text.startsWith('VISUAL') || text.startsWith('{VISUAL')) {
9194 resolved += '$' + text.replace('VISUAL', 'TM_SELECTED_TEXT');
9196 else if (!/^\d/.test(text) && !text.startsWith('{') && p != '\\') {
9197 // escape $ if it's not escaped and not a placeholder, ultisnips sucks
9198 resolved += '\\' + parser.eat(1);
9202 resolved += parser.eat(1);
9205 let prev = parser.prev() || '';
9206 parser.iterate(ch => {
9207 if (prev !== '\\' && (ch == '`' || ch == '$')) {
9211 resolved = resolved + ch;
9217 resolved = decode(resolved);
9218 this.debug(`resolved: ${resolved}`);
9221 async execute(code, pyMethod, indent) {
9222 let { nvim } = coc_nvim_1.workspace;
9224 if (code.startsWith('!')) {
9225 code = code.trim().slice(1);
9226 if (code.startsWith('p')) {
9227 code = code.slice(1).trim();
9228 let lines = code.split('\n');
9229 lines = lines.map(line => line.replace(/\t/g, ' '));
9230 lines = lines.map(line => ` ${line}`);
9231 lines.unshift('try:');
9232 lines.unshift('import traceback');
9233 lines.push('except Exception as e:');
9234 lines.push(' snip.rv = traceback.format_exc()');
9235 await nvim.command(`${pyMethod} ${lines.join('\n')}`);
9236 res = await nvim.call(`${pyMethod}eval`, 'snip.rv');
9238 else if (code.startsWith('v')) {
9239 code = code.replace(/^v\s*/, '');
9241 res = await nvim.eval(code);
9244 res = `Error: ${e.message}`;
9245 this.error(e.stack);
9251 res = await pify_1.default(child_process_1.exec)(code);
9254 res = `Error: ${e.message}`;
9255 this.error(`Error on eval ${code}: ` + e.stack);
9258 res = res.toString();
9259 res = res.replace(/\r?\n$/, '');
9260 let parts = res.split(/\r?\n/);
9261 if (parts.length > 1) {
9262 res = parts.map((s, idx) => {
9263 if (idx == 0 || s.length == 0)
9265 return `${indent}${s}`;
9273 this.channel.appendLine(`[Error ${(new Date()).toLocaleTimeString()}] ${str}`);
9276 if (!this.channel || this.trace == 'error')
9278 this.channel.appendLine(`[Debug ${(new Date()).toLocaleTimeString()}] ${str}`);
9281 exports.default = UltiSnipsParser;
9282 function decode(str) {
9283 return str.replace(/\\`/g, '`').replace(/\\{/g, '{');
9285 function getTriggerKind(option) {
9286 if (option.indexOf('w') !== -1) {
9287 return types_1.TriggerKind.WordBoundary;
9289 if (option.indexOf('b') !== -1) {
9290 return types_1.TriggerKind.LineBegin;
9292 if (option.indexOf('i') !== -1) {
9293 return types_1.TriggerKind.InWord;
9295 return types_1.TriggerKind.SpaceBefore;
9301 /***/ ((module) => {
9303 module.exports = require("child_process");;
9307 /************************************************************************/
9308 /******/ // The module cache
9309 /******/ var __webpack_module_cache__ = {};
9311 /******/ // The require function
9312 /******/ function __webpack_require__(moduleId) {
9313 /******/ // Check if module is in cache
9314 /******/ if(__webpack_module_cache__[moduleId]) {
9315 /******/ return __webpack_module_cache__[moduleId].exports;
9317 /******/ // Create a new module (and put it into the cache)
9318 /******/ var module = __webpack_module_cache__[moduleId] = {
9319 /******/ // no module.id needed
9320 /******/ // no module.loaded needed
9321 /******/ exports: {}
9324 /******/ // Execute the module function
9325 /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
9327 /******/ // Return the exports of the module
9328 /******/ return module.exports;
9331 /************************************************************************/
9332 /******/ /* webpack/runtime/define property getters */
9334 /******/ // define getter functions for harmony exports
9335 /******/ __webpack_require__.d = (exports, definition) => {
9336 /******/ for(var key in definition) {
9337 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
9338 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
9344 /******/ /* webpack/runtime/hasOwnProperty shorthand */
9346 /******/ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop)
9349 /******/ /* webpack/runtime/make namespace object */
9351 /******/ // define __esModule on exports
9352 /******/ __webpack_require__.r = (exports) => {
9353 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
9354 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
9356 /******/ Object.defineProperty(exports, '__esModule', { value: true });
9360 /************************************************************************/
9361 /******/ // module exports must be returned from runtime so entry inlining is disabled
9363 /******/ // Load entry module and return exports
9364 /******/ return __webpack_require__(0);