cursor.ts 36.4 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';

A
Alex Dima 已提交
7
import * as nls from 'vs/nls';
8
import * as strings from 'vs/base/common/strings';
J
Johannes Rieken 已提交
9
import { onUnexpectedError } from 'vs/base/common/errors';
A
Alex Dima 已提交
10 11
import { EventEmitter, BulkListenerCallback } from 'vs/base/common/eventEmitter';
import { IDisposable, Disposable } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
12
import { CursorCollection } from 'vs/editor/common/controller/cursorCollection';
J
Johannes Rieken 已提交
13 14
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
A
Alex Dima 已提交
15
import { Selection, SelectionDirection, ISelection } from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
16
import * as editorCommon from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
17
import { CursorColumns, CursorConfiguration, EditOperationResult, SingleCursorState, IViewModelHelper, CursorContext, CursorState, RevealTarget, IColumnSelectData, ICursors } from 'vs/editor/common/controller/cursorCommon';
J
Johannes Rieken 已提交
18
import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry';
A
Alex Dima 已提交
19 20
import { DeleteOperations } from 'vs/editor/common/controller/cursorDeleteOperations';
import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations';
21
import { TextModelEventType, ModelRawContentChangedEvent, RawContentChangedType } from 'vs/editor/common/model/textModelEvents';
22 23
import { CursorEventType, CursorChangeReason, ICursorPositionChangedEvent, VerticalRevealType, ICursorSelectionChangedEvent, ICursorRevealRangeEvent, CursorScrollRequest } from 'vs/editor/common/controller/cursorEvents';
import { CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions';
A
Alex Dima 已提交
24
import { CoreEditorCommand } from 'vs/editor/common/controller/coreCommands';
E
Erich Gamma 已提交
25 26

interface IMultipleCursorOperationContext {
27
	cursorPositionChangeReason: CursorChangeReason;
E
Erich Gamma 已提交
28 29
	shouldPushStackElementBefore: boolean;
	shouldPushStackElementAfter: boolean;
A
Alex Dima 已提交
30
	executeCommands: editorCommon.ICommand[];
31
	isAutoWhitespaceCommand: boolean[];
E
Erich Gamma 已提交
32 33
}

34 35 36 37 38 39 40 41 42 43
class CursorOperationArgs<T> {
	public readonly eventSource: string;
	public readonly eventData: T;

	constructor(eventSource: string, eventData: T) {
		this.eventSource = eventSource;
		this.eventData = eventData;
	}
}

E
Erich Gamma 已提交
44 45 46 47 48 49
interface IExecContext {
	selectionStartMarkers: string[];
	positionMarkers: string[];
}

interface ICommandData {
A
Alex Dima 已提交
50
	operations: editorCommon.IIdentifiedSingleEditOperation[];
A
Alex Dima 已提交
51
	hadTrackedEditOperation: boolean;
E
Erich Gamma 已提交
52 53 54
}

interface ICommandsData {
A
Alex Dima 已提交
55
	operations: editorCommon.IIdentifiedSingleEditOperation[];
A
Alex Dima 已提交
56
	hadTrackedEditOperation: boolean;
E
Erich Gamma 已提交
57 58
}

A
Alex Dima 已提交
59
export class Cursor extends Disposable implements ICursors {
A
Alex Dima 已提交
60 61 62 63 64 65 66 67 68 69

	public onDidChangePosition(listener: (e: ICursorPositionChangedEvent) => void): IDisposable {
		return this._eventEmitter.addListener(CursorEventType.CursorPositionChanged, listener);
	}
	public onDidChangeSelection(listener: (e: ICursorSelectionChangedEvent) => void): IDisposable {
		return this._eventEmitter.addListener(CursorEventType.CursorSelectionChanged, listener);
	}
	public addBulkListener(listener: BulkListenerCallback): IDisposable {
		return this._eventEmitter.addBulkListener(listener);
	}
E
Erich Gamma 已提交
70

A
Alex Dima 已提交
71 72 73 74
	private readonly _eventEmitter: EventEmitter;
	private readonly _configuration: editorCommon.IConfiguration;
	private readonly _model: editorCommon.IModel;
	private readonly _viewModelHelper: IViewModelHelper;
E
Erich Gamma 已提交
75

A
Alex Dima 已提交
76 77 78
	public context: CursorContext;

	private _cursors: CursorCollection;
J
Johannes Rieken 已提交
79
	private _isHandling: boolean;
80
	private _isDoingComposition: boolean;
A
Alex Dima 已提交
81
	private _columnSelectData: IColumnSelectData;
E
Erich Gamma 已提交
82

J
Johannes Rieken 已提交
83
	private _handlers: {
84
		[key: string]: (args: CursorOperationArgs<any>, ctx: IMultipleCursorOperationContext) => void;
A
Alex Dima 已提交
85 86
	};

87
	constructor(configuration: editorCommon.IConfiguration, model: editorCommon.IModel, viewModelHelper: IViewModelHelper) {
A
Alex Dima 已提交
88 89
		super();
		this._eventEmitter = this._register(new EventEmitter());
A
Alex Dima 已提交
90 91 92
		this._configuration = configuration;
		this._model = model;
		this._viewModelHelper = viewModelHelper;
A
Alex Dima 已提交
93 94 95

		const createCursorContext = () => {
			const config = new CursorConfiguration(
A
Alex Dima 已提交
96 97 98 99
				this._model.getLanguageIdentifier(),
				this._model.getOneIndent(),
				this._model.getOptions(),
				this._configuration
A
Alex Dima 已提交
100 101
			);
			this.context = new CursorContext(
A
Alex Dima 已提交
102 103
				this._model,
				this._viewModelHelper,
A
Alex Dima 已提交
104 105
				config
			);
A
Alex Dima 已提交
106 107
			if (this._cursors) {
				this._cursors.updateContext(this.context);
A
Alex Dima 已提交
108 109 110 111
			}
		};
		createCursorContext();

A
Alex Dima 已提交
112
		this._cursors = new CursorCollection(this.context);
E
Erich Gamma 已提交
113 114

		this._isHandling = false;
115
		this._isDoingComposition = false;
A
Alex Dima 已提交
116
		this._columnSelectData = null;
E
Erich Gamma 已提交
117

A
Alex Dima 已提交
118
		this._register(this._model.addBulkListener((events) => {
119 120 121 122 123 124 125 126
			if (this._isHandling) {
				return;
			}

			let hadContentChange = false;
			let hadFlushEvent = false;
			for (let i = 0, len = events.length; i < len; i++) {
				const event = events[i];
A
Alex Dima 已提交
127
				const eventType = event.type;
128

A
Alex Dima 已提交
129
				if (eventType === TextModelEventType.ModelRawContentChanged2) {
130
					hadContentChange = true;
131
					const changeEvent = <ModelRawContentChangedEvent>event.data;
132

133 134
					for (let j = 0, lenJ = changeEvent.changes.length; j < lenJ; j++) {
						const change = changeEvent.changes[j];
135
						if (change.changeType === RawContentChangedType.Flush) {
136 137
							hadFlushEvent = true;
						}
138 139 140 141 142 143 144 145 146
					}
				}
			}

			if (!hadContentChange) {
				return;
			}

			this._onModelContentChanged(hadFlushEvent);
E
Erich Gamma 已提交
147
		}));
A
Alex Dima 已提交
148

A
Alex Dima 已提交
149
		this._register(this._model.onDidChangeLanguage((e) => {
A
Alex Dima 已提交
150
			createCursorContext();
E
Erich Gamma 已提交
151
		}));
A
Alex Dima 已提交
152
		this._register(LanguageConfigurationRegistry.onDidChange(() => {
153
			// TODO@Alex: react only if certain supports changed? (and if my model's mode changed)
A
Alex Dima 已提交
154 155
			createCursorContext();
		}));
A
Alex Dima 已提交
156
		this._register(model.onDidChangeOptions(() => {
A
Alex Dima 已提交
157 158
			createCursorContext();
		}));
A
Alex Dima 已提交
159
		this._register(this._configuration.onDidChange((e) => {
A
Alex Dima 已提交
160 161 162
			if (CursorConfiguration.shouldRecreate(e)) {
				createCursorContext();
			}
E
Erich Gamma 已提交
163 164
		}));

A
Alex Dima 已提交
165
		this._handlers = {};
E
Erich Gamma 已提交
166 167 168 169
		this._registerHandlers();
	}

	public dispose(): void {
A
Alex Dima 已提交
170 171
		this._cursors.dispose();
		this._cursors = null;
E
Erich Gamma 已提交
172 173 174
		super.dispose();
	}

A
Alex Dima 已提交
175
	public getPrimaryCursor(): CursorState {
A
Alex Dima 已提交
176
		return this._cursors.getPrimaryCursor();
A
Alex Dima 已提交
177 178 179
	}

	public getLastAddedCursorIndex(): number {
A
Alex Dima 已提交
180
		return this._cursors.getLastAddedCursorIndex();
A
Alex Dima 已提交
181 182 183
	}

	public getAll(): CursorState[] {
A
Alex Dima 已提交
184
		return this._cursors.getAll();
A
Alex Dima 已提交
185 186 187
	}

	public setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void {
A
Alex Dima 已提交
188 189
		const oldSelections = this._cursors.getSelections();
		const oldViewSelections = this._cursors.getViewSelections();
A
Alex Dima 已提交
190 191 192 193 194

		// TODO@Alex
		// ensure valid state on all cursors
		// this.cursors.ensureValidState();

A
Alex Dima 已提交
195 196
		this._cursors.setStates(states);
		this._cursors.normalize();
A
Alex Dima 已提交
197 198
		this._columnSelectData = null;

A
Alex Dima 已提交
199 200
		const newSelections = this._cursors.getSelections();
		const newViewSelections = this._cursors.getViewSelections();
A
Alex Dima 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

		let somethingChanged = false;
		if (oldSelections.length !== newSelections.length) {
			somethingChanged = true;
		} else {
			for (let i = 0, len = oldSelections.length; !somethingChanged && i < len; i++) {
				if (!oldSelections[i].equalsSelection(newSelections[i])) {
					somethingChanged = true;
				}
			}
			for (let i = 0, len = oldViewSelections.length; !somethingChanged && i < len; i++) {
				if (!oldViewSelections[i].equalsSelection(newViewSelections[i])) {
					somethingChanged = true;
				}
			}
		}

		if (somethingChanged) {
			this.emitCursorPositionChanged(source, reason);
			this.emitCursorSelectionChanged(source, reason);
		}
	}

A
Alex Dima 已提交
224 225 226 227
	public setColumnSelectData(columnSelectData: IColumnSelectData): void {
		this._columnSelectData = columnSelectData;
	}

A
Alex Dima 已提交
228
	public reveal(horizontal: boolean, target: RevealTarget): void {
229 230 231 232 233
		this._revealRange(target, VerticalRevealType.Simple, horizontal);
	}

	public revealRange(revealHorizontal: boolean, modelRange: Range, viewRange: Range, verticalType: VerticalRevealType) {
		this.emitCursorRevealRange(modelRange, viewRange, verticalType, revealHorizontal);
A
Alex Dima 已提交
234 235
	}

A
Alex Dima 已提交
236 237 238 239 240 241
	public scrollTo(desiredScrollTop: number): void {
		this._eventEmitter.emit(CursorEventType.CursorScrollRequest, new CursorScrollRequest(
			desiredScrollTop
		));
	}

A
Alex Dima 已提交
242
	public saveState(): editorCommon.ICursorState[] {
E
Erich Gamma 已提交
243

A
Alex Dima 已提交
244
		let result: editorCommon.ICursorState[] = [];
E
Erich Gamma 已提交
245

A
Alex Dima 已提交
246 247 248
		const selections = this._cursors.getSelections();
		for (let i = 0, len = selections.length; i < len; i++) {
			const selection = selections[i];
E
Erich Gamma 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

			result.push({
				inSelectionMode: !selection.isEmpty(),
				selectionStart: {
					lineNumber: selection.selectionStartLineNumber,
					column: selection.selectionStartColumn,
				},
				position: {
					lineNumber: selection.positionLineNumber,
					column: selection.positionColumn,
				}
			});
		}

		return result;
	}

J
Johannes Rieken 已提交
266
	public restoreState(states: editorCommon.ICursorState[]): void {
E
Erich Gamma 已提交
267

A
Alex Dima 已提交
268
		let desiredSelections: ISelection[] = [];
E
Erich Gamma 已提交
269

A
Alex Dima 已提交
270 271
		for (let i = 0, len = states.length; i < len; i++) {
			const state = states[i];
E
Erich Gamma 已提交
272

A
Alex Dima 已提交
273 274
			let positionLineNumber = 1;
			let positionColumn = 1;
E
Erich Gamma 已提交
275 276 277 278 279 280 281 282 283

			// Avoid missing properties on the literal
			if (state.position && state.position.lineNumber) {
				positionLineNumber = state.position.lineNumber;
			}
			if (state.position && state.position.column) {
				positionColumn = state.position.column;
			}

A
Alex Dima 已提交
284 285
			let selectionStartLineNumber = positionLineNumber;
			let selectionStartColumn = positionColumn;
E
Erich Gamma 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

			// Avoid missing properties on the literal
			if (state.selectionStart && state.selectionStart.lineNumber) {
				selectionStartLineNumber = state.selectionStart.lineNumber;
			}
			if (state.selectionStart && state.selectionStart.column) {
				selectionStartColumn = state.selectionStart.column;
			}

			desiredSelections.push({
				selectionStartLineNumber: selectionStartLineNumber,
				selectionStartColumn: selectionStartColumn,
				positionLineNumber: positionLineNumber,
				positionColumn: positionColumn
			});
		}

A
Alex Dima 已提交
303 304
		this.setStates('restoreState', CursorChangeReason.NotSet, CursorState.fromModelSelections(desiredSelections));
		this.reveal(true, RevealTarget.Primary);
E
Erich Gamma 已提交
305 306
	}

307 308
	private _onModelContentChanged(hadFlushEvent: boolean): void {
		if (hadFlushEvent) {
E
Erich Gamma 已提交
309
			// a model.setValue() was called
A
Alex Dima 已提交
310
			this._cursors.dispose();
E
Erich Gamma 已提交
311

A
Alex Dima 已提交
312
			this._cursors = new CursorCollection(this.context);
E
Erich Gamma 已提交
313

314 315
			this.emitCursorPositionChanged('model', CursorChangeReason.ContentFlush);
			this.emitCursorSelectionChanged('model', CursorChangeReason.ContentFlush);
E
Erich Gamma 已提交
316 317
		} else {
			if (!this._isHandling) {
A
Alex Dima 已提交
318
				const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
A
Alex Dima 已提交
319
				this.setStates('modelChange', CursorChangeReason.RecoverFromMarkers, CursorState.fromModelSelections(selectionsFromMarkers));
E
Erich Gamma 已提交
320 321 322 323 324 325
			}
		}
	}

	// ------ some getters/setters

326
	public getSelection(): Selection {
A
Alex Dima 已提交
327
		return this._cursors.getPrimaryCursor().modelState.selection;
E
Erich Gamma 已提交
328 329
	}

330
	public getSelections(): Selection[] {
A
Alex Dima 已提交
331
		return this._cursors.getSelections();
E
Erich Gamma 已提交
332 333
	}

A
Alex Dima 已提交
334
	public getPosition(): Position {
A
Alex Dima 已提交
335
		return this._cursors.getPrimaryCursor().modelState.position;
E
Erich Gamma 已提交
336 337
	}

A
Alex Dima 已提交
338
	public setSelections(source: string, selections: ISelection[]): void {
A
Alex Dima 已提交
339
		this.setStates(source, CursorChangeReason.NotSet, CursorState.fromModelSelections(selections));
E
Erich Gamma 已提交
340 341 342 343
	}

	// ------ auxiliary handling logic

344
	private _createAndInterpretHandlerCtx(callback: (currentHandlerCtx: IMultipleCursorOperationContext) => void): void {
E
Erich Gamma 已提交
345

A
Alex Dima 已提交
346
		const ctx: IMultipleCursorOperationContext = {
347
			cursorPositionChangeReason: CursorChangeReason.NotSet,
E
Erich Gamma 已提交
348
			executeCommands: [],
349
			isAutoWhitespaceCommand: [],
E
Erich Gamma 已提交
350
			shouldPushStackElementBefore: false,
A
Alex Dima 已提交
351
			shouldPushStackElementAfter: false
E
Erich Gamma 已提交
352 353
		};

A
Alex Dima 已提交
354
		callback(ctx);
E
Erich Gamma 已提交
355

A
Alex Dima 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
		if (ctx.shouldPushStackElementBefore) {
			this._model.pushStackElement();
			ctx.shouldPushStackElementBefore = false;
		}

		this._columnSelectData = null;

		const execCtx: IExecContext = {
			selectionStartMarkers: [],
			positionMarkers: []
		};

		this._innerExecuteCommands(execCtx, ctx.executeCommands, ctx.isAutoWhitespaceCommand);

		for (let i = 0; i < execCtx.selectionStartMarkers.length; i++) {
			this._model._removeMarker(execCtx.selectionStartMarkers[i]);
			this._model._removeMarker(execCtx.positionMarkers[i]);
		}

		ctx.executeCommands = [];

		if (ctx.shouldPushStackElementAfter) {
			this._model.pushStackElement();
			ctx.shouldPushStackElementAfter = false;
		}

A
Alex Dima 已提交
382
		this._cursors.normalize();
E
Erich Gamma 已提交
383 384
	}

385
	private _onHandler(command: string, handler: (args: CursorOperationArgs<any>, ctx: IMultipleCursorOperationContext) => void, args: CursorOperationArgs<any>): void {
E
Erich Gamma 已提交
386 387 388 389

		this._isHandling = true;

		try {
A
Alex Dima 已提交
390 391
			const oldSelections = this._cursors.getSelections();
			const oldViewSelections = this._cursors.getViewSelections();
392

A
Alex Dima 已提交
393
			// ensure valid state on all cursors
A
Alex Dima 已提交
394
			this._cursors.ensureValidState();
A
Alex Dima 已提交
395

A
Alex Dima 已提交
396
			let cursorPositionChangeReason: CursorChangeReason;
E
Erich Gamma 已提交
397

398 399
			this._createAndInterpretHandlerCtx((currentHandlerCtx: IMultipleCursorOperationContext) => {
				handler(args, currentHandlerCtx);
E
Erich Gamma 已提交
400 401 402 403

				cursorPositionChangeReason = currentHandlerCtx.cursorPositionChangeReason;
			});

A
Alex Dima 已提交
404 405
			const newSelections = this._cursors.getSelections();
			const newViewSelections = this._cursors.getViewSelections();
E
Erich Gamma 已提交
406

A
Alex Dima 已提交
407
			let somethingChanged = false;
E
Erich Gamma 已提交
408 409 410
			if (oldSelections.length !== newSelections.length) {
				somethingChanged = true;
			} else {
A
Alex Dima 已提交
411
				for (let i = 0, len = oldSelections.length; !somethingChanged && i < len; i++) {
E
Erich Gamma 已提交
412 413 414 415
					if (!oldSelections[i].equalsSelection(newSelections[i])) {
						somethingChanged = true;
					}
				}
A
Alex Dima 已提交
416
				for (let i = 0, len = oldViewSelections.length; !somethingChanged && i < len; i++) {
E
Erich Gamma 已提交
417 418 419 420 421 422 423
					if (!oldViewSelections[i].equalsSelection(newViewSelections[i])) {
						somethingChanged = true;
					}
				}
			}

			if (somethingChanged) {
424 425 426
				this.emitCursorPositionChanged(args.eventSource, cursorPositionChangeReason);
				this._revealRange(RevealTarget.Primary, VerticalRevealType.Simple, true);
				this.emitCursorSelectionChanged(args.eventSource, cursorPositionChangeReason);
E
Erich Gamma 已提交
427
			}
428

E
Erich Gamma 已提交
429
		} catch (err) {
A
Alex Dima 已提交
430
			onUnexpectedError(err);
E
Erich Gamma 已提交
431 432 433 434 435
		}

		this._isHandling = false;
	}

A
Alex Dima 已提交
436
	private _interpretCommandResult(cursorState: Selection[]): void {
437
		if (!cursorState || cursorState.length === 0) {
A
Alex Dima 已提交
438
			return;
E
Erich Gamma 已提交
439 440
		}

A
Alex Dima 已提交
441
		this._cursors.setSelections(cursorState);
E
Erich Gamma 已提交
442 443
	}

J
Johannes Rieken 已提交
444
	private _getEditOperationsFromCommand(ctx: IExecContext, majorIdentifier: number, command: editorCommon.ICommand, isAutoWhitespaceCommand: boolean): ICommandData {
E
Erich Gamma 已提交
445 446
		// This method acts as a transaction, if the command fails
		// everything it has done is ignored
A
Alex Dima 已提交
447 448
		let operations: editorCommon.IIdentifiedSingleEditOperation[] = [];
		let operationMinor = 0;
E
Erich Gamma 已提交
449

A
Alex Dima 已提交
450
		const addEditOperation = (selection: Range, text: string) => {
E
Erich Gamma 已提交
451 452 453 454 455 456 457 458 459 460 461
			if (selection.isEmpty() && text === '') {
				// This command wants to add a no-op => no thank you
				return;
			}
			operations.push({
				identifier: {
					major: majorIdentifier,
					minor: operationMinor++
				},
				range: selection,
				text: text,
462 463
				forceMoveMarkers: false,
				isAutoWhitespaceEdit: isAutoWhitespaceCommand
E
Erich Gamma 已提交
464 465 466
			});
		};

A
Alex Dima 已提交
467 468
		let hadTrackedEditOperation = false;
		const addTrackedEditOperation = (selection: Range, text: string) => {
A
Alex Dima 已提交
469 470 471 472
			hadTrackedEditOperation = true;
			addEditOperation(selection, text);
		};

A
Alex Dima 已提交
473 474 475
		const trackSelection = (selection: Selection, trackPreviousOnEmpty?: boolean) => {
			let selectionMarkerStickToPreviousCharacter: boolean;
			let positionMarkerStickToPreviousCharacter: boolean;
E
Erich Gamma 已提交
476 477 478 479 480 481 482

			if (selection.isEmpty()) {
				// Try to lock it with surrounding text
				if (typeof trackPreviousOnEmpty === 'boolean') {
					selectionMarkerStickToPreviousCharacter = trackPreviousOnEmpty;
					positionMarkerStickToPreviousCharacter = trackPreviousOnEmpty;
				} else {
A
Alex Dima 已提交
483
					const maxLineColumn = this._model.getLineMaxColumn(selection.startLineNumber);
E
Erich Gamma 已提交
484 485 486 487 488 489 490 491 492
					if (selection.startColumn === maxLineColumn) {
						selectionMarkerStickToPreviousCharacter = true;
						positionMarkerStickToPreviousCharacter = true;
					} else {
						selectionMarkerStickToPreviousCharacter = false;
						positionMarkerStickToPreviousCharacter = false;
					}
				}
			} else {
493
				if (selection.getDirection() === SelectionDirection.LTR) {
E
Erich Gamma 已提交
494 495 496 497 498 499 500 501
					selectionMarkerStickToPreviousCharacter = false;
					positionMarkerStickToPreviousCharacter = true;
				} else {
					selectionMarkerStickToPreviousCharacter = true;
					positionMarkerStickToPreviousCharacter = false;
				}
			}

A
Alex Dima 已提交
502 503 504
			const l = ctx.selectionStartMarkers.length;
			ctx.selectionStartMarkers[l] = this._model._addMarker(0, selection.selectionStartLineNumber, selection.selectionStartColumn, selectionMarkerStickToPreviousCharacter);
			ctx.positionMarkers[l] = this._model._addMarker(0, selection.positionLineNumber, selection.positionColumn, positionMarkerStickToPreviousCharacter);
E
Erich Gamma 已提交
505 506 507
			return l.toString();
		};

A
Alex Dima 已提交
508
		const editOperationBuilder: editorCommon.IEditOperationBuilder = {
E
Erich Gamma 已提交
509
			addEditOperation: addEditOperation,
A
Alex Dima 已提交
510
			addTrackedEditOperation: addTrackedEditOperation,
E
Erich Gamma 已提交
511 512 513 514
			trackSelection: trackSelection
		};

		try {
A
Alex Dima 已提交
515
			command.getEditOperations(this._model, editOperationBuilder);
E
Erich Gamma 已提交
516 517
		} catch (e) {
			e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command.");
A
Alex Dima 已提交
518
			onUnexpectedError(e);
E
Erich Gamma 已提交
519 520
			return {
				operations: [],
A
Alex Dima 已提交
521
				hadTrackedEditOperation: false
E
Erich Gamma 已提交
522 523 524 525 526
			};
		}

		return {
			operations: operations,
A
Alex Dima 已提交
527
			hadTrackedEditOperation: hadTrackedEditOperation
E
Erich Gamma 已提交
528 529 530
		};
	}

J
Johannes Rieken 已提交
531
	private _getEditOperations(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): ICommandsData {
A
Alex Dima 已提交
532
		let operations: editorCommon.IIdentifiedSingleEditOperation[] = [];
A
Alex Dima 已提交
533
		let hadTrackedEditOperation: boolean = false;
E
Erich Gamma 已提交
534

A
Alex Dima 已提交
535
		for (let i = 0, len = commands.length; i < len; i++) {
E
Erich Gamma 已提交
536
			if (commands[i]) {
A
Alex Dima 已提交
537 538 539
				const r = this._getEditOperationsFromCommand(ctx, i, commands[i], isAutoWhitespaceCommand[i]);
				operations = operations.concat(r.operations);
				hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation;
E
Erich Gamma 已提交
540 541 542 543
			}
		}
		return {
			operations: operations,
A
Alex Dima 已提交
544
			hadTrackedEditOperation: hadTrackedEditOperation
E
Erich Gamma 已提交
545 546 547
		};
	}

A
Alex Dima 已提交
548
	private _getLoserCursorMap(operations: editorCommon.IIdentifiedSingleEditOperation[]): { [index: string]: boolean; } {
E
Erich Gamma 已提交
549 550 551 552
		// This is destructive on the array
		operations = operations.slice(0);

		// Sort operations with last one first
J
Johannes Rieken 已提交
553
		operations.sort((a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation): number => {
E
Erich Gamma 已提交
554 555 556 557 558
			// Note the minus!
			return -(Range.compareRangesUsingEnds(a.range, b.range));
		});

		// Operations can not overlap!
A
Alex Dima 已提交
559
		let loserCursorsMap: { [index: string]: boolean; } = {};
E
Erich Gamma 已提交
560

A
Alex Dima 已提交
561 562 563
		for (let i = 1; i < operations.length; i++) {
			const previousOp = operations[i - 1];
			const currentOp = operations[i];
E
Erich Gamma 已提交
564

565
			if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) {
E
Erich Gamma 已提交
566

A
Alex Dima 已提交
567 568
				let loserMajor: number;

E
Erich Gamma 已提交
569 570 571 572 573 574 575 576 577
				if (previousOp.identifier.major > currentOp.identifier.major) {
					// previousOp loses the battle
					loserMajor = previousOp.identifier.major;
				} else {
					loserMajor = currentOp.identifier.major;
				}

				loserCursorsMap[loserMajor.toString()] = true;

A
Alex Dima 已提交
578
				for (let j = 0; j < operations.length; j++) {
E
Erich Gamma 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
					if (operations[j].identifier.major === loserMajor) {
						operations.splice(j, 1);
						if (j < i) {
							i--;
						}
						j--;
					}
				}

				if (i > 0) {
					i--;
				}
			}
		}

		return loserCursorsMap;
	}

A
Alex Dima 已提交
597
	private _arrayIsEmpty(commands: editorCommon.ICommand[]): boolean {
A
Alex Dima 已提交
598
		for (let i = 0, len = commands.length; i < len; i++) {
E
Erich Gamma 已提交
599 600 601 602 603 604 605
			if (commands[i]) {
				return false;
			}
		}
		return true;
	}

A
Alex Dima 已提交
606
	private _innerExecuteCommands(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): void {
E
Erich Gamma 已提交
607

A
Alex Dima 已提交
608
		if (this._configuration.editor.readOnly) {
A
Alex Dima 已提交
609
			return;
E
Erich Gamma 已提交
610 611 612
		}

		if (this._arrayIsEmpty(commands)) {
A
Alex Dima 已提交
613
			return;
E
Erich Gamma 已提交
614 615
		}

A
Alex Dima 已提交
616
		const selectionsBefore = this._cursors.getSelections();
E
Erich Gamma 已提交
617

A
Alex Dima 已提交
618 619
		const commandsData = this._getEditOperations(ctx, commands, isAutoWhitespaceCommand);
		if (commandsData.operations.length === 0) {
A
Alex Dima 已提交
620
			return;
E
Erich Gamma 已提交
621 622
		}

A
Alex Dima 已提交
623
		const rawOperations = commandsData.operations;
E
Erich Gamma 已提交
624

A
Alex Dima 已提交
625 626 627 628 629
		const editableRange = this._model.getEditableRange();
		const editableRangeStart = editableRange.getStartPosition();
		const editableRangeEnd = editableRange.getEndPosition();
		for (let i = 0, len = rawOperations.length; i < len; i++) {
			const operationRange = rawOperations[i].range;
E
Erich Gamma 已提交
630 631
			if (!editableRangeStart.isBeforeOrEqual(operationRange.getStartPosition()) || !operationRange.getEndPosition().isBeforeOrEqual(editableRangeEnd)) {
				// These commands are outside of the editable range
A
Alex Dima 已提交
632
				return;
E
Erich Gamma 已提交
633 634 635
			}
		}

A
Alex Dima 已提交
636
		const loserCursorsMap = this._getLoserCursorMap(rawOperations);
E
Erich Gamma 已提交
637 638 639
		if (loserCursorsMap.hasOwnProperty('0')) {
			// These commands are very messed up
			console.warn('Ignoring commands');
A
Alex Dima 已提交
640
			return;
E
Erich Gamma 已提交
641 642 643
		}

		// Remove operations belonging to losing cursors
A
Alex Dima 已提交
644 645
		let filteredOperations: editorCommon.IIdentifiedSingleEditOperation[] = [];
		for (let i = 0, len = rawOperations.length; i < len; i++) {
E
Erich Gamma 已提交
646 647 648 649 650
			if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
				filteredOperations.push(rawOperations[i]);
			}
		}

A
Alex Dima 已提交
651 652
		// TODO@Alex: find a better way to do this.
		// give the hint that edit operations are tracked to the model
A
Alex Dima 已提交
653
		if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
A
Alex Dima 已提交
654 655
			filteredOperations[0]._isTracked = true;
		}
A
Alex Dima 已提交
656 657 658
		const selectionsAfter = this._model.pushEditOperations(selectionsBefore, filteredOperations, (inverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[]): Selection[] => {
			let groupedInverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[][] = [];
			for (let i = 0; i < selectionsBefore.length; i++) {
E
Erich Gamma 已提交
659 660
				groupedInverseEditOperations[i] = [];
			}
A
Alex Dima 已提交
661 662
			for (let i = 0; i < inverseEditOperations.length; i++) {
				const op = inverseEditOperations[i];
663 664 665 666
				if (!op.identifier) {
					// perhaps auto whitespace trim edits
					continue;
				}
E
Erich Gamma 已提交
667 668
				groupedInverseEditOperations[op.identifier.major].push(op);
			}
A
Alex Dima 已提交
669
			const minorBasedSorter = (a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation) => {
E
Erich Gamma 已提交
670 671
				return a.identifier.minor - b.identifier.minor;
			};
A
Alex Dima 已提交
672 673 674
			let cursorSelections: Selection[] = [];
			for (let i = 0; i < selectionsBefore.length; i++) {
				if (groupedInverseEditOperations[i].length > 0) {
E
Erich Gamma 已提交
675
					groupedInverseEditOperations[i].sort(minorBasedSorter);
A
Alex Dima 已提交
676
					cursorSelections[i] = commands[i].computeCursorState(this._model, {
E
Erich Gamma 已提交
677 678 679 680 681
						getInverseEditOperations: () => {
							return groupedInverseEditOperations[i];
						},

						getTrackedSelection: (id: string) => {
A
Alex Dima 已提交
682 683 684
							const idx = parseInt(id, 10);
							const selectionStartMarker = this._model._getMarker(ctx.selectionStartMarkers[idx]);
							const positionMarker = this._model._getMarker(ctx.positionMarkers[idx]);
E
Erich Gamma 已提交
685 686 687 688 689 690 691 692 693 694 695
							return new Selection(selectionStartMarker.lineNumber, selectionStartMarker.column, positionMarker.lineNumber, positionMarker.column);
						}
					});
				} else {
					cursorSelections[i] = selectionsBefore[i];
				}
			}
			return cursorSelections;
		});

		// Extract losing cursors
A
Alex Dima 已提交
696 697
		let losingCursors: number[] = [];
		for (let losingCursorIndex in loserCursorsMap) {
E
Erich Gamma 已提交
698 699 700 701 702 703
			if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
				losingCursors.push(parseInt(losingCursorIndex, 10));
			}
		}

		// Sort losing cursors descending
J
Johannes Rieken 已提交
704
		losingCursors.sort((a: number, b: number): number => {
E
Erich Gamma 已提交
705 706 707 708
			return b - a;
		});

		// Remove losing cursors
A
Alex Dima 已提交
709
		for (let i = 0; i < losingCursors.length; i++) {
E
Erich Gamma 已提交
710 711 712
			selectionsAfter.splice(losingCursors[i], 1);
		}

A
Alex Dima 已提交
713
		this._interpretCommandResult(selectionsAfter);
E
Erich Gamma 已提交
714 715 716 717 718 719
	}


	// -----------------------------------------------------------------------------------------------------------
	// ----- emitting events

720
	private emitCursorPositionChanged(source: string, reason: CursorChangeReason): void {
A
Alex Dima 已提交
721 722 723
		const positions = this._cursors.getPositions();
		const primaryPosition = positions[0];
		const secondaryPositions = positions.slice(1);
E
Erich Gamma 已提交
724

A
Alex Dima 已提交
725 726 727
		const viewPositions = this._cursors.getViewPositions();
		const primaryViewPosition = viewPositions[0];
		const secondaryViewPositions = viewPositions.slice(1);
E
Erich Gamma 已提交
728

A
Alex Dima 已提交
729 730 731
		let isInEditableRange: boolean = true;
		if (this._model.hasEditableRange()) {
			const editableRange = this._model.getEditableRange();
E
Erich Gamma 已提交
732 733 734 735
			if (!editableRange.containsPosition(primaryPosition)) {
				isInEditableRange = false;
			}
		}
A
Alex Dima 已提交
736
		const e: ICursorPositionChangedEvent = {
E
Erich Gamma 已提交
737 738 739 740 741 742 743 744
			position: primaryPosition,
			viewPosition: primaryViewPosition,
			secondaryPositions: secondaryPositions,
			secondaryViewPositions: secondaryViewPositions,
			reason: reason,
			source: source,
			isInEditableRange: isInEditableRange
		};
A
Alex Dima 已提交
745
		this._eventEmitter.emit(CursorEventType.CursorPositionChanged, e);
E
Erich Gamma 已提交
746 747
	}

748
	private emitCursorSelectionChanged(source: string, reason: CursorChangeReason): void {
A
Alex Dima 已提交
749 750 751
		const selections = this._cursors.getSelections();
		const primarySelection = selections[0];
		const secondarySelections = selections.slice(1);
E
Erich Gamma 已提交
752

A
Alex Dima 已提交
753 754 755
		const viewSelections = this._cursors.getViewSelections();
		const primaryViewSelection = viewSelections[0];
		const secondaryViewSelections = viewSelections.slice(1);
756

A
Alex Dima 已提交
757
		const e: ICursorSelectionChangedEvent = {
E
Erich Gamma 已提交
758
			selection: primarySelection,
759
			viewSelection: primaryViewSelection,
E
Erich Gamma 已提交
760
			secondarySelections: secondarySelections,
761
			secondaryViewSelections: secondaryViewSelections,
762
			source: source || 'keyboard',
E
Erich Gamma 已提交
763 764
			reason: reason
		};
A
Alex Dima 已提交
765
		this._eventEmitter.emit(CursorEventType.CursorSelectionChanged, e);
E
Erich Gamma 已提交
766 767
	}

768
	private _revealRange(revealTarget: RevealTarget, verticalType: VerticalRevealType, revealHorizontal: boolean): void {
A
Alex Dima 已提交
769 770
		const positions = this._cursors.getPositions();
		const viewPositions = this._cursors.getViewPositions();
E
Erich Gamma 已提交
771

A
Alex Dima 已提交
772 773
		let position = positions[0];
		let viewPosition = viewPositions[0];
E
Erich Gamma 已提交
774 775

		if (revealTarget === RevealTarget.TopMost) {
A
Alex Dima 已提交
776
			for (let i = 1; i < positions.length; i++) {
E
Erich Gamma 已提交
777 778 779 780 781 782
				if (positions[i].isBefore(position)) {
					position = positions[i];
					viewPosition = viewPositions[i];
				}
			}
		} else if (revealTarget === RevealTarget.BottomMost) {
A
Alex Dima 已提交
783
			for (let i = 1; i < positions.length; i++) {
E
Erich Gamma 已提交
784 785 786 787 788 789 790 791 792 793 794 795
				if (position.isBeforeOrEqual(positions[i])) {
					position = positions[i];
					viewPosition = viewPositions[i];
				}
			}
		} else {
			if (positions.length > 1) {
				// no revealing!
				return;
			}
		}

A
Alex Dima 已提交
796 797
		const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
		const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
798
		this.emitCursorRevealRange(range, viewRange, verticalType, revealHorizontal);
799 800
	}

801
	public emitCursorRevealRange(range: Range, viewRange: Range, verticalType: VerticalRevealType, revealHorizontal: boolean) {
A
Alex Dima 已提交
802
		const e: ICursorRevealRangeEvent = {
E
Erich Gamma 已提交
803 804 805
			range: range,
			viewRange: viewRange,
			verticalType: verticalType,
806
			revealHorizontal: revealHorizontal
E
Erich Gamma 已提交
807
		};
A
Alex Dima 已提交
808
		this._eventEmitter.emit(CursorEventType.CursorRevealRange, e);
E
Erich Gamma 已提交
809 810 811 812 813
	}

	// -----------------------------------------------------------------------------------------------------------
	// ----- handlers beyond this point

J
Johannes Rieken 已提交
814
	public trigger(source: string, handlerId: string, payload: any): void {
A
Alex Dima 已提交
815
		if (!this._handlers.hasOwnProperty(handlerId)) {
A
Alex Dima 已提交
816
			const command = CommonEditorRegistry.getEditorCommand(handlerId);
A
Alex Dima 已提交
817
			if (!command || !(command instanceof CoreEditorCommand)) {
A
Alex Dima 已提交
818 819 820 821 822
				return;
			}

			payload = payload || {};
			payload.source = source;
A
Alex Dima 已提交
823
			command.runCoreEditorCommand(this, payload);
A
Alex Dima 已提交
824 825
			return;
		}
826 827 828
		const handler = this._handlers[handlerId];
		const args = new CursorOperationArgs(source, payload);
		this._onHandler(handlerId, handler, args);
A
Alex Dima 已提交
829 830
	}

E
Erich Gamma 已提交
831
	private _registerHandlers(): void {
A
Alex Dima 已提交
832
		let H = editorCommon.Handler;
E
Erich Gamma 已提交
833

834 835 836
		this._handlers[H.LineInsertBefore] = (args, ctx) => this._lineInsertBefore(args, ctx);
		this._handlers[H.LineInsertAfter] = (args, ctx) => this._lineInsertAfter(args, ctx);
		this._handlers[H.LineBreakInsert] = (args, ctx) => this._lineBreakInsert(args, ctx);
E
Erich Gamma 已提交
837

838 839 840 841 842 843 844 845
		this._handlers[H.Type] = (args, ctx) => this._type(args, ctx);
		this._handlers[H.ReplacePreviousChar] = (args, ctx) => this._replacePreviousChar(args, ctx);
		this._handlers[H.CompositionStart] = (args, ctx) => this._compositionStart(args, ctx);
		this._handlers[H.CompositionEnd] = (args, ctx) => this._compositionEnd(args, ctx);
		this._handlers[H.Tab] = (args, ctx) => this._tab(args, ctx);
		this._handlers[H.Indent] = (args, ctx) => this._indent(args, ctx);
		this._handlers[H.Outdent] = (args, ctx) => this._outdent(args, ctx);
		this._handlers[H.Paste] = (args, ctx) => this._paste(args, ctx);
846

847 848
		this._handlers[H.DeleteLeft] = (args, ctx) => this._deleteLeft(args, ctx);
		this._handlers[H.DeleteRight] = (args, ctx) => this._deleteRight(args, ctx);
E
Erich Gamma 已提交
849

850
		this._handlers[H.Cut] = (args, ctx) => this._cut(args, ctx);
E
Erich Gamma 已提交
851

852 853
		this._handlers[H.Undo] = (args, ctx) => this._undo(args, ctx);
		this._handlers[H.Redo] = (args, ctx) => this._redo(args, ctx);
E
Erich Gamma 已提交
854

855 856
		this._handlers[H.ExecuteCommand] = (args, ctx) => this._externalExecuteCommand(args, ctx);
		this._handlers[H.ExecuteCommands] = (args, ctx) => this._externalExecuteCommands(args, ctx);
E
Erich Gamma 已提交
857 858
	}

A
Alex Dima 已提交
859
	public getColumnSelectData(): IColumnSelectData {
A
Alex Dima 已提交
860 861
		if (this._columnSelectData) {
			return this._columnSelectData;
A
Alex Dima 已提交
862
		}
A
Alex Dima 已提交
863
		const primaryCursor = this._cursors.getPrimaryCursor();
A
Alex Dima 已提交
864 865 866 867 868
		const primaryPos = primaryCursor.viewState.position;
		return {
			toViewLineNumber: primaryPos.lineNumber,
			toViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos)
		};
A
Alex Dima 已提交
869
	}
A
Alex Dima 已提交
870

A
Alex Dima 已提交
871 872
	// -------------------- START editing operations

873 874 875 876 877 878 879 880 881
	private _applyEdits(ctx: IMultipleCursorOperationContext, edits: EditOperationResult): void {
		ctx.shouldPushStackElementBefore = edits.shouldPushStackElementBefore;
		ctx.shouldPushStackElementAfter = edits.shouldPushStackElementAfter;

		const commands = edits.commands;
		for (let i = 0, len = commands.length; i < len; i++) {
			const command = commands[i];
			ctx.executeCommands[i] = command ? command.command : null;
			ctx.isAutoWhitespaceCommand[i] = command ? command.isAutoWhitespaceCommand : false;
A
Alex Dima 已提交
882 883 884
		}
	}

885
	private _getAllCursorsModelState(sorted: boolean = false): SingleCursorState[] {
A
Alex Dima 已提交
886
		let cursors = this._cursors.getAll();
A
Alex Dima 已提交
887

888 889 890 891 892 893 894 895 896 897 898
		if (sorted) {
			cursors = cursors.sort((a, b) => {
				return Range.compareRangesUsingStarts(a.modelState.selection, b.modelState.selection);
			});
		}

		let r: SingleCursorState[] = [];
		for (let i = 0, len = cursors.length; i < len; i++) {
			r[i] = cursors[i].modelState;
		}
		return r;
A
Alex Dima 已提交
899 900
	}

901
	private _lineInsertBefore(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
902
		this._applyEdits(ctx, TypeOperations.lineInsertBefore(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
903 904
	}

905
	private _lineInsertAfter(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
906
		this._applyEdits(ctx, TypeOperations.lineInsertAfter(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
907 908
	}

909
	private _lineBreakInsert(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
910
		this._applyEdits(ctx, TypeOperations.lineBreakInsert(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
911 912
	}

913 914
	private _type(args: CursorOperationArgs<{ text: string; }>, ctx: IMultipleCursorOperationContext): void {
		const text = args.eventData.text;
E
Erich Gamma 已提交
915

916
		if (!this._isDoingComposition && args.eventSource === 'keyboard') {
E
Erich Gamma 已提交
917 918
			// If this event is coming straight from the keyboard, look for electric characters and enter

919 920 921 922 923 924 925 926 927
			for (let i = 0, len = text.length; i < len; i++) {
				let charCode = text.charCodeAt(i);
				let chr: string;
				if (strings.isHighSurrogate(charCode) && i + 1 < len) {
					chr = text.charAt(i) + text.charAt(i + 1);
					i++;
				} else {
					chr = text.charAt(i);
				}
E
Erich Gamma 已提交
928 929

				// Here we must interpret each typed character individually, that's why we create a new context
930
				this._createAndInterpretHandlerCtx((charHandlerCtx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
931

932
					// Decide what all cursors will do up-front
933
					this._applyEdits(charHandlerCtx, TypeOperations.typeWithInterceptors(this.context.config, this.context.model, this._getAllCursorsModelState(), chr));
E
Erich Gamma 已提交
934 935 936

					// The last typed character gets to win
					ctx.cursorPositionChangeReason = charHandlerCtx.cursorPositionChangeReason;
A
Alex Dima 已提交
937
				});
E
Erich Gamma 已提交
938 939 940

			}
		} else {
941
			this._applyEdits(ctx, TypeOperations.typeWithoutInterceptors(this.context.config, this.context.model, this._getAllCursorsModelState(), text));
E
Erich Gamma 已提交
942 943 944
		}
	}

945 946 947
	private _replacePreviousChar(args: CursorOperationArgs<{ text: string; replaceCharCnt: number; }>, ctx: IMultipleCursorOperationContext): void {
		let text = args.eventData.text;
		let replaceCharCnt = args.eventData.replaceCharCnt;
948
		this._applyEdits(ctx, TypeOperations.replacePreviousChar(this.context.config, this.context.model, this._getAllCursorsModelState(), text, replaceCharCnt));
E
Erich Gamma 已提交
949 950
	}

951
	private _compositionStart(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
952 953 954
		this._isDoingComposition = true;
	}

955
	private _compositionEnd(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
956 957 958
		this._isDoingComposition = false;
	}

959
	private _tab(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
960
		this._applyEdits(ctx, TypeOperations.tab(this.context.config, this.context.model, this._getAllCursorsModelState()));
E
Erich Gamma 已提交
961 962
	}

963
	private _indent(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
964
		this._applyEdits(ctx, TypeOperations.indent(this.context.config, this.context.model, this._getAllCursorsModelState()));
E
Erich Gamma 已提交
965 966
	}

967
	private _outdent(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
968
		this._applyEdits(ctx, TypeOperations.outdent(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
969 970
	}

971 972
	private _distributePasteToCursors(args: CursorOperationArgs<{ pasteOnNewLine: boolean; text: string; }>, ctx: IMultipleCursorOperationContext): string[] {
		if (args.eventData.pasteOnNewLine) {
A
Alex Dima 已提交
973 974 975
			return null;
		}

A
Alex Dima 已提交
976
		const selections = this._cursors.getSelections();
A
Alex Dima 已提交
977 978 979 980
		if (selections.length === 1) {
			return null;
		}

A
Alex Dima 已提交
981
		for (let i = 0; i < selections.length; i++) {
A
Alex Dima 已提交
982 983 984 985 986
			if (selections[i].startLineNumber !== selections[i].endLineNumber) {
				return null;
			}
		}

987
		let pastePieces = args.eventData.text.split(/\r\n|\r|\n/);
A
Alex Dima 已提交
988 989 990 991 992
		if (pastePieces.length !== selections.length) {
			return null;
		}

		return pastePieces;
E
Erich Gamma 已提交
993 994
	}

995 996
	private _paste(args: CursorOperationArgs<{ pasteOnNewLine: boolean; text: string; }>, ctx: IMultipleCursorOperationContext): void {
		const distributedPaste = this._distributePasteToCursors(args, ctx);
E
Erich Gamma 已提交
997

998
		ctx.cursorPositionChangeReason = CursorChangeReason.Paste;
E
Erich Gamma 已提交
999
		if (distributedPaste) {
1000
			this._applyEdits(ctx, TypeOperations.distributedPaste(this.context.config, this.context.model, this._getAllCursorsModelState(true), distributedPaste));
E
Erich Gamma 已提交
1001
		} else {
1002
			this._applyEdits(ctx, TypeOperations.paste(this.context.config, this.context.model, this._getAllCursorsModelState(), args.eventData.text, args.eventData.pasteOnNewLine));
E
Erich Gamma 已提交
1003 1004 1005
		}
	}

1006
	private _deleteLeft(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
1007
		this._applyEdits(ctx, DeleteOperations.deleteLeft(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
1008 1009
	}

1010
	private _deleteRight(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
1011
		this._applyEdits(ctx, DeleteOperations.deleteRight(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
1012 1013
	}

1014
	private _cut(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
1015
		this._applyEdits(ctx, DeleteOperations.cut(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
1016 1017 1018 1019
	}

	// -------------------- END editing operations

1020
	private _undo(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
1021
		ctx.cursorPositionChangeReason = CursorChangeReason.Undo;
A
Alex Dima 已提交
1022
		this._interpretCommandResult(this._model.undo());
E
Erich Gamma 已提交
1023 1024
	}

1025
	private _redo(args: CursorOperationArgs<void>, ctx: IMultipleCursorOperationContext): void {
1026
		ctx.cursorPositionChangeReason = CursorChangeReason.Redo;
A
Alex Dima 已提交
1027
		this._interpretCommandResult(this._model.redo());
E
Erich Gamma 已提交
1028 1029
	}

1030 1031
	private _externalExecuteCommand(args: CursorOperationArgs<editorCommon.ICommand>, ctx: IMultipleCursorOperationContext): void {
		const command = args.eventData;
1032

A
Alex Dima 已提交
1033
		this._cursors.killSecondaryCursors();
1034

A
Alex Dima 已提交
1035 1036
		ctx.shouldPushStackElementBefore = true;
		ctx.shouldPushStackElementAfter = true;
1037 1038 1039

		ctx.executeCommands[0] = command;
		ctx.isAutoWhitespaceCommand[0] = false;
E
Erich Gamma 已提交
1040 1041
	}

1042 1043
	private _externalExecuteCommands(args: CursorOperationArgs<editorCommon.ICommand[]>, ctx: IMultipleCursorOperationContext): void {
		const commands = args.eventData;
A
Alex Dima 已提交
1044

A
Alex Dima 已提交
1045 1046
		ctx.shouldPushStackElementBefore = true;
		ctx.shouldPushStackElementAfter = true;
A
Alex Dima 已提交
1047

1048
		for (let i = 0; i < commands.length; i++) {
A
Alex Dima 已提交
1049 1050 1051
			ctx.executeCommands[i] = commands[i];
			ctx.isAutoWhitespaceCommand[i] = false;
		}
E
Erich Gamma 已提交
1052 1053
	}
}