bracketMatching.ts 11.3 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import 'vs/css!./bracketMatching';
7 8 9 10 11
import * as nls from 'vs/nls';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import { Range } from 'vs/editor/common/core/range';
import { Position } from 'vs/editor/common/core/position';
12
import { Selection } from 'vs/editor/common/core/selection';
13
import { RunOnceScheduler } from 'vs/base/common/async';
14
import * as editorCommon from 'vs/editor/common/editorCommon';
T
Tomás Oliveira 已提交
15
import { EditorAction, registerEditorAction, registerEditorContribution, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
16
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
F
francis-andrade 已提交
17 18
import { registerThemingParticipant, themeColorFromId } from 'vs/platform/theme/common/themeService';
import { editorBracketMatchBackground, editorBracketMatchBorder } from 'vs/editor/common/view/editorColorRegistry';
A
Alex Dima 已提交
19
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
20
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
A
Alex Dima 已提交
21
import { registerColor } from 'vs/platform/theme/common/colorRegistry';
22
import { TrackedRangeStickiness, IModelDeltaDecoration, OverviewRulerLane } from 'vs/editor/common/model';
23
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
F
francis-andrade 已提交
24

A
Alex Dima 已提交
25
const overviewRulerBracketMatchForeground = registerColor('editorOverviewRuler.bracketMatchForeground', { dark: '#A0A0A0', light: '#A0A0A0', hc: '#A0A0A0' }, nls.localize('overviewRulerBracketMatchForeground', 'Overview ruler marker color for matching brackets.'));
F
francis-andrade 已提交
26

A
Afonso Pinto 已提交
27
class JumpToBracketAction extends EditorAction {
28 29 30 31 32 33 34
	constructor() {
		super({
			id: 'editor.action.jumpToBracket',
			label: nls.localize('smartSelect.jumpBracket', "Go to Bracket"),
			alias: 'Go to Bracket',
			precondition: null,
			kbOpts: {
35
				kbExpr: EditorContextKeys.editorTextFocus,
A
Alex Dima 已提交
36
				primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_BACKSLASH,
37
				weight: KeybindingWeight.EditorContrib
38 39 40 41
			}
		});
	}

42
	public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
43 44 45 46 47 48 49 50
		let controller = BracketMatchingController.get(editor);
		if (!controller) {
			return;
		}
		controller.jumpToBracket();
	}
}

A
Afonso Pinto 已提交
51 52 53 54 55 56
class SelectToBracketAction extends EditorAction {
	constructor() {
		super({
			id: 'editor.action.selectToBracket',
			label: nls.localize('smartSelect.selectToBracket', "Select to Bracket"),
			alias: 'Select to Bracket',
57
			precondition: null
A
Afonso Pinto 已提交
58 59 60 61 62 63 64 65 66 67 68 69
		});
	}

	public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
		let controller = BracketMatchingController.get(editor);
		if (!controller) {
			return;
		}
		controller.selectToBracket();
	}
}

70 71 72 73
type Brackets = [Range, Range];

class BracketsData {
	public readonly position: Position;
A
Alex Dima 已提交
74
	public readonly brackets: Brackets | null;
75

A
Alex Dima 已提交
76
	constructor(position: Position, brackets: Brackets | null) {
77 78 79 80 81 82
		this.position = position;
		this.brackets = brackets;
	}
}

export class BracketMatchingController extends Disposable implements editorCommon.IEditorContribution {
83
	private static readonly ID = 'editor.contrib.bracketMatchingController';
84

85
	public static get(editor: ICodeEditor): BracketMatchingController {
86 87 88
		return editor.getContribution<BracketMatchingController>(BracketMatchingController.ID);
	}

89
	private readonly _editor: ICodeEditor;
90 91 92 93

	private _lastBracketsData: BracketsData[];
	private _lastVersionId: number;
	private _decorations: string[];
94
	private _updateBracketsSoon: RunOnceScheduler;
95
	private _matchBrackets: boolean;
96

97
	constructor(
98
		editor: ICodeEditor
99
	) {
100 101 102 103 104
		super();
		this._editor = editor;
		this._lastBracketsData = [];
		this._lastVersionId = 0;
		this._decorations = [];
105
		this._updateBracketsSoon = this._register(new RunOnceScheduler(() => this._updateBrackets(), 50));
106
		this._matchBrackets = this._editor.getConfiguration().contribInfo.matchBrackets;
107

108
		this._updateBracketsSoon.schedule();
109 110 111 112 113 114 115 116 117 118
		this._register(editor.onDidChangeCursorPosition((e) => {

			if (!this._matchBrackets) {
				// Early exit if nothing needs to be done!
				// Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
				return;
			}

			this._updateBracketsSoon.schedule();
		}));
A
Alex Dima 已提交
119 120 121 122
		this._register(editor.onDidChangeModelContent((e) => {
			this._updateBracketsSoon.schedule();
		}));
		this._register(editor.onDidChangeModel((e) => {
123
			this._lastBracketsData = [];
A
Alex Dima 已提交
124 125 126
			this._decorations = [];
			this._updateBracketsSoon.schedule();
		}));
127 128 129 130
		this._register(editor.onDidChangeModelLanguageConfiguration((e) => {
			this._lastBracketsData = [];
			this._updateBracketsSoon.schedule();
		}));
131 132 133 134 135 136 137 138
		this._register(editor.onDidChangeConfiguration((e) => {
			this._matchBrackets = this._editor.getConfiguration().contribInfo.matchBrackets;
			if (!this._matchBrackets && this._decorations.length > 0) {
				// Remove existing decorations if bracket matching is off
				this._decorations = this._editor.deltaDecorations(this._decorations, []);
			}
			this._updateBracketsSoon.schedule();
		}));
139 140 141 142 143 144 145
	}

	public getId(): string {
		return BracketMatchingController.ID;
	}

	public jumpToBracket(): void {
A
Alex Dima 已提交
146
		if (!this._editor.hasModel()) {
147 148 149
			return;
		}

A
Alex Dima 已提交
150 151
		const model = this._editor.getModel();
		const newSelections = this._editor.getSelections().map(selection => {
152
			const position = selection.getStartPosition();
153

154 155
			// find matching brackets if position is on a bracket
			const brackets = model.matchBracket(position);
156
			let newCursorPosition: Position | null = null;
157 158 159 160 161 162 163 164 165 166 167 168 169
			if (brackets) {
				if (brackets[0].containsPosition(position)) {
					newCursorPosition = brackets[1].getStartPosition();
				} else if (brackets[1].containsPosition(position)) {
					newCursorPosition = brackets[0].getStartPosition();
				}
			} else {
				// find the next bracket if the position isn't on a matching bracket
				const nextBracket = model.findNextBracket(position);
				if (nextBracket && nextBracket.range) {
					newCursorPosition = nextBracket.range.getStartPosition();
				}
			}
170

171 172 173 174 175
			if (newCursorPosition) {
				return new Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
			}
			return new Selection(position.lineNumber, position.column, position.lineNumber, position.column);
		});
176

177
		this._editor.setSelections(newSelections);
178
		this._editor.revealRange(newSelections[0]);
179 180
	}

A
Afonso Pinto 已提交
181
	public selectToBracket(): void {
A
Alex Dima 已提交
182
		if (!this._editor.hasModel()) {
D
DavidPortoUP 已提交
183 184 185
			return;
		}

A
Alex Dima 已提交
186 187
		const model = this._editor.getModel();
		const newSelections: Selection[] = [];
188 189 190

		this._editor.getSelections().forEach(selection => {
			const position = selection.getStartPosition();
D
DavidPortoUP 已提交
191

192
			let brackets = model.matchBracket(position);
A
Afonso Pinto 已提交
193

194 195
			let openBracket: Position | null = null;
			let closeBracket: Position | null = null;
A
Afonso Pinto 已提交
196

197 198 199 200 201
			if (!brackets) {
				const nextBracket = model.findNextBracket(position);
				if (nextBracket && nextBracket.range) {
					brackets = model.matchBracket(nextBracket.range.getStartPosition());
				}
A
Afonso Pinto 已提交
202 203
			}

204 205 206 207 208 209 210 211 212 213 214 215
			if (brackets) {
				if (brackets[0].startLineNumber === brackets[1].startLineNumber) {
					openBracket = brackets[1].startColumn < brackets[0].startColumn ?
						brackets[1].getStartPosition() : brackets[0].getStartPosition();
					closeBracket = brackets[1].startColumn < brackets[0].startColumn ?
						brackets[0].getEndPosition() : brackets[1].getEndPosition();
				} else {
					openBracket = brackets[1].startLineNumber < brackets[0].startLineNumber ?
						brackets[1].getStartPosition() : brackets[0].getStartPosition();
					closeBracket = brackets[1].startLineNumber < brackets[0].startLineNumber ?
						brackets[0].getEndPosition() : brackets[1].getEndPosition();
				}
D
DavidPortoUP 已提交
216
			}
A
Afonso Pinto 已提交
217

218 219 220 221 222 223 224 225 226
			if (openBracket && closeBracket) {
				newSelections.push(new Selection(openBracket.lineNumber, openBracket.column, closeBracket.lineNumber, closeBracket.column));
			}
		});


		if (newSelections.length > 0) {
			this._editor.setSelections(newSelections);
			this._editor.revealRange(newSelections[0]);
D
DavidPortoUP 已提交
227 228 229 230
		}
	}


231
	private static readonly _DECORATION_OPTIONS = ModelDecorationOptions.register({
232
		stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
F
francis-andrade 已提交
233 234
		className: 'bracket-match',
		overviewRuler: {
A
Alex Dima 已提交
235
			color: themeColorFromId(overviewRulerBracketMatchForeground),
236
			position: OverviewRulerLane.Center
F
francis-andrade 已提交
237
		}
238
	});
239 240

	private _updateBrackets(): void {
241 242 243
		if (!this._matchBrackets) {
			return;
		}
244 245
		this._recomputeBrackets();

246
		let newDecorations: IModelDeltaDecoration[] = [], newDecorationsLen = 0;
247 248
		for (let i = 0, len = this._lastBracketsData.length; i < len; i++) {
			let brackets = this._lastBracketsData[i].brackets;
249
			if (brackets) {
250 251 252 253 254 255 256 257 258
				newDecorations[newDecorationsLen++] = { range: brackets[0], options: BracketMatchingController._DECORATION_OPTIONS };
				newDecorations[newDecorationsLen++] = { range: brackets[1], options: BracketMatchingController._DECORATION_OPTIONS };
			}
		}

		this._decorations = this._editor.deltaDecorations(this._decorations, newDecorations);
	}

	private _recomputeBrackets(): void {
A
Alex Dima 已提交
259
		if (!this._editor.hasModel()) {
260 261 262 263 264 265
			// no model => no brackets!
			this._lastBracketsData = [];
			this._lastVersionId = 0;
			return;
		}

A
Alex Dima 已提交
266
		const model = this._editor.getModel();
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
		const versionId = model.getVersionId();
		let previousData: BracketsData[] = [];
		if (this._lastVersionId === versionId) {
			// use the previous data only if the model is at the same version id
			previousData = this._lastBracketsData;
		}

		const selections = this._editor.getSelections();

		let positions: Position[] = [], positionsLen = 0;
		for (let i = 0, len = selections.length; i < len; i++) {
			let selection = selections[i];

			if (selection.isEmpty()) {
				// will bracket match a cursor only if the selection is collapsed
				positions[positionsLen++] = selection.getStartPosition();
			}
		}

		// sort positions for `previousData` cache hits
		if (positions.length > 1) {
			positions.sort(Position.compare);
		}

		let newData: BracketsData[] = [], newDataLen = 0;
		let previousIndex = 0, previousLen = previousData.length;
		for (let i = 0, len = positions.length; i < len; i++) {
			let position = positions[i];

			while (previousIndex < previousLen && previousData[previousIndex].position.isBefore(position)) {
				previousIndex++;
			}

			if (previousIndex < previousLen && previousData[previousIndex].position.equals(position)) {
				newData[newDataLen++] = previousData[previousIndex];
			} else {
				let brackets = model.matchBracket(position);
				newData[newDataLen++] = new BracketsData(position, brackets);
			}
		}

		this._lastBracketsData = newData;
		this._lastVersionId = versionId;
	}
}
312

313
registerEditorContribution(BracketMatchingController);
A
Afonso Pinto 已提交
314 315
registerEditorAction(SelectToBracketAction);
registerEditorAction(JumpToBracketAction);
316
registerThemingParticipant((theme, collector) => {
M
Matt Bierner 已提交
317
	const bracketMatchBackground = theme.getColor(editorBracketMatchBackground);
318 319 320
	if (bracketMatchBackground) {
		collector.addRule(`.monaco-editor .bracket-match { background-color: ${bracketMatchBackground}; }`);
	}
M
Matt Bierner 已提交
321
	const bracketMatchBorder = theme.getColor(editorBracketMatchBorder);
322 323 324
	if (bracketMatchBorder) {
		collector.addRule(`.monaco-editor .bracket-match { border: 1px solid ${bracketMatchBorder}; }`);
	}
325
});