Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[plugin] basic support of snippets #3977

Merged
merged 3 commits into from
Jan 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@
"--no-app-auto-install"
],
"env": {
"NODE_ENV": "development"
"NODE_ENV": "development",
"THEIA_DEFAULT_PLUGINS": "local-dir:plugins"
},
"sourceMaps": true,
"outFiles": [
Expand Down
2 changes: 1 addition & 1 deletion examples/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
"clean": "theia clean && rimraf errorShots",
"build": "theia build --mode development",
"watch": "yarn build --watch",
"start": "theia start",
"start": "export THEIA_DEFAULT_PLUGINS=local-dir:../../plugins && theia start",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will it be committed ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found myself doing it over and over, and thought that we can specify relative plugins location for testing purposes.

Actually, i think maybe we should add a new example that includes only plugin-ext-vscode and its dependency, and exclude all irrelevant Theia extensions.

// cc @svenefftinge

"start:debug": "yarn start --log-level=debug",
"test": "wdio wdio.conf.js",
"test-non-headless": "wdio wdio-non-headless.conf.js",
Expand Down
1 change: 1 addition & 0 deletions packages/monaco/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"@theia/markers": "^0.3.18",
"@theia/outline-view": "^0.3.18",
"@theia/workspace": "^0.3.18",
"jsonc-parser": "^2.0.2",
"monaco-css": "^2.0.1",
"monaco-html": "^2.0.2",
"onigasm": "^2.1.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,23 @@
import { injectable, inject } from 'inversify';
import { FrontendApplicationContribution } from '@theia/core/lib/browser';
import { ThemeService } from '@theia/core/lib/browser/theming';
import { MonacoSnippetSuggestProvider } from './monaco-snippet-suggest-provider';

@injectable()
export class MonacoFrontendApplicationContribution implements FrontendApplicationContribution {

@inject(ThemeService)
protected readonly themeService: ThemeService;

@inject(MonacoSnippetSuggestProvider)
protected readonly snippetSuggestProvider: MonacoSnippetSuggestProvider;

async initialize() {
const currentTheme = this.themeService.getCurrentTheme();
this.changeTheme(currentTheme.editorTheme);
this.themeService.onThemeChange(event => this.changeTheme(event.newTheme.editorTheme));

monaco.suggest.setSnippetSuggestSupport(this.snippetSuggestProvider);
}

protected changeTheme(editorTheme: string | undefined) {
Expand Down
14 changes: 8 additions & 6 deletions packages/monaco/src/browser/monaco-frontend-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import '../../src/browser/style/index.css';
import '../../src/browser/style/symbol-sprite.svg';
import '../../src/browser/style/symbol-icons.css';

import { ContainerModule, decorate, injectable } from 'inversify';
import { MenuContribution, CommandContribution } from '@theia/core/lib/common';
import { QuickOpenService, FrontendApplicationContribution, KeybindingContribution } from '@theia/core/lib/browser';
Expand Down Expand Up @@ -43,17 +47,15 @@ import MonacoTextmateModuleBinder from './textmate/monaco-textmate-frontend-bind
import { MonacoSemanticHighlightingService } from './monaco-semantic-highlighting-service';
import { SemanticHighlightingService } from '@theia/editor/lib/browser/semantic-highlight/semantic-highlighting-service';
import { MonacoBulkEditService } from './monaco-bulk-edit-service';
import { MonacoOutlineDecorator } from './monaco-outline-decorator';
import { OutlineTreeDecorator } from '@theia/outline-view/lib/browser/outline-decorator-service';
import { MonacoSnippetSuggestProvider } from './monaco-snippet-suggest-provider';

decorate(injectable(), MonacoToProtocolConverter);
decorate(injectable(), ProtocolToMonacoConverter);

import '../../src/browser/style/index.css';
import '../../src/browser/style/symbol-sprite.svg';
import '../../src/browser/style/symbol-icons.css';
import { MonacoOutlineDecorator } from './monaco-outline-decorator';
import { OutlineTreeDecorator } from '@theia/outline-view/lib/browser/outline-decorator-service';

export default new ContainerModule((bind, unbind, isBound, rebind) => {
bind(MonacoSnippetSuggestProvider).toSelf().inSingletonScope();
bind(FrontendApplicationContribution).to(MonacoFrontendApplicationContribution).inSingletonScope();

bind(MonacoToProtocolConverter).toSelf().inSingletonScope();
Expand Down
195 changes: 195 additions & 0 deletions packages/monaco/src/browser/monaco-snippet-suggest-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/********************************************************************************
* Copyright (C) 2019 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
import * as jsoncparser from 'jsonc-parser';
import { injectable, inject } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { FileSystem, FileSystemError } from '@theia/filesystem/lib/common';

@injectable()
export class MonacoSnippetSuggestProvider implements monaco.modes.ISuggestSupport {

@inject(FileSystem)
protected readonly filesystem: FileSystem;

protected readonly snippets = new Map<string, MonacoSnippetSuggestion[]>();
protected readonly pendingSnippets = new Map<string, Promise<void>[]>();

async provideCompletionItems(model: monaco.editor.ITextModel): Promise<monaco.modes.ISuggestResult> {
const languageId = model.getModeId(); // TODO: look up a language id at the position
await this.loadSnippets(languageId);
const suggestions = this.snippets.get(languageId) || [];
return { suggestions };
}

resolveCompletionItem(_: monaco.editor.ITextModel, __: monaco.Position, item: monaco.modes.ISuggestion): monaco.modes.ISuggestion {
return item instanceof MonacoSnippetSuggestion ? item.resolve() : item;
}

protected async loadSnippets(scope: string): Promise<void> {
const pending: Promise<void>[] = [];
pending.push(...(this.pendingSnippets.get(scope) || []));
pending.push(...(this.pendingSnippets.get('*') || []));
if (pending.length) {
await Promise.all(pending);
}
}

fromURI(uri: string | URI, options: SnippetLoadOptions): Promise<void> {
const pending = this.loadURI(uri, options);
const { language } = options;
const scopes = Array.isArray(language) ? language : !!language ? [language] : ['*'];
for (const scope of scopes) {
const pendingSnippets = this.pendingSnippets.get(scope) || [];
pendingSnippets.push(pending);
this.pendingSnippets.set(scope, pendingSnippets);
}
return pending;
}
/**
* should NOT throw to prevent load erros on suggest
*/
protected async loadURI(uri: string | URI, options: SnippetLoadOptions): Promise<void> {
try {
const { content } = await this.filesystem.resolveContent(uri.toString(), { encoding: 'utf-8' });
const snippets = content && jsoncparser.parse(content, undefined, { disallowComments: false });
this.fromJSON(snippets, options);
} catch (e) {
if (!FileSystemError.FileNotFound.is(e) && !FileSystemError.FileIsDirectory.is(e)) {
console.error(e);
}
}
}

fromJSON(snippets: JsonSerializedSnippets | undefined, { language, source }: SnippetLoadOptions): void {
this.parseSnippets(snippets, (name, snippet) => {
let { prefix, body, description } = snippet;
if (Array.isArray(body)) {
body = body.join('\n');
}
if (typeof prefix !== 'string' || typeof body !== 'string') {
return;
}
const scopes: string[] = [];
if (language) {
if (Array.isArray(language)) {
scopes.push(...language);
} else {
scopes.push(language);
}
} else if (typeof snippet.scope === 'string') {
for (const rawScope of snippet.scope.split(',')) {
const scope = rawScope.trim();
if (scope) {
scopes.push(scope);
}
}
}
this.push({
scopes,
name,
prefix,
description,
body,
source
});
});
}
protected parseSnippets(snippets: JsonSerializedSnippets | undefined, accept: (name: string, snippet: JsonSerializedSnippet) => void): void {
if (typeof snippets === 'object') {
// tslint:disable-next-line:forin
for (const name in snippets) {
const scopeOrTemplate = snippets[name];
if (JsonSerializedSnippet.is(scopeOrTemplate)) {
accept(name, scopeOrTemplate);
} else {
this.parseSnippets(scopeOrTemplate, accept);
}
}
}
}

push(...snippets: Snippet[]): void {
for (const snippet of snippets) {
for (const scope of snippet.scopes) {
const languageSnippets = this.snippets.get(scope) || [];
languageSnippets.push(new MonacoSnippetSuggestion(snippet));
this.snippets.set(scope, languageSnippets);
}
}
}

}

export interface SnippetLoadOptions {
language?: string | string[]
source: string
}

export interface JsonSerializedSnippets {
[name: string]: JsonSerializedSnippet | { [name: string]: JsonSerializedSnippet };
}
export interface JsonSerializedSnippet {
body: string | string[];
scope: string;
prefix: string;
description: string;
}
export namespace JsonSerializedSnippet {
export function is(obj: Object | undefined): obj is JsonSerializedSnippet {
return typeof obj === 'object' && 'body' in obj && 'prefix' in obj;
}
}

export interface Snippet {
readonly scopes: string[]
readonly name: string
readonly prefix: string
readonly description: string
readonly body: string
readonly source: string
}

export class MonacoSnippetSuggestion implements monaco.modes.ISuggestion {

readonly label: string;
readonly detail: string;
readonly sortText: string;
readonly noAutoAccept = true;
readonly type: 'snippet' = 'snippet';
readonly snippetType: 'textmate' = 'textmate';

insertText: string;
documentation?: monaco.IMarkdownString;

constructor(protected readonly snippet: Snippet) {
this.label = snippet.prefix;
this.detail = `${snippet.description || snippet.name} (${snippet.source})`;
this.insertText = snippet.body;
this.sortText = `z-${snippet.prefix}`;
}

protected resolved = false;
resolve(): MonacoSnippetSuggestion {
if (!this.resolved) {
const codeSnippet = new monaco.snippetParser.SnippetParser().parse(this.snippet.body).toString();
this.insertText = codeSnippet;
this.documentation = { value: '```\n' + codeSnippet + '```' };
this.resolved = true;
}
return this;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

/**
* @deprecated use MonacoSnippetSuggestProvider instead
*/
export class TextmateSnippetCompletionProvider implements monaco.languages.CompletionItemProvider {

private items: monaco.languages.CompletionItem[];
Expand Down Expand Up @@ -42,17 +45,23 @@ export class TextmateSnippetCompletionProvider implements monaco.languages.Compl
}

provideCompletionItems(document: monaco.editor.ITextModel,
position: monaco.Position,
token: monaco.CancellationToken,
context: monaco.languages.CompletionContext): monaco.languages.CompletionItem[] {
position: monaco.Position,
token: monaco.CancellationToken,
context: monaco.languages.CompletionContext): monaco.languages.CompletionItem[] {
return this.items;
}
}

/**
* @deprecated use JsonSerializedSnippets & MonacoSnippetSuggestProvider instead
*/
export interface TextmateSnippets {
[name: string]: TextmateSnippet;
}

/**
* @deprecated use JsonSerializedSnippet & MonacoSnippetSuggestProvider instead
*/
export interface TextmateSnippet {
readonly prefix: string,
readonly body: string[],
Expand Down
2 changes: 2 additions & 0 deletions packages/monaco/src/typings/monaco/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,8 @@ declare module monaco.suggest {
token?: monaco.CancellationToken
): Promise<ISuggestionItem[]>;

export function setSnippetSuggestSupport(support: monaco.modes.ISuggestSupport): monaco.modes.ISuggestSupport;

}

declare module monaco.suggestController {
Expand Down
Loading