cursor.ts 63.8 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 10 11 12 13
import { onUnexpectedError } from 'vs/base/common/errors';
import { EventEmitter } from 'vs/base/common/eventEmitter';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ReplaceCommand } from 'vs/editor/common/commands/replaceCommand';
import { CursorCollection, ICursorCollectionState } from 'vs/editor/common/controller/cursorCollection';
A
Alex Dima 已提交
14
import { IOneCursorOperationContext, IViewModelHelper, OneCursor, OneCursorOp } from 'vs/editor/common/controller/oneCursor';
J
Johannes Rieken 已提交
15 16 17
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection, SelectionDirection } from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
18
import * as editorCommon from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
19
import { CursorColumns, EditOperationResult } from 'vs/editor/common/controller/cursorCommon';
J
Johannes Rieken 已提交
20
import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry';
A
Alex Dima 已提交
21
import { WordOperations, WordNavigationType } from 'vs/editor/common/controller/cursorWordOperations';
22
import { ColumnSelection, IColumnSelectResult } from 'vs/editor/common/controller/cursorColumnSelection';
A
Alex Dima 已提交
23 24
import { DeleteOperations } from 'vs/editor/common/controller/cursorDeleteOperations';
import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations';
E
Erich Gamma 已提交
25 26 27 28 29

export interface ITypingListener {
	(): void;
}

A
Alex Dima 已提交
30
const enum RevealTarget {
E
Erich Gamma 已提交
31 32 33 34 35 36
	Primary = 0,
	TopMost = 1,
	BottomMost = 2
}

interface IMultipleCursorOperationContext {
A
Alex Dima 已提交
37
	cursorPositionChangeReason: editorCommon.CursorChangeReason;
E
Erich Gamma 已提交
38 39 40 41 42 43 44 45 46 47
	shouldReveal: boolean;
	shouldRevealVerticalInCenter: boolean;
	shouldRevealHorizontal: boolean;
	shouldRevealTarget: RevealTarget;
	shouldPushStackElementBefore: boolean;
	shouldPushStackElementAfter: boolean;
	eventSource: string;
	eventData: any;
	hasExecutedCommands: boolean;
	isCursorUndo: boolean;
A
Alex Dima 已提交
48
	executeCommands: editorCommon.ICommand[];
49
	isAutoWhitespaceCommand: boolean[];
A
Alex Dima 已提交
50 51
	setColumnSelectToLineNumber: number;
	setColumnSelectToVisualColumn: number;
E
Erich Gamma 已提交
52 53 54 55 56 57 58 59
}

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

interface ICommandData {
A
Alex Dima 已提交
60
	operations: editorCommon.IIdentifiedSingleEditOperation[];
E
Erich Gamma 已提交
61 62 63 64
	hadTrackedRange: boolean;
}

interface ICommandsData {
A
Alex Dima 已提交
65
	operations: editorCommon.IIdentifiedSingleEditOperation[];
E
Erich Gamma 已提交
66 67 68 69 70 71
	hadTrackedRanges: boolean[];
	anyoneHadTrackedRange: boolean;
}

export class Cursor extends EventEmitter {

J
Johannes Rieken 已提交
72 73 74
	private editorId: number;
	private configuration: editorCommon.IConfiguration;
	private model: editorCommon.IModel;
E
Erich Gamma 已提交
75

J
Johannes Rieken 已提交
76
	private modelUnbinds: IDisposable[];
E
Erich Gamma 已提交
77 78

	// Typing listeners
J
Johannes Rieken 已提交
79 80
	private typingListeners: {
		[character: string]: ITypingListener[];
E
Erich Gamma 已提交
81 82 83 84
	};

	private cursors: CursorCollection;
	private cursorUndoStack: ICursorCollectionState[];
J
Johannes Rieken 已提交
85
	private viewModelHelper: IViewModelHelper;
E
Erich Gamma 已提交
86

J
Johannes Rieken 已提交
87 88
	private _isHandling: boolean;
	private charactersTyped: string;
E
Erich Gamma 已提交
89

J
Johannes Rieken 已提交
90
	private enableEmptySelectionClipboard: boolean;
E
Erich Gamma 已提交
91

J
Johannes Rieken 已提交
92 93
	private _handlers: {
		[key: string]: (ctx: IMultipleCursorOperationContext) => boolean;
A
Alex Dima 已提交
94 95
	};

J
Johannes Rieken 已提交
96
	constructor(editorId: number, configuration: editorCommon.IConfiguration, model: editorCommon.IModel, viewModelHelper: IViewModelHelper, enableEmptySelectionClipboard: boolean) {
E
Erich Gamma 已提交
97
		super([
A
Alex Dima 已提交
98 99 100 101
			editorCommon.EventType.CursorPositionChanged,
			editorCommon.EventType.CursorSelectionChanged,
			editorCommon.EventType.CursorRevealRange,
			editorCommon.EventType.CursorScrollRequest
E
Erich Gamma 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115
		]);
		this.editorId = editorId;
		this.configuration = configuration;
		this.model = model;
		this.viewModelHelper = viewModelHelper;
		this.enableEmptySelectionClipboard = enableEmptySelectionClipboard;
		this.cursors = new CursorCollection(this.editorId, this.model, this.configuration, this.viewModelHelper);
		this.cursorUndoStack = [];

		this.typingListeners = {};

		this._isHandling = false;

		this.modelUnbinds = [];
A
Alex Dima 已提交
116
		this.modelUnbinds.push(this.model.onDidChangeRawContent((e) => {
E
Erich Gamma 已提交
117 118
			this._onModelContentChanged(e);
		}));
A
Alex Dima 已提交
119 120
		this.modelUnbinds.push(this.model.onDidChangeLanguage((e) => {
			this._onModelLanguageChanged();
E
Erich Gamma 已提交
121
		}));
122 123
		this.modelUnbinds.push(LanguageConfigurationRegistry.onDidChange(() => {
			// TODO@Alex: react only if certain supports changed? (and if my model's mode changed)
A
Alex Dima 已提交
124
			this._onModelLanguageChanged();
E
Erich Gamma 已提交
125 126
		}));

A
Alex Dima 已提交
127
		this._handlers = {};
E
Erich Gamma 已提交
128 129 130 131
		this._registerHandlers();
	}

	public dispose(): void {
J
Joao Moreno 已提交
132
		this.modelUnbinds = dispose(this.modelUnbinds);
E
Erich Gamma 已提交
133 134 135 136 137 138 139 140
		this.model = null;
		this.cursors.dispose();
		this.cursors = null;
		this.configuration = null;
		this.viewModelHelper = null;
		super.dispose();
	}

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

		var selections = this.cursors.getSelections(),
J
Johannes Rieken 已提交
144
			result: editorCommon.ICursorState[] = [],
145
			selection: Selection;
E
Erich Gamma 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

		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 已提交
166
	public restoreState(states: editorCommon.ICursorState[]): void {
E
Erich Gamma 已提交
167

J
Johannes Rieken 已提交
168 169
		var desiredSelections: editorCommon.ISelection[] = [],
			state: editorCommon.ICursorState;
E
Erich Gamma 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

		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 已提交
202
		this._onHandler('restoreState', (ctx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
203 204
			this.cursors.setSelections(desiredSelections);
			return false;
A
Alex Dima 已提交
205
		}, 'restoreState', null);
E
Erich Gamma 已提交
206 207
	}

J
Johannes Rieken 已提交
208
	public addTypingListener(character: string, callback: ITypingListener): void {
E
Erich Gamma 已提交
209 210 211 212 213 214
		if (!this.typingListeners.hasOwnProperty(character)) {
			this.typingListeners[character] = [];
		}
		this.typingListeners[character].push(callback);
	}

J
Johannes Rieken 已提交
215
	public removeTypingListener(character: string, callback: ITypingListener): void {
E
Erich Gamma 已提交
216 217 218 219 220 221 222 223 224 225 226
		if (this.typingListeners.hasOwnProperty(character)) {
			var listeners = this.typingListeners[character];
			for (var i = 0; i < listeners.length; i++) {
				if (listeners[i] === callback) {
					listeners.splice(i, 1);
					return;
				}
			}
		}
	}

A
Alex Dima 已提交
227
	private _onModelLanguageChanged(): void {
E
Erich Gamma 已提交
228 229 230 231
		// the mode of this model has changed
		this.cursors.updateMode();
	}

J
Johannes Rieken 已提交
232
	private _onModelContentChanged(e: editorCommon.IModelContentChangedEvent): void {
A
Alex Dima 已提交
233
		if (e.changeType === editorCommon.EventType.ModelRawContentChangedFlush) {
E
Erich Gamma 已提交
234 235 236 237 238
			// a model.setValue() was called
			this.cursors.dispose();

			this.cursors = new CursorCollection(this.editorId, this.model, this.configuration, this.viewModelHelper);

A
Alex Dima 已提交
239 240
			this.emitCursorPositionChanged('model', editorCommon.CursorChangeReason.ContentFlush);
			this.emitCursorSelectionChanged('model', editorCommon.CursorChangeReason.ContentFlush);
E
Erich Gamma 已提交
241 242
		} else {
			if (!this._isHandling) {
243 244 245 246 247
				// Read the markers before entering `_onHandler`, since that would validate
				// the position and ruin the markers
				let selections: Selection[] = this.cursors.getAll().map((cursor) => {
					return cursor.beginRecoverSelectionFromMarkers();
				});
J
Johannes Rieken 已提交
248
				this._onHandler('recoverSelectionFromMarkers', (ctx: IMultipleCursorOperationContext) => {
249
					var result = this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => oneCursor.endRecoverSelectionFromMarkers(oneCtx, selections[cursorIndex]));
E
Erich Gamma 已提交
250 251 252
					ctx.shouldPushStackElementBefore = false;
					ctx.shouldPushStackElementAfter = false;
					return result;
A
Alex Dima 已提交
253
				}, 'modelChange', null);
E
Erich Gamma 已提交
254 255 256 257 258 259
			}
		}
	}

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

260
	public getSelection(): Selection {
E
Erich Gamma 已提交
261 262 263
		return this.cursors.getSelection(0);
	}

264
	public getSelections(): Selection[] {
E
Erich Gamma 已提交
265 266 267
		return this.cursors.getSelections();
	}

A
Alex Dima 已提交
268
	public getPosition(): Position {
E
Erich Gamma 已提交
269 270 271
		return this.cursors.getPosition(0);
	}

A
Alex Dima 已提交
272
	public setSelections(source: string, selections: editorCommon.ISelection[]): void {
J
Johannes Rieken 已提交
273
		this._onHandler('setSelections', (ctx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
274 275 276
			ctx.shouldReveal = false;
			this.cursors.setSelections(selections);
			return false;
A
Alex Dima 已提交
277
		}, source, null);
E
Erich Gamma 已提交
278 279 280 281
	}

	// ------ auxiliary handling logic

J
Johannes Rieken 已提交
282
	private _createAndInterpretHandlerCtx(eventSource: string, eventData: any, callback: (currentHandlerCtx: IMultipleCursorOperationContext) => void): boolean {
E
Erich Gamma 已提交
283

J
Johannes Rieken 已提交
284
		var currentHandlerCtx: IMultipleCursorOperationContext = {
A
Alex Dima 已提交
285
			cursorPositionChangeReason: editorCommon.CursorChangeReason.NotSet,
E
Erich Gamma 已提交
286 287 288 289 290 291 292
			shouldReveal: true,
			shouldRevealVerticalInCenter: false,
			shouldRevealHorizontal: true,
			shouldRevealTarget: RevealTarget.Primary,
			eventSource: eventSource,
			eventData: eventData,
			executeCommands: [],
293
			isAutoWhitespaceCommand: [],
E
Erich Gamma 已提交
294 295 296
			hasExecutedCommands: false,
			isCursorUndo: false,
			shouldPushStackElementBefore: false,
297
			shouldPushStackElementAfter: false,
A
Alex Dima 已提交
298 299
			setColumnSelectToLineNumber: 0,
			setColumnSelectToVisualColumn: 0
E
Erich Gamma 已提交
300 301 302 303 304 305 306 307 308 309
		};

		callback(currentHandlerCtx);

		this._interpretHandlerContext(currentHandlerCtx);
		this.cursors.normalize();

		return currentHandlerCtx.hasExecutedCommands;
	}

J
Johannes Rieken 已提交
310
	private _onHandler(command: string, handler: (ctx: IMultipleCursorOperationContext) => boolean, source: string, data: any): boolean {
E
Erich Gamma 已提交
311 312 313 314 315 316 317

		this._isHandling = true;
		this.charactersTyped = '';

		var handled = false;

		try {
318 319 320
			var oldSelections = this.cursors.getSelections();
			var oldViewSelections = this.cursors.getViewSelections();

A
Alex Dima 已提交
321 322 323
			// ensure valid state on all cursors
			this.cursors.ensureValidState();

E
Erich Gamma 已提交
324 325
			var prevCursorsState = this.cursors.saveState();

A
Alex Dima 已提交
326 327
			var eventSource = source;
			var cursorPositionChangeReason: editorCommon.CursorChangeReason;
E
Erich Gamma 已提交
328 329 330 331 332 333
			var shouldReveal: boolean;
			var shouldRevealVerticalInCenter: boolean;
			var shouldRevealHorizontal: boolean;
			var shouldRevealTarget: RevealTarget;
			var isCursorUndo: boolean;

J
Johannes Rieken 已提交
334
			var hasExecutedCommands = this._createAndInterpretHandlerCtx(eventSource, data, (currentHandlerCtx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
				handled = handler(currentHandlerCtx);

				cursorPositionChangeReason = currentHandlerCtx.cursorPositionChangeReason;
				shouldReveal = currentHandlerCtx.shouldReveal;
				shouldRevealTarget = currentHandlerCtx.shouldRevealTarget;
				shouldRevealVerticalInCenter = currentHandlerCtx.shouldRevealVerticalInCenter;
				shouldRevealHorizontal = currentHandlerCtx.shouldRevealHorizontal;
				isCursorUndo = currentHandlerCtx.isCursorUndo;
			});

			if (hasExecutedCommands) {
				this.cursorUndoStack = [];
			}

			// Ping typing listeners after the model emits events & after I emit events
			for (var i = 0; i < this.charactersTyped.length; i++) {
				var chr = this.charactersTyped.charAt(i);
				if (this.typingListeners.hasOwnProperty(chr)) {
					var listeners = this.typingListeners[chr].slice(0);
					for (var j = 0, lenJ = listeners.length; j < lenJ; j++) {
						// Hoping that listeners understand that the view might be in an awkward state
						try {
							listeners[j]();
						} catch (e) {
A
Alex Dima 已提交
359
							onUnexpectedError(e);
E
Erich Gamma 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
						}
					}
				}
			}

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

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


			if (somethingChanged) {
				if (!hasExecutedCommands && !isCursorUndo) {
					this.cursorUndoStack.push(prevCursorsState);
				}
				if (this.cursorUndoStack.length > 50) {
					this.cursorUndoStack = this.cursorUndoStack.splice(0, this.cursorUndoStack.length - 50);
				}
				this.emitCursorPositionChanged(eventSource, cursorPositionChangeReason);

				if (shouldReveal) {
395
					this.revealRange(shouldRevealTarget, shouldRevealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, shouldRevealHorizontal);
E
Erich Gamma 已提交
396 397 398
				}
				this.emitCursorSelectionChanged(eventSource, cursorPositionChangeReason);
			}
399

E
Erich Gamma 已提交
400
		} catch (err) {
A
Alex Dima 已提交
401
			onUnexpectedError(err);
E
Erich Gamma 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414
		}

		this._isHandling = false;

		return handled;
	}

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

A
Alex Dima 已提交
415 416 417
		this._columnSelectToLineNumber = ctx.setColumnSelectToLineNumber;
		this._columnSelectToVisualColumn = ctx.setColumnSelectToVisualColumn;

A
Alex Dima 已提交
418
		ctx.hasExecutedCommands = this._internalExecuteCommands(ctx.executeCommands, ctx.isAutoWhitespaceCommand) || ctx.hasExecutedCommands;
E
Erich Gamma 已提交
419 420 421 422 423 424 425 426
		ctx.executeCommands = [];

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

J
Johannes Rieken 已提交
427
	private _interpretCommandResult(cursorState: Selection[]): boolean {
E
Erich Gamma 已提交
428 429 430 431 432 433 434 435
		if (!cursorState) {
			return false;
		}

		this.cursors.setSelections(cursorState);
		return true;
	}

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

J
Johannes Rieken 已提交
442
		var addEditOperation = (selection: Range, text: string) => {
E
Erich Gamma 已提交
443 444 445 446 447 448 449 450 451 452 453
			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,
454 455
				forceMoveMarkers: false,
				isAutoWhitespaceEdit: isAutoWhitespaceCommand
E
Erich Gamma 已提交
456 457 458 459
			});
		};

		var hadTrackedRange = false;
J
Johannes Rieken 已提交
460 461 462
		var trackSelection = (selection: Selection, trackPreviousOnEmpty?: boolean) => {
			var selectionMarkerStickToPreviousCharacter: boolean,
				positionMarkerStickToPreviousCharacter: boolean;
E
Erich Gamma 已提交
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

			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 {
480
				if (selection.getDirection() === SelectionDirection.LTR) {
E
Erich Gamma 已提交
481 482 483 484 485 486 487 488 489
					selectionMarkerStickToPreviousCharacter = false;
					positionMarkerStickToPreviousCharacter = true;
				} else {
					selectionMarkerStickToPreviousCharacter = true;
					positionMarkerStickToPreviousCharacter = false;
				}
			}

			var l = ctx.selectionStartMarkers.length;
A
Alex Dima 已提交
490 491
			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 已提交
492 493 494
			return l.toString();
		};

J
Johannes Rieken 已提交
495
		var editOperationBuilder: editorCommon.IEditOperationBuilder = {
E
Erich Gamma 已提交
496 497 498 499 500 501 502 503
			addEditOperation: addEditOperation,
			trackSelection: trackSelection
		};

		try {
			command.getEditOperations(this.model, editOperationBuilder);
		} catch (e) {
			e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command.");
A
Alex Dima 已提交
504
			onUnexpectedError(e);
E
Erich Gamma 已提交
505 506 507 508 509 510 511 512 513 514 515 516
			return {
				operations: [],
				hadTrackedRange: false
			};
		}

		return {
			operations: operations,
			hadTrackedRange: hadTrackedRange
		};
	}

J
Johannes Rieken 已提交
517
	private _getEditOperations(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): ICommandsData {
E
Erich Gamma 已提交
518
		var oneResult: ICommandData;
A
Alex Dima 已提交
519
		var operations: editorCommon.IIdentifiedSingleEditOperation[] = [];
E
Erich Gamma 已提交
520 521 522 523 524
		var hadTrackedRanges: boolean[] = [];
		var anyoneHadTrackedRange: boolean;

		for (var i = 0; i < commands.length; i++) {
			if (commands[i]) {
525
				oneResult = this._getEditOperationsFromCommand(ctx, i, commands[i], isAutoWhitespaceCommand[i]);
E
Erich Gamma 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539
				operations = operations.concat(oneResult.operations);
				hadTrackedRanges[i] = oneResult.hadTrackedRange;
				anyoneHadTrackedRange = anyoneHadTrackedRange || hadTrackedRanges[i];
			} else {
				hadTrackedRanges[i] = false;
			}
		}
		return {
			operations: operations,
			hadTrackedRanges: hadTrackedRanges,
			anyoneHadTrackedRange: anyoneHadTrackedRange
		};
	}

A
Alex Dima 已提交
540
	private _getLoserCursorMap(operations: editorCommon.IIdentifiedSingleEditOperation[]): { [index: string]: boolean; } {
E
Erich Gamma 已提交
541 542 543 544
		// This is destructive on the array
		operations = operations.slice(0);

		// Sort operations with last one first
J
Johannes Rieken 已提交
545
		operations.sort((a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation): number => {
E
Erich Gamma 已提交
546 547 548 549 550
			// Note the minus!
			return -(Range.compareRangesUsingEnds(a.range, b.range));
		});

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

A
Alex Dima 已提交
553 554
		var previousOp: editorCommon.IIdentifiedSingleEditOperation;
		var currentOp: editorCommon.IIdentifiedSingleEditOperation;
E
Erich Gamma 已提交
555 556 557 558 559 560
		var loserMajor: number;

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

561
			if (previousOp.range.getStartPosition().isBefore(currentOp.range.getEndPosition())) {
E
Erich Gamma 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

				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 已提交
591
	private _collapseDeleteCommands(rawCmds: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): boolean {
E
Erich Gamma 已提交
592
		if (rawCmds.length === 1) {
J
Johannes Rieken 已提交
593
			return;
E
Erich Gamma 已提交
594 595 596 597 598 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 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
		}

		// Merge adjacent delete commands
		var allAreDeleteCommands = rawCmds.every((command) => {
			if (!(command instanceof ReplaceCommand)) {
				return false;
			}
			var replCmd = (<ReplaceCommand>command);
			if (replCmd.getText().length > 0) {
				return false;
			}
			return true;
		});

		if (!allAreDeleteCommands) {
			return;
		}

		var commands = <ReplaceCommand[]>rawCmds;
		var cursors = commands.map((cmd, i) => {
			return {
				range: commands[i].getRange(),
				order: i
			};
		});

		cursors.sort((a, b) => {
			return Range.compareRangesUsingStarts(a.range, b.range);
		});

		var previousCursor = cursors[0];
		for (var i = 1; i < cursors.length; i++) {
			if (previousCursor.range.endLineNumber === cursors[i].range.startLineNumber && previousCursor.range.endColumn === cursors[i].range.startColumn) {
				// Merge ranges
				var mergedRange = new Range(
					previousCursor.range.startLineNumber,
					previousCursor.range.startColumn,
					cursors[i].range.endLineNumber,
					cursors[i].range.endColumn
				);

				previousCursor.range = mergedRange;

				commands[cursors[i].order].setRange(mergedRange);
				commands[previousCursor.order].setRange(mergedRange);
			} else {
				// Push previous cursor
				previousCursor = cursors[i];
			}
		}
	}

A
Alex Dima 已提交
646
	private _internalExecuteCommands(commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): boolean {
J
Johannes Rieken 已提交
647
		var ctx: IExecContext = {
E
Erich Gamma 已提交
648 649 650 651
			selectionStartMarkers: [],
			positionMarkers: []
		};

A
Alex Dima 已提交
652
		this._collapseDeleteCommands(commands, isAutoWhitespaceCommand);
E
Erich Gamma 已提交
653

A
Alex Dima 已提交
654
		var r = this._innerExecuteCommands(ctx, commands, isAutoWhitespaceCommand);
E
Erich Gamma 已提交
655 656 657 658 659 660 661
		for (var i = 0; i < ctx.selectionStartMarkers.length; i++) {
			this.model._removeMarker(ctx.selectionStartMarkers[i]);
			this.model._removeMarker(ctx.positionMarkers[i]);
		}
		return r;
	}

A
Alex Dima 已提交
662
	private _arrayIsEmpty(commands: editorCommon.ICommand[]): boolean {
J
Johannes Rieken 已提交
663 664
		var i: number,
			len: number;
E
Erich Gamma 已提交
665 666 667 668 669 670 671 672 673 674

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

		return true;
	}

A
Alex Dima 已提交
675
	private _innerExecuteCommands(ctx: IExecContext, commands: editorCommon.ICommand[], isAutoWhitespaceCommand: boolean[]): boolean {
E
Erich Gamma 已提交
676 677 678 679 680 681 682 683 684 685 686

		if (this.configuration.editor.readOnly) {
			return false;
		}

		if (this._arrayIsEmpty(commands)) {
			return false;
		}

		var selectionsBefore = this.cursors.getSelections();

687
		var commandsData = this._getEditOperations(ctx, commands, isAutoWhitespaceCommand);
E
Erich Gamma 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
		if (commandsData.operations.length === 0 && !commandsData.anyoneHadTrackedRange) {
			return false;
		}

		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
				return false;
			}
		}

		var loserCursorsMap = this._getLoserCursorMap(rawOperations);
		if (loserCursorsMap.hasOwnProperty('0')) {
			// These commands are very messed up
			console.warn('Ignoring commands');
			return false;
		}

		// Remove operations belonging to losing cursors
A
Alex Dima 已提交
713
		var filteredOperations: editorCommon.IIdentifiedSingleEditOperation[] = [];
E
Erich Gamma 已提交
714 715 716 717 718 719
		for (var i = 0; i < rawOperations.length; i++) {
			if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
				filteredOperations.push(rawOperations[i]);
			}
		}

J
Johannes Rieken 已提交
720 721
		var selectionsAfter = this.model.pushEditOperations(selectionsBefore, filteredOperations, (inverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[]): Selection[] => {
			var groupedInverseEditOperations: editorCommon.IIdentifiedSingleEditOperation[][] = [];
E
Erich Gamma 已提交
722 723 724 725 726
			for (var i = 0; i < selectionsBefore.length; i++) {
				groupedInverseEditOperations[i] = [];
			}
			for (var i = 0; i < inverseEditOperations.length; i++) {
				var op = inverseEditOperations[i];
727 728 729 730
				if (!op.identifier) {
					// perhaps auto whitespace trim edits
					continue;
				}
E
Erich Gamma 已提交
731 732
				groupedInverseEditOperations[op.identifier.major].push(op);
			}
J
Johannes Rieken 已提交
733
			var minorBasedSorter = (a: editorCommon.IIdentifiedSingleEditOperation, b: editorCommon.IIdentifiedSingleEditOperation) => {
E
Erich Gamma 已提交
734 735
				return a.identifier.minor - b.identifier.minor;
			};
736
			var cursorSelections: Selection[] = [];
E
Erich Gamma 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
			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 已提交
769
		losingCursors.sort((a: number, b: number): number => {
E
Erich Gamma 已提交
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
			return b - a;
		});

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

		return this._interpretCommandResult(selectionsAfter);
	}


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

J
Johannes Rieken 已提交
785
	private emitCursorPositionChanged(source: string, reason: editorCommon.CursorChangeReason): void {
E
Erich Gamma 已提交
786 787 788 789 790 791 792 793
		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 已提交
794
		var isInEditableRange: boolean = true;
E
Erich Gamma 已提交
795 796 797 798 799 800
		if (this.model.hasEditableRange()) {
			var editableRange = this.model.getEditableRange();
			if (!editableRange.containsPosition(primaryPosition)) {
				isInEditableRange = false;
			}
		}
J
Johannes Rieken 已提交
801
		var e: editorCommon.ICursorPositionChangedEvent = {
E
Erich Gamma 已提交
802 803 804 805 806 807 808 809
			position: primaryPosition,
			viewPosition: primaryViewPosition,
			secondaryPositions: secondaryPositions,
			secondaryViewPositions: secondaryViewPositions,
			reason: reason,
			source: source,
			isInEditableRange: isInEditableRange
		};
A
Alex Dima 已提交
810
		this.emit(editorCommon.EventType.CursorPositionChanged, e);
E
Erich Gamma 已提交
811 812
	}

J
Johannes Rieken 已提交
813
	private emitCursorSelectionChanged(source: string, reason: editorCommon.CursorChangeReason): void {
814 815 816
		let selections = this.cursors.getSelections();
		let primarySelection = selections[0];
		let secondarySelections = selections.slice(1);
E
Erich Gamma 已提交
817

818 819 820 821
		let viewSelections = this.cursors.getViewSelections();
		let primaryViewSelection = viewSelections[0];
		let secondaryViewSelections = viewSelections.slice(1);

J
Johannes Rieken 已提交
822
		let e: editorCommon.ICursorSelectionChangedEvent = {
E
Erich Gamma 已提交
823
			selection: primarySelection,
824
			viewSelection: primaryViewSelection,
E
Erich Gamma 已提交
825
			secondarySelections: secondarySelections,
826
			secondaryViewSelections: secondaryViewSelections,
E
Erich Gamma 已提交
827 828 829
			source: source,
			reason: reason
		};
A
Alex Dima 已提交
830
		this.emit(editorCommon.EventType.CursorSelectionChanged, e);
E
Erich Gamma 已提交
831 832
	}

833
	private emitCursorScrollRequest(deltaLines: number, revealCursor: boolean): void {
J
Johannes Rieken 已提交
834
		var e: editorCommon.ICursorScrollRequestEvent = {
835 836
			deltaLines,
			revealCursor
837
		};
A
Alex Dima 已提交
838
		this.emit(editorCommon.EventType.CursorScrollRequest, e);
839 840
	}

841
	private revealRange(revealTarget: RevealTarget, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
E
Erich Gamma 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
		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);
871
		this.emitCursorRevealRange(range, viewRange, verticalType, revealHorizontal, false);
872 873
	}

874
	private emitCursorRevealRange(range: Range, viewRange: Range, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean, revealCursor: boolean) {
J
Johannes Rieken 已提交
875
		var e: editorCommon.ICursorRevealRangeEvent = {
E
Erich Gamma 已提交
876 877 878
			range: range,
			viewRange: viewRange,
			verticalType: verticalType,
879 880
			revealHorizontal: revealHorizontal,
			revealCursor: revealCursor
E
Erich Gamma 已提交
881
		};
A
Alex Dima 已提交
882
		this.emit(editorCommon.EventType.CursorRevealRange, e);
E
Erich Gamma 已提交
883 884 885 886 887
	}

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

J
Johannes Rieken 已提交
888
	public trigger(source: string, handlerId: string, payload: any): void {
A
Alex Dima 已提交
889 890 891 892 893 894 895
		if (!this._handlers.hasOwnProperty(handlerId)) {
			return;
		}
		let handler = this._handlers[handlerId];
		this._onHandler(handlerId, handler, source, payload);
	}

E
Erich Gamma 已提交
896
	private _registerHandlers(): void {
A
Alex Dima 已提交
897
		let H = editorCommon.Handler;
E
Erich Gamma 已提交
898

J
Johannes Rieken 已提交
899
		this._handlers[H.JumpToBracket] = (ctx) => this._jumpToBracket(ctx);
E
Erich Gamma 已提交
900

J
Johannes Rieken 已提交
901 902 903 904 905 906 907 908
		this._handlers[H.CursorMove] = (ctx) => this._cursorMove(ctx);
		this._handlers[H.MoveTo] = (ctx) => this._moveTo(false, ctx);
		this._handlers[H.MoveToSelect] = (ctx) => this._moveTo(true, ctx);
		this._handlers[H.ColumnSelect] = (ctx) => this._columnSelectMouse(ctx);
		this._handlers[H.AddCursorUp] = (ctx) => this._addCursorUp(ctx);
		this._handlers[H.AddCursorDown] = (ctx) => this._addCursorDown(ctx);
		this._handlers[H.CreateCursor] = (ctx) => this._createCursor(ctx);
		this._handlers[H.LastCursorMoveToSelect] = (ctx) => this._lastCursorMoveTo(ctx);
909 910


J
Johannes Rieken 已提交
911 912
		this._handlers[H.CursorLeft] = (ctx) => this._moveLeft(false, ctx);
		this._handlers[H.CursorLeftSelect] = (ctx) => this._moveLeft(true, ctx);
E
Erich Gamma 已提交
913

J
Johannes Rieken 已提交
914 915 916
		this._handlers[H.CursorWordLeft] = (ctx) => this._moveWordLeft(false, WordNavigationType.WordStart, ctx);
		this._handlers[H.CursorWordStartLeft] = (ctx) => this._moveWordLeft(false, WordNavigationType.WordStart, ctx);
		this._handlers[H.CursorWordEndLeft] = (ctx) => this._moveWordLeft(false, WordNavigationType.WordEnd, ctx);
917

J
Johannes Rieken 已提交
918 919 920
		this._handlers[H.CursorWordLeftSelect] = (ctx) => this._moveWordLeft(true, WordNavigationType.WordStart, ctx);
		this._handlers[H.CursorWordStartLeftSelect] = (ctx) => this._moveWordLeft(true, WordNavigationType.WordStart, ctx);
		this._handlers[H.CursorWordEndLeftSelect] = (ctx) => this._moveWordLeft(true, WordNavigationType.WordEnd, ctx);
921

J
Johannes Rieken 已提交
922 923
		this._handlers[H.CursorRight] = (ctx) => this._moveRight(false, ctx);
		this._handlers[H.CursorRightSelect] = (ctx) => this._moveRight(true, ctx);
E
Erich Gamma 已提交
924

J
Johannes Rieken 已提交
925 926 927
		this._handlers[H.CursorWordRight] = (ctx) => this._moveWordRight(false, WordNavigationType.WordEnd, ctx);
		this._handlers[H.CursorWordStartRight] = (ctx) => this._moveWordRight(false, WordNavigationType.WordStart, ctx);
		this._handlers[H.CursorWordEndRight] = (ctx) => this._moveWordRight(false, WordNavigationType.WordEnd, ctx);
E
Erich Gamma 已提交
928

J
Johannes Rieken 已提交
929 930 931
		this._handlers[H.CursorWordRightSelect] = (ctx) => this._moveWordRight(true, WordNavigationType.WordEnd, ctx);
		this._handlers[H.CursorWordStartRightSelect] = (ctx) => this._moveWordRight(true, WordNavigationType.WordStart, ctx);
		this._handlers[H.CursorWordEndRightSelect] = (ctx) => this._moveWordRight(true, WordNavigationType.WordEnd, ctx);
E
Erich Gamma 已提交
932

J
Johannes Rieken 已提交
933 934 935 936
		this._handlers[H.CursorUp] = (ctx) => this._moveUp(false, false, ctx);
		this._handlers[H.CursorUpSelect] = (ctx) => this._moveUp(true, false, ctx);
		this._handlers[H.CursorDown] = (ctx) => this._moveDown(false, false, ctx);
		this._handlers[H.CursorDownSelect] = (ctx) => this._moveDown(true, false, ctx);
E
Erich Gamma 已提交
937

J
Johannes Rieken 已提交
938 939 940 941
		this._handlers[H.CursorPageUp] = (ctx) => this._moveUp(false, true, ctx);
		this._handlers[H.CursorPageUpSelect] = (ctx) => this._moveUp(true, true, ctx);
		this._handlers[H.CursorPageDown] = (ctx) => this._moveDown(false, true, ctx);
		this._handlers[H.CursorPageDownSelect] = (ctx) => this._moveDown(true, true, ctx);
E
Erich Gamma 已提交
942

J
Johannes Rieken 已提交
943 944
		this._handlers[H.CursorHome] = (ctx) => this._moveToBeginningOfLine(false, ctx);
		this._handlers[H.CursorHomeSelect] = (ctx) => this._moveToBeginningOfLine(true, ctx);
E
Erich Gamma 已提交
945

J
Johannes Rieken 已提交
946 947
		this._handlers[H.CursorEnd] = (ctx) => this._moveToEndOfLine(false, ctx);
		this._handlers[H.CursorEndSelect] = (ctx) => this._moveToEndOfLine(true, ctx);
A
Alex Dima 已提交
948

J
Johannes Rieken 已提交
949 950 951 952
		this._handlers[H.CursorTop] = (ctx) => this._moveToBeginningOfBuffer(false, ctx);
		this._handlers[H.CursorTopSelect] = (ctx) => this._moveToBeginningOfBuffer(true, ctx);
		this._handlers[H.CursorBottom] = (ctx) => this._moveToEndOfBuffer(false, ctx);
		this._handlers[H.CursorBottomSelect] = (ctx) => this._moveToEndOfBuffer(true, ctx);
E
Erich Gamma 已提交
953

J
Johannes Rieken 已提交
954 955 956 957 958 959
		this._handlers[H.CursorColumnSelectLeft] = (ctx) => this._columnSelectLeft(ctx);
		this._handlers[H.CursorColumnSelectRight] = (ctx) => this._columnSelectRight(ctx);
		this._handlers[H.CursorColumnSelectUp] = (ctx) => this._columnSelectUp(false, ctx);
		this._handlers[H.CursorColumnSelectPageUp] = (ctx) => this._columnSelectUp(true, ctx);
		this._handlers[H.CursorColumnSelectDown] = (ctx) => this._columnSelectDown(false, ctx);
		this._handlers[H.CursorColumnSelectPageDown] = (ctx) => this._columnSelectDown(true, ctx);
E
Erich Gamma 已提交
960

J
Johannes Rieken 已提交
961
		this._handlers[H.SelectAll] = (ctx) => this._selectAll(ctx);
E
Erich Gamma 已提交
962

J
Johannes Rieken 已提交
963 964 965 966
		this._handlers[H.LineSelect] = (ctx) => this._line(false, ctx);
		this._handlers[H.LineSelectDrag] = (ctx) => this._line(true, ctx);
		this._handlers[H.LastCursorLineSelect] = (ctx) => this._lastCursorLine(false, ctx);
		this._handlers[H.LastCursorLineSelectDrag] = (ctx) => this._lastCursorLine(true, ctx);
E
Erich Gamma 已提交
967

J
Johannes Rieken 已提交
968 969 970
		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 已提交
971

J
Johannes Rieken 已提交
972 973 974 975 976
		this._handlers[H.WordSelect] = (ctx) => this._word(false, ctx);
		this._handlers[H.WordSelectDrag] = (ctx) => this._word(true, ctx);
		this._handlers[H.LastCursorWordSelect] = (ctx) => this._lastCursorWord(ctx);
		this._handlers[H.CancelSelection] = (ctx) => this._cancelSelection(ctx);
		this._handlers[H.RemoveSecondaryCursors] = (ctx) => this._removeSecondaryCursors(ctx);
977

J
Johannes Rieken 已提交
978 979 980 981 982 983
		this._handlers[H.Type] = (ctx) => this._type(ctx);
		this._handlers[H.ReplacePreviousChar] = (ctx) => this._replacePreviousChar(ctx);
		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);
984

J
Johannes Rieken 已提交
985
		this._handlers[H.EditorScroll] = (ctx) => this._editorScroll(ctx);
986

J
Johannes Rieken 已提交
987 988 989 990
		this._handlers[H.ScrollLineUp] = (ctx) => this._scrollUp(false, ctx);
		this._handlers[H.ScrollLineDown] = (ctx) => this._scrollDown(false, ctx);
		this._handlers[H.ScrollPageUp] = (ctx) => this._scrollUp(true, ctx);
		this._handlers[H.ScrollPageDown] = (ctx) => this._scrollDown(true, ctx);
991

J
Johannes Rieken 已提交
992
		this._handlers[H.DeleteLeft] = (ctx) => this._deleteLeft(ctx);
993

J
Johannes Rieken 已提交
994 995 996
		this._handlers[H.DeleteWordLeft] = (ctx) => this._deleteWordLeft(true, WordNavigationType.WordStart, ctx);
		this._handlers[H.DeleteWordStartLeft] = (ctx) => this._deleteWordLeft(false, WordNavigationType.WordStart, ctx);
		this._handlers[H.DeleteWordEndLeft] = (ctx) => this._deleteWordLeft(false, WordNavigationType.WordEnd, ctx);
997

J
Johannes Rieken 已提交
998
		this._handlers[H.DeleteRight] = (ctx) => this._deleteRight(ctx);
E
Erich Gamma 已提交
999

J
Johannes Rieken 已提交
1000 1001 1002
		this._handlers[H.DeleteWordRight] = (ctx) => this._deleteWordRight(true, WordNavigationType.WordEnd, ctx);
		this._handlers[H.DeleteWordStartRight] = (ctx) => this._deleteWordRight(false, WordNavigationType.WordStart, ctx);
		this._handlers[H.DeleteWordEndRight] = (ctx) => this._deleteWordRight(false, WordNavigationType.WordEnd, ctx);
1003

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

J
Johannes Rieken 已提交
1006
		this._handlers[H.ExpandLineSelection] = (ctx) => this._expandLineSelection(ctx);
E
Erich Gamma 已提交
1007

J
Johannes Rieken 已提交
1008 1009 1010
		this._handlers[H.Undo] = (ctx) => this._undo(ctx);
		this._handlers[H.CursorUndo] = (ctx) => this._cursorUndo(ctx);
		this._handlers[H.Redo] = (ctx) => this._redo(ctx);
E
Erich Gamma 已提交
1011

J
Johannes Rieken 已提交
1012 1013
		this._handlers[H.ExecuteCommand] = (ctx) => this._externalExecuteCommand(ctx);
		this._handlers[H.ExecuteCommands] = (ctx) => this._externalExecuteCommands(ctx);
1014

J
Johannes Rieken 已提交
1015
		this._handlers[H.RevealLine] = (ctx) => this._revealLine(ctx);
E
Erich Gamma 已提交
1016 1017
	}

1018 1019 1020 1021
	private _invokeForAllSorted(ctx: IMultipleCursorOperationContext, callable: (cursorIndex: number, cursor: OneCursor, ctx: IOneCursorOperationContext) => boolean, pushStackElementBefore: boolean = true, pushStackElementAfter: boolean = true): boolean {
		return this._doInvokeForAll(ctx, true, callable, pushStackElementBefore, pushStackElementAfter);
	}

E
Erich Gamma 已提交
1022
	private _invokeForAll(ctx: IMultipleCursorOperationContext, callable: (cursorIndex: number, cursor: OneCursor, ctx: IOneCursorOperationContext) => boolean, pushStackElementBefore: boolean = true, pushStackElementAfter: boolean = true): boolean {
1023 1024 1025 1026 1027 1028 1029 1030 1031
		return this._doInvokeForAll(ctx, false, callable, pushStackElementBefore, pushStackElementAfter);
	}

	private _doInvokeForAll(ctx: IMultipleCursorOperationContext, sorted: boolean, callable: (cursorIndex: number, cursor: OneCursor, ctx: IOneCursorOperationContext) => boolean, pushStackElementBefore: boolean = true, pushStackElementAfter: boolean = true): boolean {
		let result = false;
		let cursors = this.cursors.getAll();

		if (sorted) {
			cursors = cursors.sort((a, b) => {
A
Alex Dima 已提交
1032
				return Range.compareRangesUsingStarts(a.modelState.selection, b.modelState.selection);
1033 1034 1035
			});
		}

J
Johannes Rieken 已提交
1036
		let context: IOneCursorOperationContext;
E
Erich Gamma 已提交
1037 1038 1039 1040

		ctx.shouldPushStackElementBefore = pushStackElementBefore;
		ctx.shouldPushStackElementAfter = pushStackElementAfter;

1041
		for (let i = 0; i < cursors.length; i++) {
E
Erich Gamma 已提交
1042
			context = {
A
Alex Dima 已提交
1043
				cursorPositionChangeReason: editorCommon.CursorChangeReason.NotSet,
E
Erich Gamma 已提交
1044 1045 1046 1047
				shouldReveal: true,
				shouldRevealVerticalInCenter: false,
				shouldRevealHorizontal: true,
				executeCommand: null,
1048
				isAutoWhitespaceCommand: false,
E
Erich Gamma 已提交
1049
				shouldPushStackElementBefore: false,
1050
				shouldPushStackElementAfter: false
E
Erich Gamma 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
			};

			result = callable(i, cursors[i], context) || result;

			if (i === 0) {
				ctx.cursorPositionChangeReason = context.cursorPositionChangeReason;
				ctx.shouldRevealHorizontal = context.shouldRevealHorizontal;
				ctx.shouldReveal = context.shouldReveal;
				ctx.shouldRevealVerticalInCenter = context.shouldRevealVerticalInCenter;
			}

			ctx.shouldPushStackElementBefore = ctx.shouldPushStackElementBefore || context.shouldPushStackElementBefore;
			ctx.shouldPushStackElementAfter = ctx.shouldPushStackElementAfter || context.shouldPushStackElementAfter;

			ctx.executeCommands[i] = context.executeCommand;
1066
			ctx.isAutoWhitespaceCommand[i] = context.isAutoWhitespaceCommand;
E
Erich Gamma 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
		}

		return result;
	}

	private _jumpToBracket(ctx: IMultipleCursorOperationContext): boolean {
		this.cursors.killSecondaryCursors();
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.jumpToBracket(oneCursor, oneCtx));
	}

J
Johannes Rieken 已提交
1077
	private _moveTo(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1078 1079 1080 1081
		this.cursors.killSecondaryCursors();
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveTo(oneCursor, inSelectionMode, ctx.eventData.position, ctx.eventData.viewPosition, ctx.eventSource, oneCtx));
	}

S
Sandeep Somavarapu 已提交
1082
	private _cursorMove(ctx: IMultipleCursorOperationContext): boolean {
1083
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.move(oneCursor, ctx.eventData, ctx.eventSource, oneCtx));
1084 1085
	}

A
Alex Dima 已提交
1086 1087 1088 1089
	private _columnSelectToLineNumber: number = 0;
	private _getColumnSelectToLineNumber(): number {
		if (!this._columnSelectToLineNumber) {
			let primaryCursor = this.cursors.getAll()[0];
A
Alex Dima 已提交
1090
			let primaryPos = primaryCursor.viewState.position;
A
Alex Dima 已提交
1091
			return primaryPos.lineNumber;
A
Alex Dima 已提交
1092
		}
A
Alex Dima 已提交
1093 1094
		return this._columnSelectToLineNumber;
	}
A
Alex Dima 已提交
1095

A
Alex Dima 已提交
1096 1097 1098 1099
	private _columnSelectToVisualColumn: number = 0;
	private _getColumnSelectToVisualColumn(): number {
		if (!this._columnSelectToVisualColumn) {
			let primaryCursor = this.cursors.getAll()[0];
A
Alex Dima 已提交
1100
			let primaryPos = primaryCursor.viewState.position;
A
Alex Dima 已提交
1101
			return CursorColumns.visibleColumnFromColumn2(primaryCursor.config, primaryCursor.viewModel, primaryPos);
A
Alex Dima 已提交
1102 1103 1104 1105 1106
		}
		return this._columnSelectToVisualColumn;
	}

	private _columnSelectMouse(ctx: IMultipleCursorOperationContext): boolean {
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
		let primary = this.cursors.getAll()[0];

		// validate `eventData`
		let validatedPosition = primary.model.validatePosition(ctx.eventData.position);
		let validatedViewPosition: Position;
		if (ctx.eventData.viewPosition) {
			validatedViewPosition = primary.validateViewPosition(ctx.eventData.viewPosition.lineNumber, ctx.eventData.viewPosition.column, validatedPosition);
		} else {
			validatedViewPosition = primary.convertModelPositionToViewPosition(validatedPosition.lineNumber, validatedPosition.column);
		}

		let result = ColumnSelection.columnSelect(primary.config, primary.viewModel, primary.viewState.selection.getStartPosition(), validatedViewPosition.lineNumber, ctx.eventData.mouseColumn - 1);
		let selections = result.viewSelections.map(viewSel => primary.convertViewSelectionToModelSelection(viewSel));
A
Alex Dima 已提交
1120 1121 1122 1123 1124 1125

		ctx.shouldRevealTarget = (result.reversed ? RevealTarget.TopMost : RevealTarget.BottomMost);
		ctx.shouldReveal = true;
		ctx.setColumnSelectToLineNumber = result.toLineNumber;
		ctx.setColumnSelectToVisualColumn = result.toVisualColumn;

1126
		this.cursors.setSelections(selections, result.viewSelections);
A
Alex Dima 已提交
1127 1128 1129
		return true;
	}

J
Johannes Rieken 已提交
1130
	private _columnSelectOp(ctx: IMultipleCursorOperationContext, op: (cursor: OneCursor, toViewLineNumber: number, toViewVisualColumn: number) => IColumnSelectResult): boolean {
A
Alex Dima 已提交
1131
		let primary = this.cursors.getAll()[0];
A
Alex Dima 已提交
1132
		let result = op(primary, this._getColumnSelectToLineNumber(), this._getColumnSelectToVisualColumn());
1133
		let selections = result.viewSelections.map(viewSel => primary.convertViewSelectionToModelSelection(viewSel));
A
Alex Dima 已提交
1134 1135 1136

		ctx.shouldRevealTarget = (result.reversed ? RevealTarget.TopMost : RevealTarget.BottomMost);
		ctx.shouldReveal = true;
A
Alex Dima 已提交
1137 1138
		ctx.setColumnSelectToLineNumber = result.toLineNumber;
		ctx.setColumnSelectToVisualColumn = result.toVisualColumn;
A
Alex Dima 已提交
1139

1140
		this.cursors.setSelections(selections, result.viewSelections);
A
Alex Dima 已提交
1141 1142 1143
		return true;
	}

A
Alex Dima 已提交
1144
	private _columnSelectLeft(ctx: IMultipleCursorOperationContext): boolean {
1145
		return this._columnSelectOp(ctx, (cursor, toViewLineNumber, toViewVisualColumn) => ColumnSelection.columnSelectLeft(cursor.config, cursor.viewModel, cursor.viewState, toViewLineNumber, toViewVisualColumn));
A
Alex Dima 已提交
1146 1147 1148
	}

	private _columnSelectRight(ctx: IMultipleCursorOperationContext): boolean {
1149
		return this._columnSelectOp(ctx, (cursor, toViewLineNumber, toViewVisualColumn) => ColumnSelection.columnSelectRight(cursor.config, cursor.viewModel, cursor.viewState, toViewLineNumber, toViewVisualColumn));
A
Alex Dima 已提交
1150 1151
	}

J
Johannes Rieken 已提交
1152
	private _columnSelectUp(isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
1153
		return this._columnSelectOp(ctx, (cursor, toViewLineNumber, toViewVisualColumn) => ColumnSelection.columnSelectUp(cursor.config, cursor.viewModel, cursor.viewState, isPaged, toViewLineNumber, toViewVisualColumn));
A
Alex Dima 已提交
1154 1155
	}

J
Johannes Rieken 已提交
1156
	private _columnSelectDown(isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
1157
		return this._columnSelectOp(ctx, (cursor, toViewLineNumber, toViewVisualColumn) => ColumnSelection.columnSelectDown(cursor.config, cursor.viewModel, cursor.viewState, isPaged, toViewLineNumber, toViewVisualColumn));
A
Alex Dima 已提交
1158 1159
	}

E
Erich Gamma 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
	private _createCursor(ctx: IMultipleCursorOperationContext): boolean {
		if (this.configuration.editor.readOnly || this.model.hasEditableRange()) {
			return false;
		}

		this.cursors.addSecondaryCursor({
			selectionStartLineNumber: 1,
			selectionStartColumn: 1,
			positionLineNumber: 1,
			positionColumn: 1
		});

		// Manually move to get events
		var lastAddedCursor = this.cursors.getLastAddedCursor();
		this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			if (oneCursor === lastAddedCursor) {
				if (ctx.eventData.wholeLine) {
					return OneCursorOp.line(oneCursor, false, ctx.eventData.position, ctx.eventData.viewPosition, oneCtx);
				} else {
					return OneCursorOp.moveTo(oneCursor, false, ctx.eventData.position, ctx.eventData.viewPosition, ctx.eventSource, oneCtx);
				}
			}
			return false;
		});

		ctx.shouldReveal = false;
		ctx.shouldRevealHorizontal = false;

		return true;
	}

	private _lastCursorMoveTo(ctx: IMultipleCursorOperationContext): boolean {
		if (this.configuration.editor.readOnly || this.model.hasEditableRange()) {
			return false;
		}

		var lastAddedCursor = this.cursors.getLastAddedCursor();
		this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			if (oneCursor === lastAddedCursor) {
J
Johannes Rieken 已提交
1199
				return OneCursorOp.moveTo(oneCursor, true, ctx.eventData.position, ctx.eventData.viewPosition, ctx.eventSource, oneCtx);
E
Erich Gamma 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
			}
			return false;
		});

		ctx.shouldReveal = false;
		ctx.shouldRevealHorizontal = false;

		return true;
	}

	private _addCursorUp(ctx: IMultipleCursorOperationContext): boolean {
		if (this.configuration.editor.readOnly) {
			return false;
		}

		var originalCnt = this.cursors.getSelections().length;
		this.cursors.duplicateCursors();
		ctx.shouldRevealTarget = RevealTarget.TopMost;

		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			if (cursorIndex >= originalCnt) {
				return OneCursorOp.translateUp(oneCursor, oneCtx);
			}
			return false;
		});
	}

	private _addCursorDown(ctx: IMultipleCursorOperationContext): boolean {
		if (this.configuration.editor.readOnly) {
			return false;
		}

		var originalCnt = this.cursors.getSelections().length;
		this.cursors.duplicateCursors();
		ctx.shouldRevealTarget = RevealTarget.BottomMost;

		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			if (cursorIndex >= originalCnt) {
				return OneCursorOp.translateDown(oneCursor, oneCtx);
			}
			return false;
		});
	}

J
Johannes Rieken 已提交
1244 1245 1246
	private _moveLeft(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
		ctx.eventData = ctx.eventData || {};
		ctx.eventData.to = editorCommon.CursorMovePosition.Left;
1247 1248 1249
		ctx.eventData.select = inSelectionMode;

		return this._cursorMove(ctx);
E
Erich Gamma 已提交
1250 1251
	}

J
Johannes Rieken 已提交
1252
	private _moveWordLeft(inSelectionMode: boolean, wordNavigationType: WordNavigationType, ctx: IMultipleCursorOperationContext): boolean {
1253
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveWordLeft(oneCursor, inSelectionMode, wordNavigationType, oneCtx));
E
Erich Gamma 已提交
1254 1255
	}

1256
	private _moveRight(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
J
Johannes Rieken 已提交
1257 1258
		ctx.eventData = ctx.eventData || {};
		ctx.eventData.to = editorCommon.CursorMovePosition.Right;
1259 1260 1261
		ctx.eventData.select = inSelectionMode;

		return this._cursorMove(ctx);
E
Erich Gamma 已提交
1262 1263
	}

J
Johannes Rieken 已提交
1264
	private _moveWordRight(inSelectionMode: boolean, wordNavigationType: WordNavigationType, ctx: IMultipleCursorOperationContext): boolean {
1265
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveWordRight(oneCursor, inSelectionMode, wordNavigationType, oneCtx));
E
Erich Gamma 已提交
1266 1267
	}

J
Johannes Rieken 已提交
1268 1269 1270
	private _moveDown(inSelectionMode: boolean, isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
		ctx.eventData = ctx.eventData || {};
		ctx.eventData.to = editorCommon.CursorMovePosition.Down;
1271
		ctx.eventData.select = inSelectionMode;
J
Johannes Rieken 已提交
1272 1273
		ctx.eventData.by = editorCommon.CursorMoveByUnit.WrappedLine;
		ctx.eventData.isPaged = isPaged;
1274 1275

		return this._cursorMove(ctx);
E
Erich Gamma 已提交
1276 1277
	}

J
Johannes Rieken 已提交
1278 1279 1280 1281 1282 1283
	private _moveUp(inSelectionMode: boolean, isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
		ctx.eventData = ctx.eventData || {};
		ctx.eventData.to = editorCommon.CursorMovePosition.Up;
		ctx.eventData.select = inSelectionMode;
		ctx.eventData.by = editorCommon.CursorMoveByUnit.WrappedLine;
		ctx.eventData.isPaged = isPaged;
1284 1285

		return this._cursorMove(ctx);
E
Erich Gamma 已提交
1286 1287
	}

J
Johannes Rieken 已提交
1288
	private _moveToBeginningOfLine(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1289 1290 1291
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveToBeginningOfLine(oneCursor, inSelectionMode, oneCtx));
	}

J
Johannes Rieken 已提交
1292
	private _moveToEndOfLine(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1293 1294 1295
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveToEndOfLine(oneCursor, inSelectionMode, oneCtx));
	}

J
Johannes Rieken 已提交
1296
	private _moveToBeginningOfBuffer(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1297 1298 1299
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveToBeginningOfBuffer(oneCursor, inSelectionMode, oneCtx));
	}

J
Johannes Rieken 已提交
1300
	private _moveToEndOfBuffer(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1301 1302 1303 1304 1305 1306 1307 1308
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.moveToEndOfBuffer(oneCursor, inSelectionMode, oneCtx));
	}

	private _selectAll(ctx: IMultipleCursorOperationContext): boolean {
		this.cursors.killSecondaryCursors();
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.selectAll(oneCursor, oneCtx));
	}

J
Johannes Rieken 已提交
1309
	private _line(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1310 1311 1312 1313
		this.cursors.killSecondaryCursors();
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.line(oneCursor, inSelectionMode, ctx.eventData.position, ctx.eventData.viewPosition, oneCtx));
	}

J
Johannes Rieken 已提交
1314
	private _lastCursorLine(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
		if (this.configuration.editor.readOnly || this.model.hasEditableRange()) {
			return false;
		}

		var lastAddedCursor = this.cursors.getLastAddedCursor();
		this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			if (oneCursor === lastAddedCursor) {
				return OneCursorOp.line(oneCursor, inSelectionMode, ctx.eventData.position, ctx.eventData.viewPosition, oneCtx);
			}
			return false;
		});

		ctx.shouldReveal = false;
		ctx.shouldRevealHorizontal = false;

		return true;
	}

1333 1334 1335 1336
	private _expandLineSelection(ctx: IMultipleCursorOperationContext): boolean {
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.expandLineSelection(oneCursor, oneCtx));
	}

J
Johannes Rieken 已提交
1337
	private _word(inSelectionMode: boolean, ctx: IMultipleCursorOperationContext): boolean {
E
Erich Gamma 已提交
1338
		this.cursors.killSecondaryCursors();
A
Alex Dima 已提交
1339
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.word(oneCursor, inSelectionMode, oneCursor.validatePosition(ctx.eventData.position), oneCtx));
E
Erich Gamma 已提交
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
	}

	private _lastCursorWord(ctx: IMultipleCursorOperationContext): boolean {
		if (this.configuration.editor.readOnly || this.model.hasEditableRange()) {
			return false;
		}

		var lastAddedCursor = this.cursors.getLastAddedCursor();
		this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			if (oneCursor === lastAddedCursor) {
A
Alex Dima 已提交
1350
				return OneCursorOp.word(oneCursor, true, oneCursor.validatePosition(ctx.eventData.position), oneCtx);
E
Erich Gamma 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
			}
			return false;
		});

		ctx.shouldReveal = false;
		ctx.shouldRevealHorizontal = false;

		return true;
	}

	private _removeSecondaryCursors(ctx: IMultipleCursorOperationContext): boolean {
		this.cursors.killSecondaryCursors();
		return true;
	}

	private _cancelSelection(ctx: IMultipleCursorOperationContext): boolean {
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => OneCursorOp.cancelSelection(oneCursor, oneCtx));
	}

A
Alex Dima 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
	// -------------------- START editing operations

	private _doApplyEdit(cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext, callable: (oneCursor: OneCursor, cursorIndex: number) => EditOperationResult): boolean {
		let r = callable(oneCursor, cursorIndex);
		if (r) {
			oneCtx.executeCommand = r.command;
			oneCtx.shouldPushStackElementBefore = r.shouldPushStackElementBefore;
			oneCtx.shouldPushStackElementAfter = r.shouldPushStackElementAfter;
			oneCtx.isAutoWhitespaceCommand = r.isAutoWhitespaceCommand;
			oneCtx.shouldRevealHorizontal = r.shouldRevealHorizontal;
			oneCtx.cursorPositionChangeReason = r.cursorPositionChangeReason;
		}
		return true;
	}

	private _applyEditForAll(ctx: IMultipleCursorOperationContext, callable: (oneCursor: OneCursor, cursorIndex: number) => EditOperationResult): boolean {
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => this._doApplyEdit(cursorIndex, oneCursor, oneCtx, callable), false, false);
	}

	private _applyEditForAllSorted(ctx: IMultipleCursorOperationContext, callable: (oneCursor: OneCursor, cursorIndex: number) => EditOperationResult): boolean {
		return this._invokeForAllSorted(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => this._doApplyEdit(cursorIndex, oneCursor, oneCtx, callable), false, false);
	}

	private _lineInsertBefore(ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.lineInsertBefore(cursor.config, cursor.model, cursor.modelState));
	}

	private _lineInsertAfter(ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.lineInsertAfter(cursor.config, cursor.model, cursor.modelState));
	}

	private _lineBreakInsert(ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.lineBreakInsert(cursor.config, cursor.model, cursor.modelState));
	}

E
Erich Gamma 已提交
1405 1406 1407 1408 1409 1410
	private _type(ctx: IMultipleCursorOperationContext): boolean {
		var text = ctx.eventData.text;

		if (ctx.eventSource === 'keyboard') {
			// If this event is coming straight from the keyboard, look for electric characters and enter

1411 1412 1413 1414 1415 1416 1417 1418 1419
			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 已提交
1420 1421 1422 1423

				this.charactersTyped += chr;

				// Here we must interpret each typed character individually, that's why we create a new context
J
Johannes Rieken 已提交
1424
				ctx.hasExecutedCommands = this._createAndInterpretHandlerCtx(ctx.eventSource, ctx.eventData, (charHandlerCtx: IMultipleCursorOperationContext) => {
E
Erich Gamma 已提交
1425

A
Alex Dima 已提交
1426
					this._applyEditForAll(charHandlerCtx, (cursor) => TypeOperations.typeWithInterceptors(cursor.config, cursor.model, cursor.modelState, chr));
E
Erich Gamma 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

					// The last typed character gets to win
					ctx.cursorPositionChangeReason = charHandlerCtx.cursorPositionChangeReason;
					ctx.shouldReveal = charHandlerCtx.shouldReveal;
					ctx.shouldRevealVerticalInCenter = charHandlerCtx.shouldRevealVerticalInCenter;
					ctx.shouldRevealHorizontal = charHandlerCtx.shouldRevealHorizontal;
				}) || ctx.hasExecutedCommands;

			}
		} else {
A
Alex Dima 已提交
1437
			this._applyEditForAll(ctx, (cursor) => TypeOperations.typeWithoutInterceptors(cursor.config, cursor.model, cursor.modelState, text));
E
Erich Gamma 已提交
1438 1439 1440 1441 1442 1443
		}

		return true;
	}

	private _replacePreviousChar(ctx: IMultipleCursorOperationContext): boolean {
1444 1445
		let text = ctx.eventData.text;
		let replaceCharCnt = ctx.eventData.replaceCharCnt;
A
Alex Dima 已提交
1446
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.replacePreviousChar(cursor.config, cursor.model, cursor.modelState, text, replaceCharCnt));
E
Erich Gamma 已提交
1447 1448 1449
	}

	private _tab(ctx: IMultipleCursorOperationContext): boolean {
A
Alex Dima 已提交
1450
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.tab(cursor.config, cursor.model, cursor.modelState));
E
Erich Gamma 已提交
1451 1452 1453
	}

	private _indent(ctx: IMultipleCursorOperationContext): boolean {
A
Alex Dima 已提交
1454
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.indent(cursor.config, cursor.model, cursor.modelState));
E
Erich Gamma 已提交
1455 1456 1457
	}

	private _outdent(ctx: IMultipleCursorOperationContext): boolean {
A
Alex Dima 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
		return this._applyEditForAll(ctx, (cursor) => TypeOperations.outdent(cursor.config, cursor.model, cursor.modelState));
	}

	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 已提交
1483 1484 1485 1486 1487 1488
	}

	private _paste(ctx: IMultipleCursorOperationContext): boolean {
		var distributedPaste = this._distributePasteToCursors(ctx);

		if (distributedPaste) {
A
Alex Dima 已提交
1489
			return this._applyEditForAllSorted(ctx, (cursor, cursorIndex) => TypeOperations.paste(cursor.config, cursor.model, cursor.modelState, distributedPaste[cursorIndex], false));
E
Erich Gamma 已提交
1490
		} else {
A
Alex Dima 已提交
1491
			return this._applyEditForAll(ctx, (cursor) => TypeOperations.paste(cursor.config, cursor.model, cursor.modelState, ctx.eventData.text, ctx.eventData.pasteOnNewLine));
E
Erich Gamma 已提交
1492 1493 1494
		}
	}

A
Alex Dima 已提交
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
	private _deleteLeft(ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => DeleteOperations.deleteLeft(cursor.config, cursor.model, cursor.modelState));
	}

	private _deleteWordLeft(whitespaceHeuristics: boolean, wordNavigationType: WordNavigationType, ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => WordOperations.deleteWordLeft(cursor.config, cursor.model, cursor.modelState, whitespaceHeuristics, wordNavigationType));
	}

	private _deleteRight(ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => DeleteOperations.deleteRight(cursor.config, cursor.model, cursor.modelState));
	}

	private _deleteWordRight(whitespaceHeuristics: boolean, wordNavigationType: WordNavigationType, ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => WordOperations.deleteWordRight(cursor.config, cursor.model, cursor.modelState, whitespaceHeuristics, wordNavigationType));
	}

	private _cut(ctx: IMultipleCursorOperationContext): boolean {
		return this._applyEditForAll(ctx, (cursor) => DeleteOperations.cut(cursor.config, cursor.model, cursor.modelState, this.enableEmptySelectionClipboard));
	}

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


1518 1519 1520
	private _revealLine(ctx: IMultipleCursorOperationContext): boolean {
		const revealLineArg: editorCommon.RevealLineArguments = ctx.eventData;
		const lineNumber = revealLineArg.lineNumber + 1;
1521
		let range = this.model.validateRange({
1522 1523 1524 1525 1526
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
		});
1527
		range = new Range(range.startLineNumber, range.startColumn, range.endLineNumber, this.model.getLineMaxColumn(range.endLineNumber));
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545

		let revealAt = editorCommon.VerticalRevealType.Simple;
		if (revealLineArg.at) {
			switch (revealLineArg.at) {
				case editorCommon.RevealLineAtArgument.Top:
					revealAt = editorCommon.VerticalRevealType.Top;
					break;
				case editorCommon.RevealLineAtArgument.Center:
					revealAt = editorCommon.VerticalRevealType.Center;
					break;
				case editorCommon.RevealLineAtArgument.Bottom:
					revealAt = editorCommon.VerticalRevealType.Bottom;
					break;
				default:
					break;
			}
		}

1546
		this.emitCursorRevealRange(range, null, revealAt, false, false);
1547 1548 1549
		return true;
	}

1550 1551
	private _editorScroll(ctx: IMultipleCursorOperationContext): boolean {
		let editorScrollArg: editorCommon.EditorScrollArguments = ctx.eventData;
1552
		editorScrollArg.value = editorScrollArg.value || 1;
1553 1554 1555
		switch (editorScrollArg.to) {
			case editorCommon.EditorScrollDirection.Up:
			case editorCommon.EditorScrollDirection.Down:
1556 1557 1558 1559 1560 1561
				return this._scrollUpOrDown(editorScrollArg, ctx);
		}
		return true;
	}

	private _scrollUpOrDown(editorScrollArg: editorCommon.EditorScrollArguments, ctx: IMultipleCursorOperationContext): boolean {
1562
		if (this._scrollByReveal(editorScrollArg, ctx)) {
1563 1564
			return true;
		}
1565 1566 1567
		let up = editorScrollArg.to === editorCommon.EditorScrollDirection.Up;
		let cursor: OneCursor = this.cursors.getAll()[0];
		let noOfLines = editorScrollArg.value || 1;
1568 1569
		switch (editorScrollArg.by) {
			case editorCommon.EditorScrollByUnit.Page:
A
Alex Dima 已提交
1570
				noOfLines = cursor.config.pageSize * noOfLines;
1571 1572
				break;
			case editorCommon.EditorScrollByUnit.HalfPage:
A
Alex Dima 已提交
1573
				noOfLines = Math.round(cursor.config.pageSize / 2) * noOfLines;
1574 1575
				break;
		}
1576
		this.emitCursorScrollRequest((up ? -1 : 1) * noOfLines, !!editorScrollArg.revealCursor);
B
Benjamin Pasero 已提交
1577
		return true;
1578 1579
	}

1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
	private _scrollByReveal(editorScrollArg: editorCommon.EditorScrollArguments, ctx: IMultipleCursorOperationContext): boolean {
		let up = editorScrollArg.to === editorCommon.EditorScrollDirection.Up;
		let cursor: OneCursor = this.cursors.getAll()[0];
		if (editorCommon.EditorScrollByUnit.Line !== editorScrollArg.by) {
			// Scroll by reveal is done only when unit is line.
			return false;
		}
		if (!up && cursor.isLastLineVisibleInViewPort()) {
			// Scroll by reveal is not done if last line is visible and scrolling down.
			return false;
		}
		let range = up ? cursor.getRangeToRevealModelLinesBeforeViewPortTop(editorScrollArg.value) : cursor.getRangeToRevealModelLinesAfterViewPortBottom(editorScrollArg.value);
		this.emitCursorRevealRange(range, null, up ? editorCommon.VerticalRevealType.Top : editorCommon.VerticalRevealType.Bottom, false, true);
		return true;
	}

1596 1597
	private _scrollUp(isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
		ctx.eventData = <editorCommon.EditorScrollArguments>{ to: editorCommon.EditorScrollDirection.Up, value: 1 };
1598
		ctx.eventData.by = isPaged ? editorCommon.EditorScrollByUnit.Page : editorCommon.EditorScrollByUnit.WrappedLine;
1599 1600 1601
		return this._editorScroll(ctx);
	}

1602
	private _scrollDown(isPaged: boolean, ctx: IMultipleCursorOperationContext): boolean {
1603
		ctx.eventData = <editorCommon.EditorScrollArguments>{ to: editorCommon.EditorScrollDirection.Down, value: 1 };
1604
		ctx.eventData.by = isPaged ? editorCommon.EditorScrollByUnit.Page : editorCommon.EditorScrollByUnit.WrappedLine;
1605
		return this._editorScroll(ctx);
1606 1607
	}

E
Erich Gamma 已提交
1608
	private _undo(ctx: IMultipleCursorOperationContext): boolean {
A
Alex Dima 已提交
1609
		ctx.cursorPositionChangeReason = editorCommon.CursorChangeReason.Undo;
E
Erich Gamma 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618
		ctx.hasExecutedCommands = true;
		this._interpretCommandResult(this.model.undo());
		return true;
	}

	private _cursorUndo(ctx: IMultipleCursorOperationContext): boolean {
		if (this.cursorUndoStack.length === 0) {
			return false;
		}
A
Alex Dima 已提交
1619
		ctx.cursorPositionChangeReason = editorCommon.CursorChangeReason.Undo;
E
Erich Gamma 已提交
1620 1621 1622 1623 1624 1625
		ctx.isCursorUndo = true;
		this.cursors.restoreState(this.cursorUndoStack.pop());
		return true;
	}

	private _redo(ctx: IMultipleCursorOperationContext): boolean {
A
Alex Dima 已提交
1626
		ctx.cursorPositionChangeReason = editorCommon.CursorChangeReason.Redo;
E
Erich Gamma 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
		ctx.hasExecutedCommands = true;
		this._interpretCommandResult(this.model.redo());
		return true;
	}

	private _externalExecuteCommand(ctx: IMultipleCursorOperationContext): boolean {
		this.cursors.killSecondaryCursors();
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			oneCtx.shouldPushStackElementBefore = true;
			oneCtx.shouldPushStackElementAfter = true;
			oneCtx.executeCommand = ctx.eventData;
			return false;
		});
	}

	private _externalExecuteCommands(ctx: IMultipleCursorOperationContext): boolean {
		return this._invokeForAll(ctx, (cursorIndex: number, oneCursor: OneCursor, oneCtx: IOneCursorOperationContext) => {
			oneCtx.shouldPushStackElementBefore = true;
			oneCtx.shouldPushStackElementAfter = true;
			oneCtx.executeCommand = ctx.eventData[cursorIndex];
			return false;
		});
	}
}