wordDistance.ts 1.9 KB
Newer Older
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  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 已提交
8
import { binarySearch, isFalsyOrEmpty } from 'vs/base/common/arrays';
9 10 11
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { IPosition } from 'vs/editor/common/core/position';
J
Johannes Rieken 已提交
12
import { Range } from 'vs/editor/common/core/range';
13 14 15 16


export abstract class WordDistance {

J
Johannes Rieken 已提交
17 18 19 20
	static readonly None = new class extends WordDistance {
		distance() { return 0; }
	};

21 22
	static create(service: IEditorWorkerService, editor: ICodeEditor): Thenable<WordDistance> {

J
Johannes Rieken 已提交
23 24 25 26
		if (!editor.getConfiguration().contribInfo.suggest.localityBonus) {
			return Promise.resolve(WordDistance.None);
		}

27 28
		const model = editor.getModel();
		const position = editor.getPosition();
J
Johannes Rieken 已提交
29
		const range = new Range(Math.max(1, position.lineNumber - 100), 1, Math.min(model.getLineCount() - 1, position.lineNumber + 100), 1);
30

J
Johannes Rieken 已提交
31
		return service.computeWordLines(model.uri, range).then(lineNumbers => {
32 33 34

			return new class extends WordDistance {
				distance(anchor: IPosition, word: string) {
J
Johannes Rieken 已提交
35
					if (!lineNumbers || !position.equals(editor.getPosition())) {
36 37
						return 0;
					}
J
Johannes Rieken 已提交
38 39 40
					let wordLines = lineNumbers[word];
					if (isFalsyOrEmpty(wordLines)) {
						return 101;
41
					}
J
Johannes Rieken 已提交
42
					let idx = binarySearch(wordLines, anchor.lineNumber, (a, b) => a - b);
43 44 45
					if (idx >= 0) {
						return 0;
					} else {
J
Johannes Rieken 已提交
46 47
						idx = Math.max(0, ~idx - 1);
						return Math.abs(wordLines[idx] - anchor.lineNumber);
48 49 50 51 52 53 54 55 56 57
					}
				}
			};
		});
	}

	abstract distance(anchor: IPosition, word: string): number;
}