cursor.ts 37.2 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 30 31 32
	shouldReveal: boolean;
	shouldPushStackElementBefore: boolean;
	shouldPushStackElementAfter: boolean;
	eventSource: string;
	eventData: any;
A
Alex Dima 已提交
33
	executeCommands: editorCommon.ICommand[];
34
	isAutoWhitespaceCommand: boolean[];
E
Erich Gamma 已提交
35 36 37 38 39 40 41 42
}

interface IExecContext {
	selectionStartMarkers: string[];
	positionMarkers: string[];
}

interface ICommandData {
A
Alex Dima 已提交
43
	operations: editorCommon.IIdentifiedSingleEditOperation[];
E
Erich Gamma 已提交
44
	hadTrackedRange: boolean;
A
Alex Dima 已提交
45
	hadTrackedEditOperation: boolean;
E
Erich Gamma 已提交
46 47 48
}

interface ICommandsData {
A
Alex Dima 已提交
49
	operations: editorCommon.IIdentifiedSingleEditOperation[];
E
Erich Gamma 已提交
50 51
	hadTrackedRanges: boolean[];
	anyoneHadTrackedRange: boolean;
A
Alex Dima 已提交
52
	anyoneHadTrackedEditOperation: boolean;
E
Erich Gamma 已提交
53 54
}

A
Alex Dima 已提交
55
export class Cursor extends Disposable implements ICursors {
A
Alex Dima 已提交
56 57 58 59 60 61 62

	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);
	}
E
Erich Gamma 已提交
63

J
Johannes Rieken 已提交
64
	private configuration: editorCommon.IConfiguration;
A
Alex Dima 已提交
65
	public context: CursorContext;
J
Johannes Rieken 已提交
66
	private model: editorCommon.IModel;
A
Alex Dima 已提交
67
	private _eventEmitter: EventEmitter;
E
Erich Gamma 已提交
68

A
Alex Dima 已提交
69 70 71
	public addBulkListener(listener: BulkListenerCallback): IDisposable {
		return this._eventEmitter.addBulkListener(listener);
	}
E
Erich Gamma 已提交
72 73

	private cursors: CursorCollection;
J
Johannes Rieken 已提交
74
	private viewModelHelper: IViewModelHelper;
E
Erich Gamma 已提交
75

J
Johannes Rieken 已提交
76
	private _isHandling: boolean;
77
	private _isDoingComposition: boolean;
A
Alex Dima 已提交
78
	private _columnSelectData: IColumnSelectData;
E
Erich Gamma 已提交
79

J
Johannes Rieken 已提交
80
	private enableEmptySelectionClipboard: boolean;
E
Erich Gamma 已提交
81

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

86
	constructor(configuration: editorCommon.IConfiguration, model: editorCommon.IModel, viewModelHelper: IViewModelHelper, enableEmptySelectionClipboard: boolean) {
A
Alex Dima 已提交
87 88
		super();
		this._eventEmitter = this._register(new EventEmitter());
E
Erich Gamma 已提交
89 90 91 92
		this.configuration = configuration;
		this.model = model;
		this.viewModelHelper = viewModelHelper;
		this.enableEmptySelectionClipboard = enableEmptySelectionClipboard;
A
Alex Dima 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

		const createCursorContext = () => {
			const config = new CursorConfiguration(
				this.model.getLanguageIdentifier(),
				this.model.getOneIndent(),
				this.model.getOptions(),
				this.configuration
			);
			this.context = new CursorContext(
				this.model,
				this.viewModelHelper,
				config
			);
			if (this.cursors) {
				this.cursors.updateContext(this.context);
			}
		};
		createCursorContext();

		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 170 171 172 173 174 175 176 177
		this._registerHandlers();
	}

	public dispose(): void {
		this.model = null;
		this.cursors.dispose();
		this.cursors = null;
		this.configuration = null;
		this.viewModelHelper = null;
		super.dispose();
	}

A
Alex Dima 已提交
178
	public getPrimaryCursor(): CursorState {
179
		return this.cursors.getPrimaryCursor();
A
Alex Dima 已提交
180 181 182 183 184 185 186
	}

	public getLastAddedCursorIndex(): number {
		return this.cursors.getLastAddedCursorIndex();
	}

	public getAll(): CursorState[] {
187
		return this.cursors.getAll();
A
Alex Dima 已提交
188 189 190 191 192 193 194 195 196 197
	}

	public setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void {
		const oldSelections = this.cursors.getSelections();
		const oldViewSelections = this.cursors.getViewSelections();

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

198
		this.cursors.setStates(states);
A
Alex Dima 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
		this.cursors.normalize();
		this._columnSelectData = null;

		const newSelections = this.cursors.getSelections();
		const newViewSelections = this.cursors.getViewSelections();

		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 已提交
227 228 229 230
	public setColumnSelectData(columnSelectData: IColumnSelectData): void {
		this._columnSelectData = columnSelectData;
	}

A
Alex Dima 已提交
231
	public reveal(horizontal: boolean, target: RevealTarget): void {
232 233 234 235 236
		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 已提交
237 238
	}

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

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

		var selections = this.cursors.getSelections(),
J
Johannes Rieken 已提交
248
			result: editorCommon.ICursorState[] = [],
249
			selection: Selection;
E
Erich Gamma 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

		for (var i = 0; i < selections.length; i++) {
			selection = selections[i];

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

		return result;
	}

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

A
Alex Dima 已提交
272
		var desiredSelections: ISelection[] = [],
J
Johannes Rieken 已提交
273
			state: editorCommon.ICursorState;
E
Erich Gamma 已提交
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

		for (var i = 0; i < states.length; i++) {
			state = states[i];

			var positionLineNumber = 1, positionColumn = 1;

			// 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;
			}

			var selectionStartLineNumber = positionLineNumber, selectionStartColumn = positionColumn;

			// 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
			});
		}

J
Johannes Rieken 已提交
306
		this._onHandler('restoreState', (ctx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
307 308
			this.cursors.setSelections(desiredSelections);
			return false;
A
Alex Dima 已提交
309
		}, 'restoreState', null);
E
Erich Gamma 已提交
310 311
	}

312 313
	private _onModelContentChanged(hadFlushEvent: boolean): void {
		if (hadFlushEvent) {
E
Erich Gamma 已提交
314 315 316
			// a model.setValue() was called
			this.cursors.dispose();

A
Alex Dima 已提交
317
			this.cursors = new CursorCollection(this.context);
E
Erich Gamma 已提交
318

319 320
			this.emitCursorPositionChanged('model', CursorChangeReason.ContentFlush);
			this.emitCursorSelectionChanged('model', CursorChangeReason.ContentFlush);
E
Erich Gamma 已提交
321 322
		} else {
			if (!this._isHandling) {
323 324
				// Read the markers before entering `_onHandler`, since that would validate
				// the position and ruin the markers
325
				const selectionsFromMarkers = this.cursors.readSelectionFromMarkers();
J
Johannes Rieken 已提交
326
				this._onHandler('recoverSelectionFromMarkers', (ctx: IMultipleCursorOperationContext) => {
A
Alex Dima 已提交
327 328
					ctx.cursorPositionChangeReason = CursorChangeReason.RecoverFromMarkers;
					ctx.shouldReveal = false;
E
Erich Gamma 已提交
329 330
					ctx.shouldPushStackElementBefore = false;
					ctx.shouldPushStackElementAfter = false;
331
					this.cursors.setSelections(selectionsFromMarkers);
A
Alex Dima 已提交
332
				}, 'modelChange', null);
E
Erich Gamma 已提交
333 334 335 336 337 338
			}
		}
	}

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

339
	public getSelection(): Selection {
A
Alex Dima 已提交
340
		return this.cursors.getPrimaryCursor().modelState.selection;
E
Erich Gamma 已提交
341 342
	}

343
	public getSelections(): Selection[] {
E
Erich Gamma 已提交
344 345 346
		return this.cursors.getSelections();
	}

A
Alex Dima 已提交
347
	public getPosition(): Position {
A
Alex Dima 已提交
348
		return this.cursors.getPrimaryCursor().modelState.position;
E
Erich Gamma 已提交
349 350
	}

A
Alex Dima 已提交
351
	public setSelections(source: string, selections: ISelection[]): void {
J
Johannes Rieken 已提交
352
		this._onHandler('setSelections', (ctx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
353 354 355
			ctx.shouldReveal = false;
			this.cursors.setSelections(selections);
			return false;
A
Alex Dima 已提交
356
		}, source, null);
E
Erich Gamma 已提交
357 358 359 360
	}

	// ------ auxiliary handling logic

A
Alex Dima 已提交
361
	private _createAndInterpretHandlerCtx(eventSource: string, eventData: any, callback: (currentHandlerCtx: IMultipleCursorOperationContext) => void): void {
E
Erich Gamma 已提交
362

A
Alex Dima 已提交
363
		var ctx: IMultipleCursorOperationContext = {
364
			cursorPositionChangeReason: CursorChangeReason.NotSet,
E
Erich Gamma 已提交
365 366 367 368
			shouldReveal: true,
			eventSource: eventSource,
			eventData: eventData,
			executeCommands: [],
369
			isAutoWhitespaceCommand: [],
E
Erich Gamma 已提交
370
			shouldPushStackElementBefore: false,
A
Alex Dima 已提交
371
			shouldPushStackElementAfter: false
E
Erich Gamma 已提交
372 373
		};

A
Alex Dima 已提交
374
		callback(ctx);
E
Erich Gamma 已提交
375

A
Alex Dima 已提交
376
		this._interpretHandlerContext(ctx);
E
Erich Gamma 已提交
377 378 379
		this.cursors.normalize();
	}

380
	private _onHandler(command: string, handler: (ctx: IMultipleCursorOperationContext) => void, source: string, data: any): void {
E
Erich Gamma 已提交
381 382 383 384

		this._isHandling = true;

		try {
A
Alex Dima 已提交
385 386
			const oldSelections = this.cursors.getSelections();
			const oldViewSelections = this.cursors.getViewSelections();
387

A
Alex Dima 已提交
388 389 390
			// ensure valid state on all cursors
			this.cursors.ensureValidState();

A
Alex Dima 已提交
391 392
			let cursorPositionChangeReason: CursorChangeReason;
			let shouldReveal: boolean;
E
Erich Gamma 已提交
393

A
Alex Dima 已提交
394
			this._createAndInterpretHandlerCtx(source, data, (currentHandlerCtx: IMultipleCursorOperationContext) => {
395
				handler(currentHandlerCtx);
E
Erich Gamma 已提交
396 397 398 399 400

				cursorPositionChangeReason = currentHandlerCtx.cursorPositionChangeReason;
				shouldReveal = currentHandlerCtx.shouldReveal;
			});

A
Alex Dima 已提交
401 402
			const newSelections = this.cursors.getSelections();
			const newViewSelections = this.cursors.getViewSelections();
E
Erich Gamma 已提交
403

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

			if (somethingChanged) {
A
Alex Dima 已提交
421
				this.emitCursorPositionChanged(source, cursorPositionChangeReason);
E
Erich Gamma 已提交
422 423

				if (shouldReveal) {
424
					this._revealRange(RevealTarget.Primary, VerticalRevealType.Simple, true);
E
Erich Gamma 已提交
425
				}
A
Alex Dima 已提交
426
				this.emitCursorSelectionChanged(source, 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 436 437 438 439 440 441
		}

		this._isHandling = false;
	}

	private _interpretHandlerContext(ctx: IMultipleCursorOperationContext): void {
		if (ctx.shouldPushStackElementBefore) {
			this.model.pushStackElement();
			ctx.shouldPushStackElementBefore = false;
		}

A
Alex Dima 已提交
442
		this._columnSelectData = null;
A
Alex Dima 已提交
443

A
Alex Dima 已提交
444
		this._internalExecuteCommands(ctx.executeCommands, ctx.isAutoWhitespaceCommand);
E
Erich Gamma 已提交
445 446 447 448 449 450 451 452
		ctx.executeCommands = [];

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

A
Alex Dima 已提交
453
	private _interpretCommandResult(cursorState: Selection[]): void {
454
		if (!cursorState || cursorState.length === 0) {
A
Alex Dima 已提交
455
			return;
E
Erich Gamma 已提交
456 457 458 459 460
		}

		this.cursors.setSelections(cursorState);
	}

J
Johannes Rieken 已提交
461
	private _getEditOperationsFromCommand(ctx: IExecContext, majorIdentifier: number, command: editorCommon.ICommand, isAutoWhitespaceCommand: boolean): ICommandData {
E
Erich Gamma 已提交
462 463
		// This method acts as a transaction, if the command fails
		// everything it has done is ignored
A
Alex Dima 已提交
464
		var operations: editorCommon.IIdentifiedSingleEditOperation[] = [],
E
Erich Gamma 已提交
465 466
			operationMinor = 0;

J
Johannes Rieken 已提交
467
		var addEditOperation = (selection: Range, text: string) => {
E
Erich Gamma 已提交
468 469 470 471 472 473 474 475 476 477 478
			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,
479 480
				forceMoveMarkers: false,
				isAutoWhitespaceEdit: isAutoWhitespaceCommand
E
Erich Gamma 已提交
481 482 483
			});
		};

A
Alex Dima 已提交
484 485 486 487 488 489
		var hadTrackedEditOperation = false;
		var addTrackedEditOperation = (selection: Range, text: string) => {
			hadTrackedEditOperation = true;
			addEditOperation(selection, text);
		};

E
Erich Gamma 已提交
490
		var hadTrackedRange = false;
J
Johannes Rieken 已提交
491 492 493
		var trackSelection = (selection: Selection, trackPreviousOnEmpty?: boolean) => {
			var selectionMarkerStickToPreviousCharacter: boolean,
				positionMarkerStickToPreviousCharacter: boolean;
E
Erich Gamma 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

			if (selection.isEmpty()) {
				// Try to lock it with surrounding text
				if (typeof trackPreviousOnEmpty === 'boolean') {
					selectionMarkerStickToPreviousCharacter = trackPreviousOnEmpty;
					positionMarkerStickToPreviousCharacter = trackPreviousOnEmpty;
				} else {
					var maxLineColumn = this.model.getLineMaxColumn(selection.startLineNumber);
					if (selection.startColumn === maxLineColumn) {
						selectionMarkerStickToPreviousCharacter = true;
						positionMarkerStickToPreviousCharacter = true;
					} else {
						selectionMarkerStickToPreviousCharacter = false;
						positionMarkerStickToPreviousCharacter = false;
					}
				}
			} else {
511
				if (selection.getDirection() === SelectionDirection.LTR) {
E
Erich Gamma 已提交
512 513 514 515 516 517 518 519 520
					selectionMarkerStickToPreviousCharacter = false;
					positionMarkerStickToPreviousCharacter = true;
				} else {
					selectionMarkerStickToPreviousCharacter = true;
					positionMarkerStickToPreviousCharacter = false;
				}
			}

			var l = ctx.selectionStartMarkers.length;
A
Alex Dima 已提交
521 522
			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 已提交
523 524 525
			return l.toString();
		};

J
Johannes Rieken 已提交
526
		var editOperationBuilder: editorCommon.IEditOperationBuilder = {
E
Erich Gamma 已提交
527
			addEditOperation: addEditOperation,
A
Alex Dima 已提交
528
			addTrackedEditOperation: addTrackedEditOperation,
E
Erich Gamma 已提交
529 530 531 532 533 534 535
			trackSelection: trackSelection
		};

		try {
			command.getEditOperations(this.model, editOperationBuilder);
		} catch (e) {
			e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command.");
A
Alex Dima 已提交
536
			onUnexpectedError(e);
E
Erich Gamma 已提交
537 538
			return {
				operations: [],
A
Alex Dima 已提交
539 540
				hadTrackedRange: false,
				hadTrackedEditOperation: false
E
Erich Gamma 已提交
541 542 543 544 545
			};
		}

		return {
			operations: operations,
A
Alex Dima 已提交
546 547
			hadTrackedRange: hadTrackedRange,
			hadTrackedEditOperation: hadTrackedEditOperation
E
Erich Gamma 已提交
548 549 550
		};
	}

J
Johannes Rieken 已提交
551
	private _getEditOperations(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): ICommandsData {
E
Erich Gamma 已提交
552
		var oneResult: ICommandData;
A
Alex Dima 已提交
553
		var operations: editorCommon.IIdentifiedSingleEditOperation[] = [];
E
Erich Gamma 已提交
554
		var hadTrackedRanges: boolean[] = [];
A
Alex Dima 已提交
555
		var anyoneHadTrackedEditOperation: boolean = false;
E
Erich Gamma 已提交
556 557 558 559
		var anyoneHadTrackedRange: boolean;

		for (var i = 0; i < commands.length; i++) {
			if (commands[i]) {
560
				oneResult = this._getEditOperationsFromCommand(ctx, i, commands[i], isAutoWhitespaceCommand[i]);
E
Erich Gamma 已提交
561 562 563
				operations = operations.concat(oneResult.operations);
				hadTrackedRanges[i] = oneResult.hadTrackedRange;
				anyoneHadTrackedRange = anyoneHadTrackedRange || hadTrackedRanges[i];
A
Alex Dima 已提交
564
				anyoneHadTrackedEditOperation = anyoneHadTrackedEditOperation || oneResult.hadTrackedEditOperation;
E
Erich Gamma 已提交
565 566 567 568 569 570 571
			} else {
				hadTrackedRanges[i] = false;
			}
		}
		return {
			operations: operations,
			hadTrackedRanges: hadTrackedRanges,
A
Alex Dima 已提交
572 573
			anyoneHadTrackedRange: anyoneHadTrackedRange,
			anyoneHadTrackedEditOperation: anyoneHadTrackedEditOperation
E
Erich Gamma 已提交
574 575 576
		};
	}

A
Alex Dima 已提交
577
	private _getLoserCursorMap(operations: editorCommon.IIdentifiedSingleEditOperation[]): { [index: string]: boolean; } {
E
Erich Gamma 已提交
578 579 580 581
		// This is destructive on the array
		operations = operations.slice(0);

		// Sort operations with last one first
J
Johannes Rieken 已提交
582
		operations.sort((a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation): number => {
E
Erich Gamma 已提交
583 584 585 586 587
			// Note the minus!
			return -(Range.compareRangesUsingEnds(a.range, b.range));
		});

		// Operations can not overlap!
J
Johannes Rieken 已提交
588
		var loserCursorsMap: { [index: string]: boolean; } = {};
E
Erich Gamma 已提交
589

A
Alex Dima 已提交
590 591
		var previousOp: editorCommon.IIdentifiedSingleEditOperation;
		var currentOp: editorCommon.IIdentifiedSingleEditOperation;
E
Erich Gamma 已提交
592 593 594 595 596 597
		var loserMajor: number;

		for (var i = 1; i < operations.length; i++) {
			previousOp = operations[i - 1];
			currentOp = operations[i];

598
			if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) {
E
Erich Gamma 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

				if (previousOp.identifier.major > currentOp.identifier.major) {
					// previousOp loses the battle
					loserMajor = previousOp.identifier.major;
				} else {
					loserMajor = currentOp.identifier.major;
				}

				loserCursorsMap[loserMajor.toString()] = true;

				for (var j = 0; j < operations.length; j++) {
					if (operations[j].identifier.major === loserMajor) {
						operations.splice(j, 1);
						if (j < i) {
							i--;
						}
						j--;
					}
				}

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

		return loserCursorsMap;
	}

A
Alex Dima 已提交
628
	private _internalExecuteCommands(commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): void {
J
Johannes Rieken 已提交
629
		var ctx: IExecContext = {
E
Erich Gamma 已提交
630 631 632 633
			selectionStartMarkers: [],
			positionMarkers: []
		};

A
Alex Dima 已提交
634
		this._innerExecuteCommands(ctx, commands, isAutoWhitespaceCommand);
E
Erich Gamma 已提交
635 636 637 638 639 640
		for (var i = 0; i < ctx.selectionStartMarkers.length; i++) {
			this.model._removeMarker(ctx.selectionStartMarkers[i]);
			this.model._removeMarker(ctx.positionMarkers[i]);
		}
	}

A
Alex Dima 已提交
641
	private _arrayIsEmpty(commands: editorCommon.ICommand[]): boolean {
J
Johannes Rieken 已提交
642 643
		var i: number,
			len: number;
E
Erich Gamma 已提交
644 645 646 647 648 649 650 651 652 653

		for (i = 0, len = commands.length; i < len; i++) {
			if (commands[i]) {
				return false;
			}
		}

		return true;
	}

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

		if (this.configuration.editor.readOnly) {
A
Alex Dima 已提交
657
			return;
E
Erich Gamma 已提交
658 659 660
		}

		if (this._arrayIsEmpty(commands)) {
A
Alex Dima 已提交
661
			return;
E
Erich Gamma 已提交
662 663 664 665
		}

		var selectionsBefore = this.cursors.getSelections();

666
		var commandsData = this._getEditOperations(ctx, commands, isAutoWhitespaceCommand);
E
Erich Gamma 已提交
667
		if (commandsData.operations.length === 0 && !commandsData.anyoneHadTrackedRange) {
A
Alex Dima 已提交
668
			return;
E
Erich Gamma 已提交
669 670 671 672 673 674 675 676 677 678 679
		}

		var rawOperations = commandsData.operations;

		var editableRange = this.model.getEditableRange();
		var editableRangeStart = editableRange.getStartPosition();
		var editableRangeEnd = editableRange.getEndPosition();
		for (var i = 0; i < rawOperations.length; i++) {
			var operationRange = rawOperations[i].range;
			if (!editableRangeStart.isBeforeOrEqual(operationRange.getStartPosition()) || !operationRange.getEndPosition().isBeforeOrEqual(editableRangeEnd)) {
				// These commands are outside of the editable range
A
Alex Dima 已提交
680
				return;
E
Erich Gamma 已提交
681 682 683 684 685 686 687
			}
		}

		var loserCursorsMap = this._getLoserCursorMap(rawOperations);
		if (loserCursorsMap.hasOwnProperty('0')) {
			// These commands are very messed up
			console.warn('Ignoring commands');
A
Alex Dima 已提交
688
			return;
E
Erich Gamma 已提交
689 690 691
		}

		// Remove operations belonging to losing cursors
A
Alex Dima 已提交
692
		var filteredOperations: editorCommon.IIdentifiedSingleEditOperation[] = [];
E
Erich Gamma 已提交
693 694 695 696 697 698
		for (var i = 0; i < rawOperations.length; i++) {
			if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
				filteredOperations.push(rawOperations[i]);
			}
		}

A
Alex Dima 已提交
699 700 701 702 703
		// TODO@Alex: find a better way to do this.
		// give the hint that edit operations are tracked to the model
		if (commandsData.anyoneHadTrackedEditOperation && filteredOperations.length > 0) {
			filteredOperations[0]._isTracked = true;
		}
J
Johannes Rieken 已提交
704 705
		var selectionsAfter = this.model.pushEditOperations(selectionsBefore, filteredOperations, (inverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[]): Selection[] => {
			var groupedInverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[][] = [];
E
Erich Gamma 已提交
706 707 708 709 710
			for (var i = 0; i < selectionsBefore.length; i++) {
				groupedInverseEditOperations[i] = [];
			}
			for (var i = 0; i < inverseEditOperations.length; i++) {
				var op = inverseEditOperations[i];
711 712 713 714
				if (!op.identifier) {
					// perhaps auto whitespace trim edits
					continue;
				}
E
Erich Gamma 已提交
715 716
				groupedInverseEditOperations[op.identifier.major].push(op);
			}
J
Johannes Rieken 已提交
717
			var minorBasedSorter = (a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation) => {
E
Erich Gamma 已提交
718 719
				return a.identifier.minor - b.identifier.minor;
			};
720
			var cursorSelections: Selection[] = [];
E
Erich Gamma 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
			for (var i = 0; i < selectionsBefore.length; i++) {
				if (groupedInverseEditOperations[i].length > 0 || commandsData.hadTrackedRanges[i]) {
					groupedInverseEditOperations[i].sort(minorBasedSorter);
					cursorSelections[i] = commands[i].computeCursorState(this.model, {
						getInverseEditOperations: () => {
							return groupedInverseEditOperations[i];
						},

						getTrackedSelection: (id: string) => {
							var idx = parseInt(id, 10);
							var selectionStartMarker = this.model._getMarker(ctx.selectionStartMarkers[idx]);
							var positionMarker = this.model._getMarker(ctx.positionMarkers[idx]);
							return new Selection(selectionStartMarker.lineNumber, selectionStartMarker.column, positionMarker.lineNumber, positionMarker.column);
						}
					});
				} else {
					cursorSelections[i] = selectionsBefore[i];
				}
			}
			return cursorSelections;
		});

		// Extract losing cursors
		var losingCursorIndex: string;
		var losingCursors: number[] = [];
		for (losingCursorIndex in loserCursorsMap) {
			if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
				losingCursors.push(parseInt(losingCursorIndex, 10));
			}
		}

		// Sort losing cursors descending
J
Johannes Rieken 已提交
753
		losingCursors.sort((a: number, b: number): number => {
E
Erich Gamma 已提交
754 755 756 757 758 759 760 761
			return b - a;
		});

		// Remove losing cursors
		for (var i = 0; i < losingCursors.length; i++) {
			selectionsAfter.splice(losingCursors[i], 1);
		}

A
Alex Dima 已提交
762
		this._interpretCommandResult(selectionsAfter);
E
Erich Gamma 已提交
763 764 765 766 767 768
	}


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

769
	private emitCursorPositionChanged(source: string, reason: CursorChangeReason): void {
E
Erich Gamma 已提交
770 771 772 773 774 775 776 777
		var positions = this.cursors.getPositions();
		var primaryPosition = positions[0];
		var secondaryPositions = positions.slice(1);

		var viewPositions = this.cursors.getViewPositions();
		var primaryViewPosition = viewPositions[0];
		var secondaryViewPositions = viewPositions.slice(1);

J
Johannes Rieken 已提交
778
		var isInEditableRange: boolean = true;
E
Erich Gamma 已提交
779 780 781 782 783 784
		if (this.model.hasEditableRange()) {
			var editableRange = this.model.getEditableRange();
			if (!editableRange.containsPosition(primaryPosition)) {
				isInEditableRange = false;
			}
		}
785
		var e: ICursorPositionChangedEvent = {
E
Erich Gamma 已提交
786 787 788 789 790 791 792 793
			position: primaryPosition,
			viewPosition: primaryViewPosition,
			secondaryPositions: secondaryPositions,
			secondaryViewPositions: secondaryViewPositions,
			reason: reason,
			source: source,
			isInEditableRange: isInEditableRange
		};
A
Alex Dima 已提交
794
		this._eventEmitter.emit(CursorEventType.CursorPositionChanged, e);
E
Erich Gamma 已提交
795 796
	}

797
	private emitCursorSelectionChanged(source: string, reason: CursorChangeReason): void {
798 799 800
		let selections = this.cursors.getSelections();
		let primarySelection = selections[0];
		let secondarySelections = selections.slice(1);
E
Erich Gamma 已提交
801

802 803 804 805
		let viewSelections = this.cursors.getViewSelections();
		let primaryViewSelection = viewSelections[0];
		let secondaryViewSelections = viewSelections.slice(1);

806
		let e: ICursorSelectionChangedEvent = {
E
Erich Gamma 已提交
807
			selection: primarySelection,
808
			viewSelection: primaryViewSelection,
E
Erich Gamma 已提交
809
			secondarySelections: secondarySelections,
810
			secondaryViewSelections: secondaryViewSelections,
811
			source: source || 'keyboard',
E
Erich Gamma 已提交
812 813
			reason: reason
		};
A
Alex Dima 已提交
814
		this._eventEmitter.emit(CursorEventType.CursorSelectionChanged, e);
E
Erich Gamma 已提交
815 816
	}

817
	private _revealRange(revealTarget: RevealTarget, verticalType: VerticalRevealType, revealHorizontal: boolean): void {
E
Erich Gamma 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
		var positions = this.cursors.getPositions();
		var viewPositions = this.cursors.getViewPositions();

		var position = positions[0];
		var viewPosition = viewPositions[0];

		if (revealTarget === RevealTarget.TopMost) {
			for (var i = 1; i < positions.length; i++) {
				if (positions[i].isBefore(position)) {
					position = positions[i];
					viewPosition = viewPositions[i];
				}
			}
		} else if (revealTarget === RevealTarget.BottomMost) {
			for (var i = 1; i < positions.length; i++) {
				if (position.isBeforeOrEqual(positions[i])) {
					position = positions[i];
					viewPosition = viewPositions[i];
				}
			}
		} else {
			if (positions.length > 1) {
				// no revealing!
				return;
			}
		}

		var range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
		var viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
847
		this.emitCursorRevealRange(range, viewRange, verticalType, revealHorizontal);
848 849
	}

850
	public emitCursorRevealRange(range: Range, viewRange: Range, verticalType: VerticalRevealType, revealHorizontal: boolean) {
851
		var e: ICursorRevealRangeEvent = {
E
Erich Gamma 已提交
852 853 854
			range: range,
			viewRange: viewRange,
			verticalType: verticalType,
855
			revealHorizontal: revealHorizontal
E
Erich Gamma 已提交
856
		};
A
Alex Dima 已提交
857
		this._eventEmitter.emit(CursorEventType.CursorRevealRange, e);
E
Erich Gamma 已提交
858 859 860 861 862
	}

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

J
Johannes Rieken 已提交
863
	public trigger(source: string, handlerId: string, payload: any): void {
A
Alex Dima 已提交
864
		if (!this._handlers.hasOwnProperty(handlerId)) {
A
Alex Dima 已提交
865
			const command = CommonEditorRegistry.getEditorCommand(handlerId);
A
Alex Dima 已提交
866
			if (!command || !(command instanceof CoreEditorCommand)) {
A
Alex Dima 已提交
867 868 869 870 871
				return;
			}

			payload = payload || {};
			payload.source = source;
A
Alex Dima 已提交
872
			command.runCoreEditorCommand(this, payload);
A
Alex Dima 已提交
873 874 875 876 877 878
			return;
		}
		let handler = this._handlers[handlerId];
		this._onHandler(handlerId, handler, source, payload);
	}

E
Erich Gamma 已提交
879
	private _registerHandlers(): void {
A
Alex Dima 已提交
880
		let H = editorCommon.Handler;
E
Erich Gamma 已提交
881

J
Johannes Rieken 已提交
882 883 884
		this._handlers[H.LineInsertBefore] = (ctx) => this._lineInsertBefore(ctx);
		this._handlers[H.LineInsertAfter] = (ctx) => this._lineInsertAfter(ctx);
		this._handlers[H.LineBreakInsert] = (ctx) => this._lineBreakInsert(ctx);
E
Erich Gamma 已提交
885

J
Johannes Rieken 已提交
886 887
		this._handlers[H.Type] = (ctx) => this._type(ctx);
		this._handlers[H.ReplacePreviousChar] = (ctx) => this._replacePreviousChar(ctx);
888 889
		this._handlers[H.CompositionStart] = (ctx) => this._compositionStart(ctx);
		this._handlers[H.CompositionEnd] = (ctx) => this._compositionEnd(ctx);
J
Johannes Rieken 已提交
890 891 892 893
		this._handlers[H.Tab] = (ctx) => this._tab(ctx);
		this._handlers[H.Indent] = (ctx) => this._indent(ctx);
		this._handlers[H.Outdent] = (ctx) => this._outdent(ctx);
		this._handlers[H.Paste] = (ctx) => this._paste(ctx);
894

J
Johannes Rieken 已提交
895 896
		this._handlers[H.DeleteLeft] = (ctx) => this._deleteLeft(ctx);
		this._handlers[H.DeleteRight] = (ctx) => this._deleteRight(ctx);
E
Erich Gamma 已提交
897

J
Johannes Rieken 已提交
898
		this._handlers[H.Cut] = (ctx) => this._cut(ctx);
E
Erich Gamma 已提交
899

J
Johannes Rieken 已提交
900 901
		this._handlers[H.Undo] = (ctx) => this._undo(ctx);
		this._handlers[H.Redo] = (ctx) => this._redo(ctx);
E
Erich Gamma 已提交
902

J
Johannes Rieken 已提交
903 904
		this._handlers[H.ExecuteCommand] = (ctx) => this._externalExecuteCommand(ctx);
		this._handlers[H.ExecuteCommands] = (ctx) => this._externalExecuteCommands(ctx);
E
Erich Gamma 已提交
905 906
	}

A
Alex Dima 已提交
907
	public getColumnSelectData(): IColumnSelectData {
A
Alex Dima 已提交
908 909
		if (this._columnSelectData) {
			return this._columnSelectData;
A
Alex Dima 已提交
910
		}
A
Alex Dima 已提交
911 912 913 914 915 916
		const primaryCursor = this.cursors.getPrimaryCursor();
		const primaryPos = primaryCursor.viewState.position;
		return {
			toViewLineNumber: primaryPos.lineNumber,
			toViewVisualColumn: CursorColumns.visibleColumnFromColumn2(this.context.config, this.context.viewModel, primaryPos)
		};
A
Alex Dima 已提交
917
	}
A
Alex Dima 已提交
918

A
Alex Dima 已提交
919 920
	// -------------------- START editing operations

921 922 923 924 925 926 927 928 929 930
	private _applyEdits(ctx: IMultipleCursorOperationContext, edits: EditOperationResult): void {
		ctx.shouldReveal = true;
		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 已提交
931 932 933
		}
	}

934 935
	private _getAllCursorsModelState(sorted: boolean = false): SingleCursorState[] {
		let cursors = this.cursors.getAll();
A
Alex Dima 已提交
936

937 938 939 940 941 942 943 944 945 946 947
		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 已提交
948 949
	}

950
	private _lineInsertBefore(ctx: IMultipleCursorOperationContext): void {
951
		this._applyEdits(ctx, TypeOperations.lineInsertBefore(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
952 953
	}

954
	private _lineInsertAfter(ctx: IMultipleCursorOperationContext): void {
955
		this._applyEdits(ctx, TypeOperations.lineInsertAfter(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
956 957
	}

958
	private _lineBreakInsert(ctx: IMultipleCursorOperationContext): void {
959
		this._applyEdits(ctx, TypeOperations.lineBreakInsert(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
960 961
	}

962
	private _type(ctx: IMultipleCursorOperationContext): void {
E
Erich Gamma 已提交
963 964
		var text = ctx.eventData.text;

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

968 969 970 971 972 973 974 975 976
			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 已提交
977 978

				// Here we must interpret each typed character individually, that's why we create a new context
A
Alex Dima 已提交
979
				this._createAndInterpretHandlerCtx(ctx.eventSource, ctx.eventData, (charHandlerCtx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
980

981
					// Decide what all cursors will do up-front
982
					this._applyEdits(charHandlerCtx, TypeOperations.typeWithInterceptors(this.context.config, this.context.model, this._getAllCursorsModelState(), chr));
E
Erich Gamma 已提交
983 984 985 986

					// The last typed character gets to win
					ctx.cursorPositionChangeReason = charHandlerCtx.cursorPositionChangeReason;
					ctx.shouldReveal = charHandlerCtx.shouldReveal;
A
Alex Dima 已提交
987
				});
E
Erich Gamma 已提交
988 989 990

			}
		} else {
991
			this._applyEdits(ctx, TypeOperations.typeWithoutInterceptors(this.context.config, this.context.model, this._getAllCursorsModelState(), text));
E
Erich Gamma 已提交
992 993 994
		}
	}

995
	private _replacePreviousChar(ctx: IMultipleCursorOperationContext): void {
996 997
		let text = ctx.eventData.text;
		let replaceCharCnt = ctx.eventData.replaceCharCnt;
998
		this._applyEdits(ctx, TypeOperations.replacePreviousChar(this.context.config, this.context.model, this._getAllCursorsModelState(), text, replaceCharCnt));
E
Erich Gamma 已提交
999 1000
	}

1001
	private _compositionStart(ctx: IMultipleCursorOperationContext): void {
1002 1003 1004
		this._isDoingComposition = true;
	}

1005
	private _compositionEnd(ctx: IMultipleCursorOperationContext): void {
1006 1007 1008
		this._isDoingComposition = false;
	}

1009
	private _tab(ctx: IMultipleCursorOperationContext): void {
1010
		this._applyEdits(ctx, TypeOperations.tab(this.context.config, this.context.model, this._getAllCursorsModelState()));
E
Erich Gamma 已提交
1011 1012
	}

1013
	private _indent(ctx: IMultipleCursorOperationContext): void {
1014
		this._applyEdits(ctx, TypeOperations.indent(this.context.config, this.context.model, this._getAllCursorsModelState()));
E
Erich Gamma 已提交
1015 1016
	}

1017
	private _outdent(ctx: IMultipleCursorOperationContext): void {
1018
		this._applyEdits(ctx, TypeOperations.outdent(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
	}

	private _distributePasteToCursors(ctx: IMultipleCursorOperationContext): string[] {
		if (ctx.eventData.pasteOnNewLine) {
			return null;
		}

		var selections = this.cursors.getSelections();
		if (selections.length === 1) {
			return null;
		}

		for (var i = 0; i < selections.length; i++) {
			if (selections[i].startLineNumber !== selections[i].endLineNumber) {
				return null;
			}
		}

		var pastePieces = ctx.eventData.text.split(/\r\n|\r|\n/);
		if (pastePieces.length !== selections.length) {
			return null;
		}

		return pastePieces;
E
Erich Gamma 已提交
1043 1044
	}

1045
	private _paste(ctx: IMultipleCursorOperationContext): void {
E
Erich Gamma 已提交
1046 1047
		var distributedPaste = this._distributePasteToCursors(ctx);

1048
		ctx.cursorPositionChangeReason = CursorChangeReason.Paste;
E
Erich Gamma 已提交
1049
		if (distributedPaste) {
1050
			this._applyEdits(ctx, TypeOperations.distributedPaste(this.context.config, this.context.model, this._getAllCursorsModelState(true), distributedPaste));
E
Erich Gamma 已提交
1051
		} else {
1052
			this._applyEdits(ctx, TypeOperations.paste(this.context.config, this.context.model, this._getAllCursorsModelState(), ctx.eventData.text, ctx.eventData.pasteOnNewLine));
E
Erich Gamma 已提交
1053 1054 1055
		}
	}

1056
	private _deleteLeft(ctx: IMultipleCursorOperationContext): void {
1057
		this._applyEdits(ctx, DeleteOperations.deleteLeft(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
1058 1059
	}

1060
	private _deleteRight(ctx: IMultipleCursorOperationContext): void {
1061
		this._applyEdits(ctx, DeleteOperations.deleteRight(this.context.config, this.context.model, this._getAllCursorsModelState()));
A
Alex Dima 已提交
1062 1063
	}

1064
	private _cut(ctx: IMultipleCursorOperationContext): void {
1065
		this._applyEdits(ctx, DeleteOperations.cut(this.context.config, this.context.model, this._getAllCursorsModelState(), this.enableEmptySelectionClipboard));
A
Alex Dima 已提交
1066 1067 1068 1069
	}

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

1070
	private _undo(ctx: IMultipleCursorOperationContext): void {
1071
		ctx.cursorPositionChangeReason = CursorChangeReason.Undo;
E
Erich Gamma 已提交
1072 1073 1074
		this._interpretCommandResult(this.model.undo());
	}

1075
	private _redo(ctx: IMultipleCursorOperationContext): void {
1076
		ctx.cursorPositionChangeReason = CursorChangeReason.Redo;
E
Erich Gamma 已提交
1077 1078 1079
		this._interpretCommandResult(this.model.redo());
	}

1080
	private _externalExecuteCommand(ctx: IMultipleCursorOperationContext): void {
1081 1082
		const command = <editorCommon.ICommand>ctx.eventData;

E
Erich Gamma 已提交
1083
		this.cursors.killSecondaryCursors();
1084 1085 1086

		ctx.shouldReveal = true;

A
Alex Dima 已提交
1087 1088
		ctx.shouldPushStackElementBefore = true;
		ctx.shouldPushStackElementAfter = true;
1089 1090 1091

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

1094
	private _externalExecuteCommands(ctx: IMultipleCursorOperationContext): void {
A
Alex Dima 已提交
1095 1096 1097 1098
		const commands = <editorCommon.ICommand[]>ctx.eventData;

		ctx.shouldReveal = true;

A
Alex Dima 已提交
1099 1100
		ctx.shouldPushStackElementBefore = true;
		ctx.shouldPushStackElementAfter = true;
A
Alex Dima 已提交
1101

1102
		for (let i = 0; i < commands.length; i++) {
A
Alex Dima 已提交
1103 1104 1105
			ctx.executeCommands[i] = commands[i];
			ctx.isAutoWhitespaceCommand[i] = false;
		}
E
Erich Gamma 已提交
1106 1107
	}
}