Run prettier

This commit is contained in:
Alex Dima 2020-09-07 13:12:30 +02:00
parent 06e3393f83
commit 0b344d31d0
No known key found for this signature in database
GPG key ID: 6E58D7B045760DA0
19 changed files with 1796 additions and 1442 deletions

View file

@ -1,13 +1,14 @@
# Monaco JSON # Monaco JSON
JSON language plugin for the Monaco Editor. It provides the following features when editing JSON files: JSON language plugin for the Monaco Editor. It provides the following features when editing JSON files:
* Code completion, based on JSON schemas or by looking at similar objects in the same file
* Hovers, based on JSON schemas - Code completion, based on JSON schemas or by looking at similar objects in the same file
* Validation: Syntax errors and schema validation - Hovers, based on JSON schemas
* Formatting - Validation: Syntax errors and schema validation
* Document Symbols - Formatting
* Syntax highlighting - Document Symbols
* Color decorators for all properties matching a schema containing `format: "color-hex"'` (non-standard schema extension) - Syntax highlighting
- Color decorators for all properties matching a schema containing `format: "color-hex"'` (non-standard schema extension)
Schemas can be provided by configuration. See [here](https://github.com/Microsoft/monaco-json/blob/master/monaco.d.ts) Schemas can be provided by configuration. See [here](https://github.com/Microsoft/monaco-json/blob/master/monaco.d.ts)
for the API that the JSON plugin offers to configure the JSON language support. for the API that the JSON plugin offers to configure the JSON language support.
@ -26,12 +27,13 @@ This npm module is bundled and distributed in the [monaco-editor](https://www.np
## Development ## Development
* `git clone https://github.com/Microsoft/monaco-json` - `git clone https://github.com/Microsoft/monaco-json`
* `npm install .` - `npm install .`
* compile with `npm run compile` - compile with `npm run compile`
* watch with `npm run watch` - watch with `npm run watch`
* `npm run prepublishOnly` - `npm run prepublishOnly`
* open `$/monaco-json/test/index.html` in your favorite browser. - open `$/monaco-json/test/index.html` in your favorite browser.
## License ## License
[MIT](https://github.com/Microsoft/monaco-json/blob/master/LICENSE.md) [MIT](https://github.com/Microsoft/monaco-json/blob/master/LICENSE.md)

2
monaco.d.ts vendored
View file

@ -4,7 +4,6 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
declare namespace monaco.languages.json { declare namespace monaco.languages.json {
export interface DiagnosticsOptions { export interface DiagnosticsOptions {
/** /**
* If set, the validator will be enabled and perform syntax validation as well as schema based validation. * If set, the validator will be enabled and perform syntax validation as well as schema based validation.
@ -87,5 +86,4 @@ declare namespace monaco.languages.json {
setModeConfiguration(modeConfiguration: ModeConfiguration): void; setModeConfiguration(modeConfiguration: ModeConfiguration): void;
} }
export const jsonDefaults: LanguageServiceDefaults; export const jsonDefaults: LanguageServiceDefaults;
} }

View file

@ -1,7 +1,7 @@
const requirejs = require('requirejs'); const requirejs = require('requirejs');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const Terser = require("terser"); const Terser = require('terser');
const helpers = require('monaco-plugin-helpers'); const helpers = require('monaco-plugin-helpers');
const REPO_ROOT = path.resolve(__dirname, '..'); const REPO_ROOT = path.resolve(__dirname, '..');
@ -25,43 +25,68 @@ bundleOne('jsonMode');
bundleOne('jsonWorker'); bundleOne('jsonWorker');
function bundleOne(moduleId) { function bundleOne(moduleId) {
requirejs.optimize({ requirejs.optimize(
{
baseUrl: 'out/amd/', baseUrl: 'out/amd/',
name: 'vs/language/json/' + moduleId, name: 'vs/language/json/' + moduleId,
out: 'release/dev/' + moduleId + '.js', out: 'release/dev/' + moduleId + '.js',
paths: { paths: {
'vs/language/json': REPO_ROOT + '/out/amd', 'vs/language/json': REPO_ROOT + '/out/amd',
'vs/language/json/fillers/monaco-editor-core': REPO_ROOT + '/out/amd/fillers/monaco-editor-core-amd', 'vs/language/json/fillers/monaco-editor-core':
REPO_ROOT + '/out/amd/fillers/monaco-editor-core-amd'
}, },
optimize: 'none', optimize: 'none',
packages: [{ packages: [
{
name: 'vscode-json-languageservice', name: 'vscode-json-languageservice',
location: path.join(REPO_ROOT, 'node_modules/vscode-json-languageservice/lib/umd'), location: path.join(
REPO_ROOT,
'node_modules/vscode-json-languageservice/lib/umd'
),
main: 'jsonLanguageService' main: 'jsonLanguageService'
}, { },
{
name: 'vscode-languageserver-types', name: 'vscode-languageserver-types',
location: path.join(REPO_ROOT, 'node_modules/vscode-languageserver-types/lib/umd'), location: path.join(
REPO_ROOT,
'node_modules/vscode-languageserver-types/lib/umd'
),
main: 'main' main: 'main'
}, { },
{
name: 'vscode-languageserver-textdocument', name: 'vscode-languageserver-textdocument',
location: path.join(REPO_ROOT, 'node_modules/vscode-languageserver-textdocument/lib/umd'), location: path.join(
REPO_ROOT,
'node_modules/vscode-languageserver-textdocument/lib/umd'
),
main: 'main' main: 'main'
}, { },
{
name: 'jsonc-parser', name: 'jsonc-parser',
location: path.join(REPO_ROOT, 'node_modules/jsonc-parser/lib/umd'), location: path.join(REPO_ROOT, 'node_modules/jsonc-parser/lib/umd'),
main: 'main' main: 'main'
}, { },
{
name: 'vscode-uri', name: 'vscode-uri',
location: path.join(REPO_ROOT, 'node_modules/vscode-uri/lib/umd'), location: path.join(REPO_ROOT, 'node_modules/vscode-uri/lib/umd'),
main: 'index' main: 'index'
}, { },
{
name: 'vscode-nls', name: 'vscode-nls',
location: path.join(REPO_ROOT, '/out/amd/fillers'), location: path.join(REPO_ROOT, '/out/amd/fillers'),
main: 'vscode-nls' main: 'vscode-nls'
}] }
}, async function (buildResponse) { ]
const devFilePath = path.join(REPO_ROOT, 'release/dev/' + moduleId + '.js'); },
const minFilePath = path.join(REPO_ROOT, 'release/min/' + moduleId + '.js'); async function (buildResponse) {
const devFilePath = path.join(
REPO_ROOT,
'release/dev/' + moduleId + '.js'
);
const minFilePath = path.join(
REPO_ROOT,
'release/min/' + moduleId + '.js'
);
const fileContents = fs.readFileSync(devFilePath).toString(); const fileContents = fs.readFileSync(devFilePath).toString();
console.log(`Minifying ${devFilePath}...`); console.log(`Minifying ${devFilePath}...`);
const result = await Terser.minify(fileContents, { const result = await Terser.minify(fileContents, {
@ -70,7 +95,10 @@ function bundleOne(moduleId) {
} }
}); });
console.log(`Done minifying ${devFilePath}.`); console.log(`Done minifying ${devFilePath}.`);
try { fs.mkdirSync(path.join(REPO_ROOT, 'release/min')) } catch (err) { } try {
fs.mkdirSync(path.join(REPO_ROOT, 'release/min'));
} catch (err) {}
fs.writeFileSync(minFilePath, BUNDLED_FILE_HEADER + result.code); fs.writeFileSync(minFilePath, BUNDLED_FILE_HEADER + result.code);
}) }
);
} }

View file

@ -10,7 +10,10 @@ const REPO_ROOT = path.join(__dirname, '../');
const SRC_PATH = path.join(REPO_ROOT, 'out/amd/monaco.contribution.d.ts'); const SRC_PATH = path.join(REPO_ROOT, 'out/amd/monaco.contribution.d.ts');
const DST_PATH = path.join(REPO_ROOT, 'monaco.d.ts'); const DST_PATH = path.join(REPO_ROOT, 'monaco.d.ts');
const lines = fs.readFileSync(SRC_PATH).toString().split(/\r\n|\r|\n/); const lines = fs
.readFileSync(SRC_PATH)
.toString()
.split(/\r\n|\r|\n/);
let result = [ let result = [
`/*---------------------------------------------------------------------------------------------`, `/*---------------------------------------------------------------------------------------------`,
` * Copyright (c) Microsoft Corporation. All rights reserved.`, ` * Copyright (c) Microsoft Corporation. All rights reserved.`,

View file

@ -12,19 +12,13 @@ helpers.packageESM({
repoRoot: REPO_ROOT, repoRoot: REPO_ROOT,
esmSource: 'out/esm', esmSource: 'out/esm',
esmDestination: 'release/esm', esmDestination: 'release/esm',
entryPoints: [ entryPoints: ['monaco.contribution.js', 'jsonMode.js', 'json.worker.js'],
'monaco.contribution.js',
'jsonMode.js',
'json.worker.js'
],
resolveAlias: { resolveAlias: {
'vscode-nls': path.join(REPO_ROOT, "out/esm/fillers/vscode-nls.js") 'vscode-nls': path.join(REPO_ROOT, 'out/esm/fillers/vscode-nls.js')
}, },
resolveSkip: [ resolveSkip: ['monaco-editor-core'],
'monaco-editor-core'
],
destinationFolderSimplification: { destinationFolderSimplification: {
'node_modules': '_deps', node_modules: '_deps',
'jsonc-parser/lib/esm': 'jsonc-parser', 'jsonc-parser/lib/esm': 'jsonc-parser',
'vscode-languageserver-types/lib/esm': 'vscode-languageserver-types', 'vscode-languageserver-types/lib/esm': 'vscode-languageserver-types',
'vscode-uri/lib/esm': 'vscode-uri', 'vscode-uri/lib/esm': 'vscode-uri',

View file

@ -33,7 +33,11 @@ function format(message: string, args: any[]): string {
return result; return result;
} }
function localize(key: string | LocalizeInfo, message: string, ...args: any[]): string { function localize(
key: string | LocalizeInfo,
message: string,
...args: any[]
): string {
return format(message, args); return format(message, args);
} }

View file

@ -9,6 +9,6 @@ import { JSONWorker } from './jsonWorker';
self.onmessage = () => { self.onmessage = () => {
// ignore the first message // ignore the first message
worker.initialize((ctx, createData) => { worker.initialize((ctx, createData) => {
return new JSONWorker(ctx, createData) return new JSONWorker(ctx, createData);
}); });
}; };

View file

@ -8,61 +8,110 @@ import type { JSONWorker } from './jsonWorker';
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from './languageFeatures'; import * as languageFeatures from './languageFeatures';
import { createTokenizationSupport } from './tokenization'; import { createTokenizationSupport } from './tokenization';
import { Uri, IDisposable, languages } from './fillers/monaco-editor-core' import { Uri, IDisposable, languages } from './fillers/monaco-editor-core';
export function setupMode(defaults: LanguageServiceDefaults): IDisposable { export function setupMode(defaults: LanguageServiceDefaults): IDisposable {
const disposables: IDisposable[] = []; const disposables: IDisposable[] = [];
const providers: IDisposable[] = []; const providers: IDisposable[] = [];
const client = new WorkerManager(defaults); const client = new WorkerManager(defaults);
disposables.push(client); disposables.push(client);
const worker: languageFeatures.WorkerAccessor = (...uris: Uri[]): Promise<JSONWorker> => { const worker: languageFeatures.WorkerAccessor = (
...uris: Uri[]
): Promise<JSONWorker> => {
return client.getLanguageServiceWorker(...uris); return client.getLanguageServiceWorker(...uris);
}; };
function registerProviders(): void { function registerProviders(): void {
const { languageId, modeConfiguration } = defaults; const { languageId, modeConfiguration } = defaults;
disposeAll(providers); disposeAll(providers);
if (modeConfiguration.documentFormattingEdits) { if (modeConfiguration.documentFormattingEdits) {
providers.push(languages.registerDocumentFormattingEditProvider(languageId, new languageFeatures.DocumentFormattingEditProvider(worker))); providers.push(
languages.registerDocumentFormattingEditProvider(
languageId,
new languageFeatures.DocumentFormattingEditProvider(worker)
)
);
} }
if (modeConfiguration.documentRangeFormattingEdits) { if (modeConfiguration.documentRangeFormattingEdits) {
providers.push(languages.registerDocumentRangeFormattingEditProvider(languageId, new languageFeatures.DocumentRangeFormattingEditProvider(worker))); providers.push(
languages.registerDocumentRangeFormattingEditProvider(
languageId,
new languageFeatures.DocumentRangeFormattingEditProvider(worker)
)
);
} }
if (modeConfiguration.completionItems) { if (modeConfiguration.completionItems) {
providers.push(languages.registerCompletionItemProvider(languageId, new languageFeatures.CompletionAdapter(worker))); providers.push(
languages.registerCompletionItemProvider(
languageId,
new languageFeatures.CompletionAdapter(worker)
)
);
} }
if (modeConfiguration.hovers) { if (modeConfiguration.hovers) {
providers.push(languages.registerHoverProvider(languageId, new languageFeatures.HoverAdapter(worker))); providers.push(
languages.registerHoverProvider(
languageId,
new languageFeatures.HoverAdapter(worker)
)
);
} }
if (modeConfiguration.documentSymbols) { if (modeConfiguration.documentSymbols) {
providers.push(languages.registerDocumentSymbolProvider(languageId, new languageFeatures.DocumentSymbolAdapter(worker))); providers.push(
languages.registerDocumentSymbolProvider(
languageId,
new languageFeatures.DocumentSymbolAdapter(worker)
)
);
} }
if (modeConfiguration.tokens) { if (modeConfiguration.tokens) {
providers.push(languages.setTokensProvider(languageId, createTokenizationSupport(true))); providers.push(
languages.setTokensProvider(languageId, createTokenizationSupport(true))
);
} }
if (modeConfiguration.colors) { if (modeConfiguration.colors) {
providers.push(languages.registerColorProvider(languageId, new languageFeatures.DocumentColorAdapter(worker))); providers.push(
languages.registerColorProvider(
languageId,
new languageFeatures.DocumentColorAdapter(worker)
)
);
} }
if (modeConfiguration.foldingRanges) { if (modeConfiguration.foldingRanges) {
providers.push(languages.registerFoldingRangeProvider(languageId, new languageFeatures.FoldingRangeAdapter(worker))); providers.push(
languages.registerFoldingRangeProvider(
languageId,
new languageFeatures.FoldingRangeAdapter(worker)
)
);
} }
if (modeConfiguration.diagnostics) { if (modeConfiguration.diagnostics) {
providers.push(new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults)); providers.push(
new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults)
);
} }
if (modeConfiguration.selectionRanges) { if (modeConfiguration.selectionRanges) {
providers.push(languages.registerSelectionRangeProvider(languageId, new languageFeatures.SelectionRangeAdapter(worker))); providers.push(
languages.registerSelectionRangeProvider(
languageId,
new languageFeatures.SelectionRangeAdapter(worker)
)
);
} }
} }
registerProviders(); registerProviders();
disposables.push(languages.setLanguageConfiguration(defaults.languageId, richEditConfiguration)); disposables.push(
languages.setLanguageConfiguration(
defaults.languageId,
richEditConfiguration
)
);
let modeConfiguration = defaults.modeConfiguration; let modeConfiguration = defaults.modeConfiguration;
defaults.onDidChange((newDefaults) => { defaults.onDidChange((newDefaults) => {
@ -106,4 +155,3 @@ const richEditConfiguration: languages.LanguageConfiguration = {
{ open: '"', close: '"', notIn: ['string'] } { open: '"', close: '"', notIn: ['string'] }
] ]
}; };

View file

@ -4,15 +4,16 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as jsonService from 'vscode-json-languageservice'; import * as jsonService from 'vscode-json-languageservice';
import type { worker } from './fillers/monaco-editor-core' import type { worker } from './fillers/monaco-editor-core';
let defaultSchemaRequestService; let defaultSchemaRequestService;
if (typeof fetch !== 'undefined') { if (typeof fetch !== 'undefined') {
defaultSchemaRequestService = function (url) { return fetch(url).then(response => response.text()) }; defaultSchemaRequestService = function (url) {
return fetch(url).then((response) => response.text());
};
} }
export class JSONWorker { export class JSONWorker {
private _ctx: worker.IWorkerContext; private _ctx: worker.IWorkerContext;
private _languageService: jsonService.LanguageService; private _languageService: jsonService.LanguageService;
private _languageSettings: jsonService.LanguageSettings; private _languageSettings: jsonService.LanguageSettings;
@ -23,7 +24,8 @@ export class JSONWorker {
this._languageSettings = createData.languageSettings; this._languageSettings = createData.languageSettings;
this._languageId = createData.languageId; this._languageId = createData.languageId;
this._languageService = jsonService.getLanguageService({ this._languageService = jsonService.getLanguageService({
schemaRequestService: createData.enableSchemaRequest && defaultSchemaRequestService schemaRequestService:
createData.enableSchemaRequest && defaultSchemaRequestService
}); });
this._languageService.configure(this._languageSettings); this._languageService.configure(this._languageSettings);
} }
@ -36,20 +38,32 @@ export class JSONWorker {
} }
return Promise.resolve([]); return Promise.resolve([]);
} }
async doComplete(uri: string, position: jsonService.Position): Promise<jsonService.CompletionList> { async doComplete(
uri: string,
position: jsonService.Position
): Promise<jsonService.CompletionList> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doComplete(document, position, jsonDocument); return this._languageService.doComplete(document, position, jsonDocument);
} }
async doResolve(item: jsonService.CompletionItem): Promise<jsonService.CompletionItem> { async doResolve(
item: jsonService.CompletionItem
): Promise<jsonService.CompletionItem> {
return this._languageService.doResolve(item); return this._languageService.doResolve(item);
} }
async doHover(uri: string, position: jsonService.Position): Promise<jsonService.Hover> { async doHover(
uri: string,
position: jsonService.Position
): Promise<jsonService.Hover> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let jsonDocument = this._languageService.parseJSONDocument(document);
return this._languageService.doHover(document, position, jsonDocument); return this._languageService.doHover(document, position, jsonDocument);
} }
async format(uri: string, range: jsonService.Range, options: jsonService.FormattingOptions): Promise<jsonService.TextEdit[]> { async format(
uri: string,
range: jsonService.Range,
options: jsonService.FormattingOptions
): Promise<jsonService.TextEdit[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let textEdits = this._languageService.format(document, range, options); let textEdits = this._languageService.format(document, range, options);
return Promise.resolve(textEdits); return Promise.resolve(textEdits);
@ -57,40 +71,74 @@ export class JSONWorker {
async resetSchema(uri: string): Promise<boolean> { async resetSchema(uri: string): Promise<boolean> {
return Promise.resolve(this._languageService.resetSchema(uri)); return Promise.resolve(this._languageService.resetSchema(uri));
} }
async findDocumentSymbols(uri: string): Promise<jsonService.SymbolInformation[]> { async findDocumentSymbols(
uri: string
): Promise<jsonService.SymbolInformation[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let jsonDocument = this._languageService.parseJSONDocument(document);
let symbols = this._languageService.findDocumentSymbols(document, jsonDocument); let symbols = this._languageService.findDocumentSymbols(
document,
jsonDocument
);
return Promise.resolve(symbols); return Promise.resolve(symbols);
} }
async findDocumentColors(uri: string): Promise<jsonService.ColorInformation[]> { async findDocumentColors(
uri: string
): Promise<jsonService.ColorInformation[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let jsonDocument = this._languageService.parseJSONDocument(document);
let colorSymbols = this._languageService.findDocumentColors(document, jsonDocument); let colorSymbols = this._languageService.findDocumentColors(
document,
jsonDocument
);
return Promise.resolve(colorSymbols); return Promise.resolve(colorSymbols);
} }
async getColorPresentations(uri: string, color: jsonService.Color, range: jsonService.Range): Promise<jsonService.ColorPresentation[]> { async getColorPresentations(
uri: string,
color: jsonService.Color,
range: jsonService.Range
): Promise<jsonService.ColorPresentation[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let jsonDocument = this._languageService.parseJSONDocument(document);
let colorPresentations = this._languageService.getColorPresentations(document, jsonDocument, color, range); let colorPresentations = this._languageService.getColorPresentations(
document,
jsonDocument,
color,
range
);
return Promise.resolve(colorPresentations); return Promise.resolve(colorPresentations);
} }
async getFoldingRanges(uri: string, context?: { rangeLimit?: number; }): Promise<jsonService.FoldingRange[]> { async getFoldingRanges(
uri: string,
context?: { rangeLimit?: number }
): Promise<jsonService.FoldingRange[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let ranges = this._languageService.getFoldingRanges(document, context); let ranges = this._languageService.getFoldingRanges(document, context);
return Promise.resolve(ranges); return Promise.resolve(ranges);
} }
async getSelectionRanges(uri: string, positions: jsonService.Position[]): Promise<jsonService.SelectionRange[]> { async getSelectionRanges(
uri: string,
positions: jsonService.Position[]
): Promise<jsonService.SelectionRange[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let jsonDocument = this._languageService.parseJSONDocument(document);
let ranges = this._languageService.getSelectionRanges(document, positions, jsonDocument); let ranges = this._languageService.getSelectionRanges(
document,
positions,
jsonDocument
);
return Promise.resolve(ranges); return Promise.resolve(ranges);
} }
private _getTextDocument(uri: string): jsonService.TextDocument { private _getTextDocument(uri: string): jsonService.TextDocument {
let models = this._ctx.getMirrorModels(); let models = this._ctx.getMirrorModels();
for (let model of models) { for (let model of models) {
if (model.uri.toString() === uri) { if (model.uri.toString() === uri) {
return jsonService.TextDocument.create(uri, this._languageId, model.version, model.getValue()); return jsonService.TextDocument.create(
uri,
this._languageId,
model.version,
model.getValue()
);
} }
} }
return null; return null;
@ -103,6 +151,9 @@ export interface ICreateData {
enableSchemaRequest: boolean; enableSchemaRequest: boolean;
} }
export function create(ctx: worker.IWorkerContext, createData: ICreateData): JSONWorker { export function create(
ctx: worker.IWorkerContext,
createData: ICreateData
): JSONWorker {
return new JSONWorker(ctx, createData); return new JSONWorker(ctx, createData);
} }

View file

@ -5,22 +5,35 @@
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { JSONWorker } from './jsonWorker'; import type { JSONWorker } from './jsonWorker';
import { Uri, Position, Range, IRange, CancellationToken, IDisposable, editor, languages, MarkerSeverity, IMarkdownString } from './fillers/monaco-editor-core' import {
Uri,
Position,
Range,
IRange,
CancellationToken,
IDisposable,
editor,
languages,
MarkerSeverity,
IMarkdownString
} from './fillers/monaco-editor-core';
import * as jsonService from 'vscode-json-languageservice'; import * as jsonService from 'vscode-json-languageservice';
export interface WorkerAccessor { export interface WorkerAccessor {
(...more: Uri[]): Promise<JSONWorker> (...more: Uri[]): Promise<JSONWorker>;
} }
// --- diagnostics --- --- // --- diagnostics --- ---
export class DiagnosticsAdapter { export class DiagnosticsAdapter {
private _disposables: IDisposable[] = []; private _disposables: IDisposable[] = [];
private _listener: { [uri: string]: IDisposable } = Object.create(null); private _listener: { [uri: string]: IDisposable } = Object.create(null);
constructor(private _languageId: string, private _worker: WorkerAccessor, defaults: LanguageServiceDefaults) { constructor(
private _languageId: string,
private _worker: WorkerAccessor,
defaults: LanguageServiceDefaults
) {
const onModelAdd = (model: editor.IModel): void => { const onModelAdd = (model: editor.IModel): void => {
let modeId = model.getModeId(); let modeId = model.getModeId();
if (modeId !== this._languageId) { if (modeId !== this._languageId) {
@ -47,24 +60,30 @@ export class DiagnosticsAdapter {
}; };
this._disposables.push(editor.onDidCreateModel(onModelAdd)); this._disposables.push(editor.onDidCreateModel(onModelAdd));
this._disposables.push(editor.onWillDisposeModel(model => { this._disposables.push(
editor.onWillDisposeModel((model) => {
onModelRemoved(model); onModelRemoved(model);
this._resetSchema(model.uri); this._resetSchema(model.uri);
})); })
this._disposables.push(editor.onDidChangeModelLanguage(event => { );
this._disposables.push(
editor.onDidChangeModelLanguage((event) => {
onModelRemoved(event.model); onModelRemoved(event.model);
onModelAdd(event.model); onModelAdd(event.model);
this._resetSchema(event.model.uri); this._resetSchema(event.model.uri);
})); })
);
this._disposables.push(defaults.onDidChange(_ => { this._disposables.push(
editor.getModels().forEach(model => { defaults.onDidChange((_) => {
editor.getModels().forEach((model) => {
if (model.getModeId() === this._languageId) { if (model.getModeId() === this._languageId) {
onModelRemoved(model); onModelRemoved(model);
onModelAdd(model); onModelAdd(model);
} }
}); });
})); })
);
this._disposables.push({ this._disposables.push({
dispose: () => { dispose: () => {
@ -79,45 +98,54 @@ export class DiagnosticsAdapter {
} }
public dispose(): void { public dispose(): void {
this._disposables.forEach(d => d && d.dispose()); this._disposables.forEach((d) => d && d.dispose());
this._disposables = []; this._disposables = [];
} }
private _resetSchema(resource: Uri): void { private _resetSchema(resource: Uri): void {
this._worker().then(worker => { this._worker().then((worker) => {
worker.resetSchema(resource.toString()); worker.resetSchema(resource.toString());
}); });
} }
private _doValidate(resource: Uri, languageId: string): void { private _doValidate(resource: Uri, languageId: string): void {
this._worker(resource).then(worker => { this._worker(resource)
return worker.doValidation(resource.toString()).then(diagnostics => { .then((worker) => {
const markers = diagnostics.map(d => toDiagnostics(resource, d)); return worker.doValidation(resource.toString()).then((diagnostics) => {
const markers = diagnostics.map((d) => toDiagnostics(resource, d));
let model = editor.getModel(resource); let model = editor.getModel(resource);
if (model && model.getModeId() === languageId) { if (model && model.getModeId() === languageId) {
editor.setModelMarkers(model, languageId, markers); editor.setModelMarkers(model, languageId, markers);
} }
}); });
}).then(undefined, err => { })
.then(undefined, (err) => {
console.error(err); console.error(err);
}); });
} }
} }
function toSeverity(lsSeverity: number): MarkerSeverity { function toSeverity(lsSeverity: number): MarkerSeverity {
switch (lsSeverity) { switch (lsSeverity) {
case jsonService.DiagnosticSeverity.Error: return MarkerSeverity.Error; case jsonService.DiagnosticSeverity.Error:
case jsonService.DiagnosticSeverity.Warning: return MarkerSeverity.Warning; return MarkerSeverity.Error;
case jsonService.DiagnosticSeverity.Information: return MarkerSeverity.Info; case jsonService.DiagnosticSeverity.Warning:
case jsonService.DiagnosticSeverity.Hint: return MarkerSeverity.Hint; return MarkerSeverity.Warning;
case jsonService.DiagnosticSeverity.Information:
return MarkerSeverity.Info;
case jsonService.DiagnosticSeverity.Hint:
return MarkerSeverity.Hint;
default: default:
return MarkerSeverity.Info; return MarkerSeverity.Info;
} }
} }
function toDiagnostics(resource: Uri, diag: jsonService.Diagnostic): editor.IMarkerData { function toDiagnostics(
let code = typeof diag.code === 'number' ? String(diag.code) : <string>diag.code; resource: Uri,
diag: jsonService.Diagnostic
): editor.IMarkerData {
let code =
typeof diag.code === 'number' ? String(diag.code) : <string>diag.code;
return { return {
severity: toSeverity(diag.severity), severity: toSeverity(diag.severity),
@ -144,99 +172,160 @@ function fromRange(range: IRange): jsonService.Range {
if (!range) { if (!range) {
return void 0; return void 0;
} }
return { start: { line: range.startLineNumber - 1, character: range.startColumn - 1 }, end: { line: range.endLineNumber - 1, character: range.endColumn - 1 } }; return {
start: {
line: range.startLineNumber - 1,
character: range.startColumn - 1
},
end: { line: range.endLineNumber - 1, character: range.endColumn - 1 }
};
} }
function toRange(range: jsonService.Range): Range { function toRange(range: jsonService.Range): Range {
if (!range) { if (!range) {
return void 0; return void 0;
} }
return new Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1); return new Range(
range.start.line + 1,
range.start.character + 1,
range.end.line + 1,
range.end.character + 1
);
} }
function toCompletionItemKind(kind: number): languages.CompletionItemKind { function toCompletionItemKind(kind: number): languages.CompletionItemKind {
let mItemKind = languages.CompletionItemKind; let mItemKind = languages.CompletionItemKind;
switch (kind) { switch (kind) {
case jsonService.CompletionItemKind.Text: return mItemKind.Text; case jsonService.CompletionItemKind.Text:
case jsonService.CompletionItemKind.Method: return mItemKind.Method; return mItemKind.Text;
case jsonService.CompletionItemKind.Function: return mItemKind.Function; case jsonService.CompletionItemKind.Method:
case jsonService.CompletionItemKind.Constructor: return mItemKind.Constructor; return mItemKind.Method;
case jsonService.CompletionItemKind.Field: return mItemKind.Field; case jsonService.CompletionItemKind.Function:
case jsonService.CompletionItemKind.Variable: return mItemKind.Variable; return mItemKind.Function;
case jsonService.CompletionItemKind.Class: return mItemKind.Class; case jsonService.CompletionItemKind.Constructor:
case jsonService.CompletionItemKind.Interface: return mItemKind.Interface; return mItemKind.Constructor;
case jsonService.CompletionItemKind.Module: return mItemKind.Module; case jsonService.CompletionItemKind.Field:
case jsonService.CompletionItemKind.Property: return mItemKind.Property; return mItemKind.Field;
case jsonService.CompletionItemKind.Unit: return mItemKind.Unit; case jsonService.CompletionItemKind.Variable:
case jsonService.CompletionItemKind.Value: return mItemKind.Value; return mItemKind.Variable;
case jsonService.CompletionItemKind.Enum: return mItemKind.Enum; case jsonService.CompletionItemKind.Class:
case jsonService.CompletionItemKind.Keyword: return mItemKind.Keyword; return mItemKind.Class;
case jsonService.CompletionItemKind.Snippet: return mItemKind.Snippet; case jsonService.CompletionItemKind.Interface:
case jsonService.CompletionItemKind.Color: return mItemKind.Color; return mItemKind.Interface;
case jsonService.CompletionItemKind.File: return mItemKind.File; case jsonService.CompletionItemKind.Module:
case jsonService.CompletionItemKind.Reference: return mItemKind.Reference; return mItemKind.Module;
case jsonService.CompletionItemKind.Property:
return mItemKind.Property;
case jsonService.CompletionItemKind.Unit:
return mItemKind.Unit;
case jsonService.CompletionItemKind.Value:
return mItemKind.Value;
case jsonService.CompletionItemKind.Enum:
return mItemKind.Enum;
case jsonService.CompletionItemKind.Keyword:
return mItemKind.Keyword;
case jsonService.CompletionItemKind.Snippet:
return mItemKind.Snippet;
case jsonService.CompletionItemKind.Color:
return mItemKind.Color;
case jsonService.CompletionItemKind.File:
return mItemKind.File;
case jsonService.CompletionItemKind.Reference:
return mItemKind.Reference;
} }
return mItemKind.Property; return mItemKind.Property;
} }
function fromCompletionItemKind(kind: languages.CompletionItemKind): jsonService.CompletionItemKind { function fromCompletionItemKind(
kind: languages.CompletionItemKind
): jsonService.CompletionItemKind {
let mItemKind = languages.CompletionItemKind; let mItemKind = languages.CompletionItemKind;
switch (kind) { switch (kind) {
case mItemKind.Text: return jsonService.CompletionItemKind.Text; case mItemKind.Text:
case mItemKind.Method: return jsonService.CompletionItemKind.Method; return jsonService.CompletionItemKind.Text;
case mItemKind.Function: return jsonService.CompletionItemKind.Function; case mItemKind.Method:
case mItemKind.Constructor: return jsonService.CompletionItemKind.Constructor; return jsonService.CompletionItemKind.Method;
case mItemKind.Field: return jsonService.CompletionItemKind.Field; case mItemKind.Function:
case mItemKind.Variable: return jsonService.CompletionItemKind.Variable; return jsonService.CompletionItemKind.Function;
case mItemKind.Class: return jsonService.CompletionItemKind.Class; case mItemKind.Constructor:
case mItemKind.Interface: return jsonService.CompletionItemKind.Interface; return jsonService.CompletionItemKind.Constructor;
case mItemKind.Module: return jsonService.CompletionItemKind.Module; case mItemKind.Field:
case mItemKind.Property: return jsonService.CompletionItemKind.Property; return jsonService.CompletionItemKind.Field;
case mItemKind.Unit: return jsonService.CompletionItemKind.Unit; case mItemKind.Variable:
case mItemKind.Value: return jsonService.CompletionItemKind.Value; return jsonService.CompletionItemKind.Variable;
case mItemKind.Enum: return jsonService.CompletionItemKind.Enum; case mItemKind.Class:
case mItemKind.Keyword: return jsonService.CompletionItemKind.Keyword; return jsonService.CompletionItemKind.Class;
case mItemKind.Snippet: return jsonService.CompletionItemKind.Snippet; case mItemKind.Interface:
case mItemKind.Color: return jsonService.CompletionItemKind.Color; return jsonService.CompletionItemKind.Interface;
case mItemKind.File: return jsonService.CompletionItemKind.File; case mItemKind.Module:
case mItemKind.Reference: return jsonService.CompletionItemKind.Reference; return jsonService.CompletionItemKind.Module;
case mItemKind.Property:
return jsonService.CompletionItemKind.Property;
case mItemKind.Unit:
return jsonService.CompletionItemKind.Unit;
case mItemKind.Value:
return jsonService.CompletionItemKind.Value;
case mItemKind.Enum:
return jsonService.CompletionItemKind.Enum;
case mItemKind.Keyword:
return jsonService.CompletionItemKind.Keyword;
case mItemKind.Snippet:
return jsonService.CompletionItemKind.Snippet;
case mItemKind.Color:
return jsonService.CompletionItemKind.Color;
case mItemKind.File:
return jsonService.CompletionItemKind.File;
case mItemKind.Reference:
return jsonService.CompletionItemKind.Reference;
} }
return jsonService.CompletionItemKind.Property; return jsonService.CompletionItemKind.Property;
} }
function toTextEdit(textEdit: jsonService.TextEdit): editor.ISingleEditOperation { function toTextEdit(
textEdit: jsonService.TextEdit
): editor.ISingleEditOperation {
if (!textEdit) { if (!textEdit) {
return void 0; return void 0;
} }
return { return {
range: toRange(textEdit.range), range: toRange(textEdit.range),
text: textEdit.newText text: textEdit.newText
} };
} }
export class CompletionAdapter implements languages.CompletionItemProvider { export class CompletionAdapter implements languages.CompletionItemProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) {
}
public get triggerCharacters(): string[] { public get triggerCharacters(): string[] {
return [' ', ':']; return [' ', ':'];
} }
provideCompletionItems(model: editor.IReadOnlyModel, position: Position, context: languages.CompletionContext, token: CancellationToken): Promise<languages.CompletionList> { provideCompletionItems(
model: editor.IReadOnlyModel,
position: Position,
context: languages.CompletionContext,
token: CancellationToken
): Promise<languages.CompletionList> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => { return this._worker(resource)
.then((worker) => {
return worker.doComplete(resource.toString(), fromPosition(position)); return worker.doComplete(resource.toString(), fromPosition(position));
}).then(info => { })
.then((info) => {
if (!info) { if (!info) {
return; return;
} }
const wordInfo = model.getWordUntilPosition(position); const wordInfo = model.getWordUntilPosition(position);
const wordRange = new Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn); const wordRange = new Range(
position.lineNumber,
wordInfo.startColumn,
position.lineNumber,
wordInfo.endColumn
);
let items: languages.CompletionItem[] = info.items.map(entry => { let items: languages.CompletionItem[] = info.items.map((entry) => {
let item: languages.CompletionItem = { let item: languages.CompletionItem = {
label: entry.label, label: entry.label,
insertText: entry.insertText || entry.label, insertText: entry.insertText || entry.label,
@ -245,17 +334,20 @@ export class CompletionAdapter implements languages.CompletionItemProvider {
documentation: entry.documentation, documentation: entry.documentation,
detail: entry.detail, detail: entry.detail,
range: wordRange, range: wordRange,
kind: toCompletionItemKind(entry.kind), kind: toCompletionItemKind(entry.kind)
}; };
if (entry.textEdit) { if (entry.textEdit) {
item.range = toRange(entry.textEdit.range); item.range = toRange(entry.textEdit.range);
item.insertText = entry.textEdit.newText; item.insertText = entry.textEdit.newText;
} }
if (entry.additionalTextEdits) { if (entry.additionalTextEdits) {
item.additionalTextEdits = entry.additionalTextEdits.map(toTextEdit) item.additionalTextEdits = entry.additionalTextEdits.map(
toTextEdit
);
} }
if (entry.insertTextFormat === jsonService.InsertTextFormat.Snippet) { if (entry.insertTextFormat === jsonService.InsertTextFormat.Snippet) {
item.insertTextRules = languages.CompletionItemInsertTextRule.InsertAsSnippet; item.insertTextRules =
languages.CompletionItemInsertTextRule.InsertAsSnippet;
} }
return item; return item;
}); });
@ -269,10 +361,16 @@ export class CompletionAdapter implements languages.CompletionItemProvider {
} }
function isMarkupContent(thing: any): thing is jsonService.MarkupContent { function isMarkupContent(thing: any): thing is jsonService.MarkupContent {
return thing && typeof thing === 'object' && typeof (<jsonService.MarkupContent>thing).kind === 'string'; return (
thing &&
typeof thing === 'object' &&
typeof (<jsonService.MarkupContent>thing).kind === 'string'
);
} }
function toMarkdownString(entry: jsonService.MarkupContent | jsonService.MarkedString): IMarkdownString { function toMarkdownString(
entry: jsonService.MarkupContent | jsonService.MarkedString
): IMarkdownString {
if (typeof entry === 'string') { if (typeof entry === 'string') {
return { return {
value: entry value: entry
@ -292,7 +390,12 @@ function toMarkdownString(entry: jsonService.MarkupContent | jsonService.MarkedS
return { value: '```' + entry.language + '\n' + entry.value + '\n```\n' }; return { value: '```' + entry.language + '\n' + entry.value + '\n```\n' };
} }
function toMarkedStringArray(contents: jsonService.MarkupContent | jsonService.MarkedString | jsonService.MarkedString[]): IMarkdownString[] { function toMarkedStringArray(
contents:
| jsonService.MarkupContent
| jsonService.MarkedString
| jsonService.MarkedString[]
): IMarkdownString[] {
if (!contents) { if (!contents) {
return void 0; return void 0;
} }
@ -302,20 +405,23 @@ function toMarkedStringArray(contents: jsonService.MarkupContent | jsonService.M
return [toMarkdownString(contents)]; return [toMarkdownString(contents)];
} }
// --- hover ------ // --- hover ------
export class HoverAdapter implements languages.HoverProvider { export class HoverAdapter implements languages.HoverProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { provideHover(
} model: editor.IReadOnlyModel,
position: Position,
provideHover(model: editor.IReadOnlyModel, position: Position, token: CancellationToken): Promise<languages.Hover> { token: CancellationToken
): Promise<languages.Hover> {
let resource = model.uri; let resource = model.uri;
return this._worker(resource).then(worker => { return this._worker(resource)
.then((worker) => {
return worker.doHover(resource.toString(), fromPosition(position)); return worker.doHover(resource.toString(), fromPosition(position));
}).then(info => { })
.then((info) => {
if (!info) { if (!info) {
return; return;
} }
@ -336,49 +442,68 @@ function toLocation(location: jsonService.Location): languages.Location {
}; };
} }
// --- document symbols ------ // --- document symbols ------
function toSymbolKind(kind: jsonService.SymbolKind): languages.SymbolKind { function toSymbolKind(kind: jsonService.SymbolKind): languages.SymbolKind {
let mKind = languages.SymbolKind; let mKind = languages.SymbolKind;
switch (kind) { switch (kind) {
case jsonService.SymbolKind.File: return mKind.Array; case jsonService.SymbolKind.File:
case jsonService.SymbolKind.Module: return mKind.Module; return mKind.Array;
case jsonService.SymbolKind.Namespace: return mKind.Namespace; case jsonService.SymbolKind.Module:
case jsonService.SymbolKind.Package: return mKind.Package; return mKind.Module;
case jsonService.SymbolKind.Class: return mKind.Class; case jsonService.SymbolKind.Namespace:
case jsonService.SymbolKind.Method: return mKind.Method; return mKind.Namespace;
case jsonService.SymbolKind.Property: return mKind.Property; case jsonService.SymbolKind.Package:
case jsonService.SymbolKind.Field: return mKind.Field; return mKind.Package;
case jsonService.SymbolKind.Constructor: return mKind.Constructor; case jsonService.SymbolKind.Class:
case jsonService.SymbolKind.Enum: return mKind.Enum; return mKind.Class;
case jsonService.SymbolKind.Interface: return mKind.Interface; case jsonService.SymbolKind.Method:
case jsonService.SymbolKind.Function: return mKind.Function; return mKind.Method;
case jsonService.SymbolKind.Variable: return mKind.Variable; case jsonService.SymbolKind.Property:
case jsonService.SymbolKind.Constant: return mKind.Constant; return mKind.Property;
case jsonService.SymbolKind.String: return mKind.String; case jsonService.SymbolKind.Field:
case jsonService.SymbolKind.Number: return mKind.Number; return mKind.Field;
case jsonService.SymbolKind.Boolean: return mKind.Boolean; case jsonService.SymbolKind.Constructor:
case jsonService.SymbolKind.Array: return mKind.Array; return mKind.Constructor;
case jsonService.SymbolKind.Enum:
return mKind.Enum;
case jsonService.SymbolKind.Interface:
return mKind.Interface;
case jsonService.SymbolKind.Function:
return mKind.Function;
case jsonService.SymbolKind.Variable:
return mKind.Variable;
case jsonService.SymbolKind.Constant:
return mKind.Constant;
case jsonService.SymbolKind.String:
return mKind.String;
case jsonService.SymbolKind.Number:
return mKind.Number;
case jsonService.SymbolKind.Boolean:
return mKind.Boolean;
case jsonService.SymbolKind.Array:
return mKind.Array;
} }
return mKind.Function; return mKind.Function;
} }
export class DocumentSymbolAdapter implements languages.DocumentSymbolProvider { export class DocumentSymbolAdapter implements languages.DocumentSymbolProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { public provideDocumentSymbols(
} model: editor.IReadOnlyModel,
token: CancellationToken
public provideDocumentSymbols(model: editor.IReadOnlyModel, token: CancellationToken): Promise<languages.DocumentSymbol[]> { ): Promise<languages.DocumentSymbol[]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => worker.findDocumentSymbols(resource.toString())).then(items => { return this._worker(resource)
.then((worker) => worker.findDocumentSymbols(resource.toString()))
.then((items) => {
if (!items) { if (!items) {
return; return;
} }
return items.map(item => ({ return items.map((item) => ({
name: item.name, name: item.name,
detail: '', detail: '',
containerName: item.containerName, containerName: item.containerName,
@ -391,24 +516,30 @@ export class DocumentSymbolAdapter implements languages.DocumentSymbolProvider {
} }
} }
function fromFormattingOptions(
function fromFormattingOptions(options: languages.FormattingOptions): jsonService.FormattingOptions { options: languages.FormattingOptions
): jsonService.FormattingOptions {
return { return {
tabSize: options.tabSize, tabSize: options.tabSize,
insertSpaces: options.insertSpaces insertSpaces: options.insertSpaces
}; };
} }
export class DocumentFormattingEditProvider implements languages.DocumentFormattingEditProvider { export class DocumentFormattingEditProvider
implements languages.DocumentFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { public provideDocumentFormattingEdits(
} model: editor.IReadOnlyModel,
options: languages.FormattingOptions,
public provideDocumentFormattingEdits(model: editor.IReadOnlyModel, options: languages.FormattingOptions, token: CancellationToken): Promise<editor.ISingleEditOperation[]> { token: CancellationToken
): Promise<editor.ISingleEditOperation[]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => { return this._worker(resource).then((worker) => {
return worker.format(resource.toString(), null, fromFormattingOptions(options)).then(edits => { return worker
.format(resource.toString(), null, fromFormattingOptions(options))
.then((edits) => {
if (!edits || edits.length === 0) { if (!edits || edits.length === 0) {
return; return;
} }
@ -418,16 +549,26 @@ export class DocumentFormattingEditProvider implements languages.DocumentFormatt
} }
} }
export class DocumentRangeFormattingEditProvider implements languages.DocumentRangeFormattingEditProvider { export class DocumentRangeFormattingEditProvider
implements languages.DocumentRangeFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { public provideDocumentRangeFormattingEdits(
} model: editor.IReadOnlyModel,
range: Range,
public provideDocumentRangeFormattingEdits(model: editor.IReadOnlyModel, range: Range, options: languages.FormattingOptions, token: CancellationToken): Promise<editor.ISingleEditOperation[]> { options: languages.FormattingOptions,
token: CancellationToken
): Promise<editor.ISingleEditOperation[]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => { return this._worker(resource).then((worker) => {
return worker.format(resource.toString(), fromRange(range), fromFormattingOptions(options)).then(edits => { return worker
.format(
resource.toString(),
fromRange(range),
fromFormattingOptions(options)
)
.then((edits) => {
if (!edits || edits.length === 0) { if (!edits || edits.length === 0) {
return; return;
} }
@ -438,40 +579,57 @@ export class DocumentRangeFormattingEditProvider implements languages.DocumentRa
} }
export class DocumentColorAdapter implements languages.DocumentColorProvider { export class DocumentColorAdapter implements languages.DocumentColorProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { public provideDocumentColors(
} model: editor.IReadOnlyModel,
token: CancellationToken
public provideDocumentColors(model: editor.IReadOnlyModel, token: CancellationToken): Promise<languages.IColorInformation[]> { ): Promise<languages.IColorInformation[]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => worker.findDocumentColors(resource.toString())).then(infos => { return this._worker(resource)
.then((worker) => worker.findDocumentColors(resource.toString()))
.then((infos) => {
if (!infos) { if (!infos) {
return; return;
} }
return infos.map(item => ({ return infos.map((item) => ({
color: item.color, color: item.color,
range: toRange(item.range) range: toRange(item.range)
})); }));
}); });
} }
public provideColorPresentations(model: editor.IReadOnlyModel, info: languages.IColorInformation, token: CancellationToken): Promise<languages.IColorPresentation[]> { public provideColorPresentations(
model: editor.IReadOnlyModel,
info: languages.IColorInformation,
token: CancellationToken
): Promise<languages.IColorPresentation[]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => worker.getColorPresentations(resource.toString(), info.color, fromRange(info.range))).then(presentations => { return this._worker(resource)
.then((worker) =>
worker.getColorPresentations(
resource.toString(),
info.color,
fromRange(info.range)
)
)
.then((presentations) => {
if (!presentations) { if (!presentations) {
return; return;
} }
return presentations.map(presentation => { return presentations.map((presentation) => {
let item: languages.IColorPresentation = { let item: languages.IColorPresentation = {
label: presentation.label, label: presentation.label
}; };
if (presentation.textEdit) { if (presentation.textEdit) {
item.textEdit = toTextEdit(presentation.textEdit) item.textEdit = toTextEdit(presentation.textEdit);
} }
if (presentation.additionalTextEdits) { if (presentation.additionalTextEdits) {
item.additionalTextEdits = presentation.additionalTextEdits.map(toTextEdit) item.additionalTextEdits = presentation.additionalTextEdits.map(
toTextEdit
);
} }
return item; return item;
}); });
@ -480,54 +638,73 @@ export class DocumentColorAdapter implements languages.DocumentColorProvider {
} }
export class FoldingRangeAdapter implements languages.FoldingRangeProvider { export class FoldingRangeAdapter implements languages.FoldingRangeProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { public provideFoldingRanges(
} model: editor.IReadOnlyModel,
context: languages.FoldingContext,
public provideFoldingRanges(model: editor.IReadOnlyModel, context: languages.FoldingContext, token: CancellationToken): Promise<languages.FoldingRange[]> { token: CancellationToken
): Promise<languages.FoldingRange[]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => worker.getFoldingRanges(resource.toString(), context)).then(ranges => { return this._worker(resource)
.then((worker) => worker.getFoldingRanges(resource.toString(), context))
.then((ranges) => {
if (!ranges) { if (!ranges) {
return; return;
} }
return ranges.map(range => { return ranges.map((range) => {
let result: languages.FoldingRange = { let result: languages.FoldingRange = {
start: range.startLine + 1, start: range.startLine + 1,
end: range.endLine + 1 end: range.endLine + 1
}; };
if (typeof range.kind !== 'undefined') { if (typeof range.kind !== 'undefined') {
result.kind = toFoldingRangeKind(<jsonService.FoldingRangeKind>range.kind); result.kind = toFoldingRangeKind(
<jsonService.FoldingRangeKind>range.kind
);
} }
return result; return result;
}); });
}); });
} }
} }
function toFoldingRangeKind(kind: jsonService.FoldingRangeKind): languages.FoldingRangeKind { function toFoldingRangeKind(
kind: jsonService.FoldingRangeKind
): languages.FoldingRangeKind {
switch (kind) { switch (kind) {
case jsonService.FoldingRangeKind.Comment: return languages.FoldingRangeKind.Comment; case jsonService.FoldingRangeKind.Comment:
case jsonService.FoldingRangeKind.Imports: return languages.FoldingRangeKind.Imports; return languages.FoldingRangeKind.Comment;
case jsonService.FoldingRangeKind.Region: return languages.FoldingRangeKind.Region; case jsonService.FoldingRangeKind.Imports:
return languages.FoldingRangeKind.Imports;
case jsonService.FoldingRangeKind.Region:
return languages.FoldingRangeKind.Region;
} }
return void 0; return void 0;
} }
export class SelectionRangeAdapter implements languages.SelectionRangeProvider { export class SelectionRangeAdapter implements languages.SelectionRangeProvider {
constructor(private _worker: WorkerAccessor) {}
constructor(private _worker: WorkerAccessor) { public provideSelectionRanges(
} model: editor.IReadOnlyModel,
positions: Position[],
public provideSelectionRanges(model: editor.IReadOnlyModel, positions: Position[], token: CancellationToken): Promise<languages.SelectionRange[][]> { token: CancellationToken
): Promise<languages.SelectionRange[][]> {
const resource = model.uri; const resource = model.uri;
return this._worker(resource).then(worker => worker.getSelectionRanges(resource.toString(), positions.map(fromPosition))).then(selectionRanges => { return this._worker(resource)
.then((worker) =>
worker.getSelectionRanges(
resource.toString(),
positions.map(fromPosition)
)
)
.then((selectionRanges) => {
if (!selectionRanges) { if (!selectionRanges) {
return; return;
} }
return selectionRanges.map(selectionRange => { return selectionRanges.map((selectionRange) => {
const result: languages.SelectionRange[] = []; const result: languages.SelectionRange[] = [];
while (selectionRange) { while (selectionRange) {
result.push({ range: toRange(selectionRange.range) }); result.push({ range: toRange(selectionRange.range) });
@ -537,5 +714,4 @@ export class SelectionRangeAdapter implements languages.SelectionRangeProvider {
}); });
}); });
} }
} }

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as mode from './jsonMode'; import * as mode from './jsonMode';
import { Emitter, IEvent, languages } from './fillers/monaco-editor-core' import { Emitter, IEvent, languages } from './fillers/monaco-editor-core';
// --- JSON configuration and defaults --------- // --- JSON configuration and defaults ---------
@ -90,7 +90,6 @@ export interface ModeConfiguration {
* Defines whether the built-in selection range provider is enabled. * Defines whether the built-in selection range provider is enabled.
*/ */
readonly selectionRanges?: boolean; readonly selectionRanges?: boolean;
} }
export interface LanguageServiceDefaults { export interface LanguageServiceDefaults {
@ -103,13 +102,16 @@ export interface LanguageServiceDefaults {
} }
class LanguageServiceDefaultsImpl implements LanguageServiceDefaults { class LanguageServiceDefaultsImpl implements LanguageServiceDefaults {
private _onDidChange = new Emitter<LanguageServiceDefaults>(); private _onDidChange = new Emitter<LanguageServiceDefaults>();
private _diagnosticsOptions: DiagnosticsOptions; private _diagnosticsOptions: DiagnosticsOptions;
private _modeConfiguration: ModeConfiguration; private _modeConfiguration: ModeConfiguration;
private _languageId: string; private _languageId: string;
constructor(languageId: string, diagnosticsOptions: DiagnosticsOptions, modeConfiguration: ModeConfiguration) { constructor(
languageId: string,
diagnosticsOptions: DiagnosticsOptions,
modeConfiguration: ModeConfiguration
) {
this._languageId = languageId; this._languageId = languageId;
this.setDiagnosticsOptions(diagnosticsOptions); this.setDiagnosticsOptions(diagnosticsOptions);
this.setModeConfiguration(modeConfiguration); this.setModeConfiguration(modeConfiguration);
@ -139,7 +141,7 @@ class LanguageServiceDefaultsImpl implements LanguageServiceDefaults {
setModeConfiguration(modeConfiguration: ModeConfiguration): void { setModeConfiguration(modeConfiguration: ModeConfiguration): void {
this._modeConfiguration = modeConfiguration || Object.create(null); this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this); this._onDidChange.fire(this);
}; }
} }
const diagnosticDefault: Required<DiagnosticsOptions> = { const diagnosticDefault: Required<DiagnosticsOptions> = {
@ -160,9 +162,13 @@ const modeConfigurationDefault: Required<ModeConfiguration> = {
foldingRanges: true, foldingRanges: true,
diagnostics: true, diagnostics: true,
selectionRanges: true selectionRanges: true
} };
export const jsonDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl('json', diagnosticDefault, modeConfigurationDefault); export const jsonDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl(
'json',
diagnosticDefault,
modeConfigurationDefault
);
// export to the global based API // export to the global based API
(<any>languages).json = { jsonDefaults }; (<any>languages).json = { jsonDefaults };
@ -175,11 +181,19 @@ function getMode(): Promise<typeof mode> {
languages.register({ languages.register({
id: 'json', id: 'json',
extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc', '.har'], extensions: [
'.json',
'.bowerrc',
'.jshintrc',
'.jscsrc',
'.eslintrc',
'.babelrc',
'.har'
],
aliases: ['JSON', 'json'], aliases: ['JSON', 'json'],
mimetypes: ['application/json'], mimetypes: ['application/json']
}); });
languages.onLanguage('json', () => { languages.onLanguage('json', () => {
getMode().then(mode => mode.setupMode(jsonDefaults)); getMode().then((mode) => mode.setupMode(jsonDefaults));
}); });

View file

@ -4,12 +4,21 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as json from 'jsonc-parser'; import * as json from 'jsonc-parser';
import { languages } from './fillers/monaco-editor-core' import { languages } from './fillers/monaco-editor-core';
export function createTokenizationSupport(supportComments: boolean): languages.TokensProvider { export function createTokenizationSupport(
supportComments: boolean
): languages.TokensProvider {
return { return {
getInitialState: () => new JSONState(null, null, false), getInitialState: () => new JSONState(null, null, false),
tokenize: (line, state, offsetDelta?, stopAtOffset?) => tokenize(supportComments, line, <JSONState>state, offsetDelta, stopAtOffset) tokenize: (line, state, offsetDelta?, stopAtOffset?) =>
tokenize(
supportComments,
line,
<JSONState>state,
offsetDelta,
stopAtOffset
)
}; };
} }
@ -26,13 +35,16 @@ export const TOKEN_COMMENT_BLOCK = 'comment.block.json';
export const TOKEN_COMMENT_LINE = 'comment.line.json'; export const TOKEN_COMMENT_LINE = 'comment.line.json';
class JSONState implements languages.IState { class JSONState implements languages.IState {
private _state: languages.IState; private _state: languages.IState;
public scanError: json.ScanError; public scanError: json.ScanError;
public lastWasColon: boolean; public lastWasColon: boolean;
constructor(state: languages.IState, scanError: json.ScanError, lastWasColon: boolean) { constructor(
state: languages.IState,
scanError: json.ScanError,
lastWasColon: boolean
) {
this._state = state; this._state = state;
this.scanError = scanError; this.scanError = scanError;
this.lastWasColon = lastWasColon; this.lastWasColon = lastWasColon;
@ -49,8 +61,10 @@ class JSONState implements languages.IState {
if (!other || !(other instanceof JSONState)) { if (!other || !(other instanceof JSONState)) {
return false; return false;
} }
return this.scanError === (<JSONState>other).scanError && return (
this.lastWasColon === (<JSONState>other).lastWasColon; this.scanError === (<JSONState>other).scanError &&
this.lastWasColon === (<JSONState>other).lastWasColon
);
} }
public getStateData(): languages.IState { public getStateData(): languages.IState {
@ -62,8 +76,13 @@ class JSONState implements languages.IState {
} }
} }
function tokenize(comments: boolean, line: string, state: JSONState, offsetDelta: number = 0, stopAtOffset?: number): languages.ILineTokens { function tokenize(
comments: boolean,
line: string,
state: JSONState,
offsetDelta: number = 0,
stopAtOffset?: number
): languages.ILineTokens {
// handle multiline strings and block comments // handle multiline strings and block comments
var numberOfInsertedCharacters = 0, var numberOfInsertedCharacters = 0,
adjustOffset = false; adjustOffset = false;
@ -90,7 +109,6 @@ function tokenize(comments: boolean, line: string, state: JSONState, offsetDelta
}; };
while (true) { while (true) {
var offset = offsetDelta + scanner.getPosition(), var offset = offsetDelta + scanner.getPosition(),
type = ''; type = '';
@ -101,7 +119,10 @@ function tokenize(comments: boolean, line: string, state: JSONState, offsetDelta
// Check that the scanner has advanced // Check that the scanner has advanced
if (offset === offsetDelta + scanner.getPosition()) { if (offset === offsetDelta + scanner.getPosition()) {
throw new Error('Scanner did not advance, next 3 characters are: ' + line.substr(scanner.getPosition(), 3)); throw new Error(
'Scanner did not advance, next 3 characters are: ' +
line.substr(scanner.getPosition(), 3)
);
} }
// In case we inserted /* or " character, we need to // In case we inserted /* or " character, we need to
@ -111,7 +132,6 @@ function tokenize(comments: boolean, line: string, state: JSONState, offsetDelta
} }
adjustOffset = numberOfInsertedCharacters > 0; adjustOffset = numberOfInsertedCharacters > 0;
// brackets and type // brackets and type
switch (kind) { switch (kind) {
case json.SyntaxKind.OpenBraceToken: case json.SyntaxKind.OpenBraceToken:
@ -169,7 +189,11 @@ function tokenize(comments: boolean, line: string, state: JSONState, offsetDelta
} }
} }
ret.endState = new JSONState(state.getStateData(), scanner.getTokenError(), lastWasColon); ret.endState = new JSONState(
state.getStateData(),
scanner.getTokenError(),
lastWasColon
);
ret.tokens.push({ ret.tokens.push({
startIndex: offset, startIndex: offset,
scopes: type scopes: type

View file

@ -5,12 +5,11 @@
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { JSONWorker } from './jsonWorker'; import type { JSONWorker } from './jsonWorker';
import { IDisposable, Uri, editor } from './fillers/monaco-editor-core' import { IDisposable, Uri, editor } from './fillers/monaco-editor-core';
const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min
export class WorkerManager { export class WorkerManager {
private _defaults: LanguageServiceDefaults; private _defaults: LanguageServiceDefaults;
private _idleCheckInterval: number; private _idleCheckInterval: number;
private _lastUsedTime: number; private _lastUsedTime: number;
@ -24,7 +23,9 @@ export class WorkerManager {
this._worker = null; this._worker = null;
this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000); this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000);
this._lastUsedTime = 0; this._lastUsedTime = 0;
this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker()); this._configChangeListener = this._defaults.onDidChange(() =>
this._stopWorker()
);
} }
private _stopWorker(): void { private _stopWorker(): void {
@ -56,7 +57,6 @@ export class WorkerManager {
if (!this._client) { if (!this._client) {
this._worker = editor.createWebWorker<JSONWorker>({ this._worker = editor.createWebWorker<JSONWorker>({
// module that exports the create() method and returns a `JSONWorker` instance // module that exports the create() method and returns a `JSONWorker` instance
moduleId: 'vs/language/json/jsonWorker', moduleId: 'vs/language/json/jsonWorker',
@ -66,11 +66,12 @@ export class WorkerManager {
createData: { createData: {
languageSettings: this._defaults.diagnosticsOptions, languageSettings: this._defaults.diagnosticsOptions,
languageId: this._defaults.languageId, languageId: this._defaults.languageId,
enableSchemaRequest: this._defaults.diagnosticsOptions.enableSchemaRequest enableSchemaRequest: this._defaults.diagnosticsOptions
.enableSchemaRequest
} }
}); });
this._client = <Promise<JSONWorker>><any>this._worker.getProxy(); this._client = <Promise<JSONWorker>>(<any>this._worker.getProxy());
} }
return this._client; return this._client;
@ -78,10 +79,13 @@ export class WorkerManager {
getLanguageServiceWorker(...resources: Uri[]): Promise<JSONWorker> { getLanguageServiceWorker(...resources: Uri[]): Promise<JSONWorker> {
let _client: JSONWorker; let _client: JSONWorker;
return this._getClient().then((client) => { return this._getClient()
_client = client .then((client) => {
}).then(_ => { _client = client;
return this._worker.withSyncedResources(resources) })
}).then(_ => _client); .then((_) => {
return this._worker.withSyncedResources(resources);
})
.then((_) => _client);
} }
} }

View file

@ -3,19 +3,25 @@
<head> <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" data-name="vs/editor/editor.main" href="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.css"> <link
rel="stylesheet"
data-name="vs/editor/editor.main"
href="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.css"
/>
</head> </head>
<body> <body>
<h2>Monaco Editor JSON test page</h2> <h2>Monaco Editor JSON test page</h2>
<div id="container" style="width:800px;height:600px;border:1px solid grey"></div> <div
id="container"
style="width: 800px; height: 600px; border: 1px solid grey"
></div>
<script> <script>
// Loading basic-languages to get the json language definition // Loading basic-languages to get the json language definition
var paths = { var paths = {
'vs/basic-languages': '../node_modules/monaco-languages/release/dev', 'vs/basic-languages': '../node_modules/monaco-languages/release/dev',
'vs/language/json': '../release/dev', 'vs/language/json': '../release/dev',
'vs': '../node_modules/monaco-editor-core/dev/vs' vs: '../node_modules/monaco-editor-core/dev/vs'
}; };
if (document.location.protocol === 'http:') { if (document.location.protocol === 'http:') {
// Add support for running local http server // Add support for running local http server
@ -38,7 +44,9 @@
'vs/basic-languages/monaco.contribution', 'vs/basic-languages/monaco.contribution',
'vs/language/json/monaco.contribution' 'vs/language/json/monaco.contribution'
], function () { ], function () {
var editor = monaco.editor.create(document.getElementById('container'), { var editor = monaco.editor.create(
document.getElementById('container'),
{
value: [ value: [
'{', '{',
' "type": "team",', ' "type": "team",',
@ -107,12 +115,12 @@
' "allowMultipleWorkers": true', ' "allowMultipleWorkers": true',
' }', ' }',
' }', ' }',
'}', '}'
].join('\n'), ].join('\n'),
language: 'json' language: 'json'
}); }
);
}); });
</script> </script>
</body> </body>
</html> </html>