suggest.ts 6.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

J
Johannes Rieken 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20
import { sequence, asWinJsPromise } from 'vs/base/common/async';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { compare } from 'vs/base/common/strings';
import { assign } from 'vs/base/common/objects';
import { onUnexpectedError } from 'vs/base/common/errors';
import { TPromise } from 'vs/base/common/winjs.base';
import { IReadOnlyModel, IPosition } from 'vs/editor/common/editorCommon';
import { CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions';
import { ISuggestResult, ISuggestSupport, ISuggestion, SuggestRegistry } from 'vs/editor/common/modes';
import { ISnippetsRegistry, Extensions } from 'vs/editor/common/modes/snippetsRegistry';
import { Position } from 'vs/editor/common/core/position';
import { Registry } from 'vs/platform/platform';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { DefaultConfig } from 'vs/editor/common/config/defaultConfig';
E
Erich Gamma 已提交
21

22
export const Context = {
A
Alex Dima 已提交
23 24
	Visible: new RawContextKey<boolean>('suggestWidgetVisible', false),
	MultipleSuggestions: new RawContextKey<boolean>('suggestWidgetMultipleSuggestions', false),
25 26
	AcceptOnKey: new RawContextKey<boolean>('suggestionSupportsAcceptOnKey', true),
	AcceptSuggestionsOnEnter: new RawContextKey<boolean>('acceptSuggestionOnEnter', DefaultConfig.editor.acceptSuggestionOnEnter)
27
};
E
Erich Gamma 已提交
28

29
export interface ISuggestionItem {
30
	position: IPosition;
31 32 33
	suggestion: ISuggestion;
	container: ISuggestResult;
	support: ISuggestSupport;
34
	resolve(): TPromise<void>;
35 36
}

37
export type SnippetConfig = 'top' | 'bottom' | 'inline' | 'none';
38

39 40

// add suggestions from snippet registry.
41
export const snippetSuggestSupport: ISuggestSupport = {
42 43 44

	triggerCharacters: [],

45
	provideCompletionItems(model: IReadOnlyModel, position: Position): ISuggestResult {
46 47 48 49
		const suggestions = Registry.as<ISnippetsRegistry>(Extensions.Snippets).getSnippetCompletions(model, position);
		if (suggestions) {
			return { suggestions, currentWord: '' };
		}
50 51
	}
};
52

53
export function provideSuggestionItems(model: IReadOnlyModel, position: Position, snippetConfig: SnippetConfig = 'bottom', onlyFrom?: ISuggestSupport[]): TPromise<ISuggestionItem[]> {
54

55
	const result: ISuggestionItem[] = [];
56
	const acceptSuggestion = createSuggesionFilter(snippetConfig);
57

58 59
	position = position.clone();

60
	// get provider groups, always add snippet suggestion provider
61
	const supports = SuggestRegistry.orderedGroups(model);
62
	supports.unshift([snippetSuggestSupport]);
63 64 65 66

	// add suggestions from contributed providers - providers are ordered in groups of
	// equal score and once a group produces a result the process stops
	let hasResult = false;
67
	const factory = supports.map(supports => {
68 69 70
		return () => {
			// stop when we have a result
			if (hasResult) {
71 72 73
				return;
			}
			// for each support in the group ask for suggestions
74 75 76 77 78
			return TPromise.join(supports.map(support => {

				if (!isFalsyOrEmpty(onlyFrom) && onlyFrom.indexOf(support) < 0) {
					return;
				}
79

80
				return asWinJsPromise(token => support.provideCompletionItems(model, position, token)).then(container => {
81

82
					const len = result.length;
83

84 85 86
					if (container && !isFalsyOrEmpty(container.suggestions)) {
						for (let suggestion of container.suggestions) {
							if (acceptSuggestion(suggestion)) {
87

88 89 90
								fixOverwriteBeforeAfter(suggestion, container);

								result.push({
91
									position,
92 93 94 95 96 97
									container,
									suggestion,
									support,
									resolve: createSuggestionResolver(support, suggestion, model, position)
								});
							}
98
						}
J
Johannes Rieken 已提交
99
					}
100

101 102 103
					if (len !== result.length && support !== snippetSuggestSupport) {
						hasResult = true;
					}
104

105 106
				}, onUnexpectedError);
			}));
107 108
		};
	});
J
Johannes Rieken 已提交
109

J
Johannes Rieken 已提交
110
	return sequence(factory).then(() => result.sort(getSuggestionComparator(snippetConfig)));
111
}
112

113 114 115 116 117 118 119 120 121
function fixOverwriteBeforeAfter(suggestion: ISuggestion, container: ISuggestResult): void {
	if (typeof suggestion.overwriteBefore !== 'number') {
		suggestion.overwriteBefore = container.currentWord.length;
	}
	if (typeof suggestion.overwriteAfter !== 'number' || suggestion.overwriteAfter < 0) {
		suggestion.overwriteAfter = 0;
	}
}

122 123 124 125 126 127 128 129 130 131
function createSuggestionResolver(provider: ISuggestSupport, suggestion: ISuggestion, model: IReadOnlyModel, position: Position): () => TPromise<void> {
	return () => {
		if (typeof provider.resolveCompletionItem === 'function') {
			return asWinJsPromise(token => provider.resolveCompletionItem(model, position, suggestion, token))
				.then(value => { assign(suggestion, value); });
		}
		return TPromise.as(void 0);
	};
}

132 133
function createSuggesionFilter(snippetConfig: SnippetConfig): (candidate: ISuggestion) => boolean {
	if (snippetConfig === 'none') {
134 135
		return suggestion => suggestion.type !== 'snippet';
	} else {
136
		return () => true;
137 138
	}
}
139

J
Johannes Rieken 已提交
140
export function getSuggestionComparator(snippetConfig: SnippetConfig): (a: ISuggestionItem, b: ISuggestionItem) => number {
141

142 143
	function defaultComparator(a: ISuggestionItem, b: ISuggestionItem): number {

144 145 146
		let ret = 0;

		// check with 'sortText'
147
		if (typeof a.suggestion.sortText === 'string' && typeof b.suggestion.sortText === 'string') {
148 149
			ret = compare(a.suggestion.sortText.toLowerCase(), b.suggestion.sortText.toLowerCase());
		}
150

151 152 153 154 155 156 157 158 159 160 161
		// check with 'label'
		if (!ret) {
			ret = compare(a.suggestion.label.toLowerCase(), b.suggestion.label.toLowerCase());
		}

		// check with 'type' and lower snippets
		if (!ret && a.suggestion.type !== b.suggestion.type) {
			if (a.suggestion.type === 'snippet') {
				ret = 1;
			} else if (b.suggestion.type === 'snippet') {
				ret = -1;
162 163 164
			}
		}

165
		return ret;
166 167 168 169 170 171 172 173 174 175
	}

	function snippetUpComparator(a: ISuggestionItem, b: ISuggestionItem): number {
		if (a.suggestion.type !== b.suggestion.type) {
			if (a.suggestion.type === 'snippet') {
				return -1;
			} else if (b.suggestion.type === 'snippet') {
				return 1;
			}
		}
176
		return defaultComparator(a, b);
177 178 179 180 181 182 183 184 185 186
	}

	function snippetDownComparator(a: ISuggestionItem, b: ISuggestionItem): number {
		if (a.suggestion.type !== b.suggestion.type) {
			if (a.suggestion.type === 'snippet') {
				return 1;
			} else if (b.suggestion.type === 'snippet') {
				return -1;
			}
		}
187
		return defaultComparator(a, b);
188 189
	}

190
	if (snippetConfig === 'top') {
191
		return snippetUpComparator;
192
	} else if (snippetConfig === 'bottom') {
193 194 195 196
		return snippetDownComparator;
	} else {
		return defaultComparator;
	}
197 198 199
}

CommonEditorRegistry.registerDefaultLanguageCommand('_executeCompletionItemProvider', (model, position, args) => {
200
	return provideSuggestionItems(model, position);
J
Johannes Rieken 已提交
201
});