commonCodeEditor.ts 31.4 KB
Newer Older
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';

7
import * as nls from 'vs/nls';
A
Alex Dima 已提交
8
import {IAction, IActionProvider, isAction} from 'vs/base/common/actions';
9
import {onUnexpectedError} from 'vs/base/common/errors';
A
Alex Dima 已提交
10
import {EventEmitter, IEventEmitter, ListenerUnbind} from 'vs/base/common/eventEmitter';
J
Joao Moreno 已提交
11
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
12 13 14
import * as objects from 'vs/base/common/objects';
import * as timer from 'vs/base/common/timer';
import {TPromise} from 'vs/base/common/winjs.base';
15
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
16
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
A
Alex Dima 已提交
17 18
import {IKeybindingContextKey, IKeybindingScopeLocation, IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
19
import {CommonEditorConfiguration} from 'vs/editor/common/config/commonEditorConfig';
A
Alex Dima 已提交
20
import {DefaultConfig} from 'vs/editor/common/config/defaultConfig';
21 22 23
import {Cursor} from 'vs/editor/common/controller/cursor';
import {CursorMoveHelper} from 'vs/editor/common/controller/cursorMoveHelper';
import {IViewModelHelper} from 'vs/editor/common/controller/oneCursor';
A
Alex Dima 已提交
24
import {EditorState} from 'vs/editor/common/core/editorState';
25
import {Position} from 'vs/editor/common/core/position';
A
Alex Dima 已提交
26
import {Range} from 'vs/editor/common/core/range';
27
import {Selection} from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
28 29 30 31 32 33
import {DynamicEditorAction} from 'vs/editor/common/editorAction';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {CharacterHardWrappingLineMapperFactory} from 'vs/editor/common/viewModel/characterHardWrappingLineMapper';
import {SplitLinesCollection} from 'vs/editor/common/viewModel/splitLinesCollection';
import {ViewModel} from 'vs/editor/common/viewModel/viewModel';
34 35 36

var EDITOR_ID = 0;

A
Alex Dima 已提交
37
export abstract class CommonCodeEditor extends EventEmitter implements IActionProvider, editorCommon.ICommonCodeEditor {
38 39 40 41 42 43 44 45 46 47

	protected domElement: IKeybindingScopeLocation;

	protected id:number;

	_lifetimeDispose: IDisposable[];
	_configuration:CommonEditorConfiguration;

	_telemetryService:ITelemetryService;

A
Alex Dima 已提交
48
	protected contributions:{ [key:string]:editorCommon.IEditorContribution; };
49 50 51 52

	protected forcedWidgetFocusCount:number;

	// --- Members logically associated to a model
A
Alex Dima 已提交
53 54
	protected model:editorCommon.IModel;
	protected listenersToRemove:ListenerUnbind[];
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
	protected hasView: boolean;

	protected viewModel:ViewModel;
	protected cursor:Cursor;

	protected _instantiationService: IInstantiationService;
	protected _keybindingService: IKeybindingService;

	private _decorationTypeKeysToIds: {[decorationTypeKey:string]:string[];};

	private _codeEditorService: ICodeEditorService;
	private _editorIdContextKey: IKeybindingContextKey<string>;
	protected _editorFocusContextKey: IKeybindingContextKey<boolean>;
	private _editorTabMovesFocusKey: IKeybindingContextKey<boolean>;
	private _hasMultipleSelectionsKey: IKeybindingContextKey<boolean>;
	private _hasNonEmptySelectionKey: IKeybindingContextKey<boolean>;
	private _langIdKey: IKeybindingContextKey<string>;

	constructor(
		domElement: IKeybindingScopeLocation,
75
		options:editorCommon.IEditorOptions,
76 77 78 79 80 81 82
		instantiationService: IInstantiationService,
		codeEditorService: ICodeEditorService,
		keybindingService: IKeybindingService,
		telemetryService: ITelemetryService
	) {
		super();

A
Alex Dima 已提交
83 84
		this.domElement = domElement;

85 86 87
		this.id = (++EDITOR_ID);
		this._codeEditorService = codeEditorService;

A
Alex Dima 已提交
88
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.ctor');
89 90 91 92 93

		this._lifetimeDispose = [];

		this._keybindingService = keybindingService.createScoped(domElement);
		this._editorIdContextKey = this._keybindingService.createKey('editorId', this.getId());
A
Alex Dima 已提交
94 95 96 97 98
		this._editorFocusContextKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_FOCUS, undefined);
		this._editorTabMovesFocusKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_TAB_MOVES_FOCUS, false);
		this._hasMultipleSelectionsKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_MULTIPLE_SELECTIONS, false);
		this._hasNonEmptySelectionKey = this._keybindingService.createKey(editorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_NON_EMPTY_SELECTION, false);
		this._langIdKey = this._keybindingService.createKey<string>(editorCommon.KEYBINDING_CONTEXT_EDITOR_LANGUAGE_ID, undefined);
99 100 101 102 103

		// listeners that are kept during the whole editor lifetime
		this._decorationTypeKeysToIds = {};

		options = options || {};
104 105 106 107 108
		if (typeof options.ariaLabel === 'undefined') {
			options.ariaLabel = DefaultConfig.editor.ariaLabel;
		}
		options.ariaLabel += this._ariaLabelAppendMessage();

109
		this._configuration = this._createConfiguration(options);
110 111 112
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		}
A
Alex Dima 已提交
113
		this._lifetimeDispose.push(this._configuration.onDidChange((e) => this.emit(editorCommon.EventType.ConfigurationChanged, e)));
114 115 116 117

		this.forcedWidgetFocusCount = 0;

		this._telemetryService = telemetryService;
118
		this._instantiationService = instantiationService.createChild(new ServiceCollection([IKeybindingService, this._keybindingService]));
119

120
		this._attachModel(null);
121 122 123 124 125 126 127 128 129 130

		// Create editor contributions
		this.contributions = {};


		timerEvent.stop();

		this._codeEditorService.addCodeEditor(this);
	}

131
	protected abstract _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration;
132 133 134 135 136 137

	public getId(): string {
		return this.getEditorType() + ':' + this.id;
	}

	public getEditorType(): string {
A
Alex Dima 已提交
138
		return editorCommon.EditorType.ICodeEditor;
139 140 141 142 143 144 145 146
	}

	public destroy(): void {
		this.dispose();
	}

	public dispose(): void {
		this._codeEditorService.removeCodeEditor(this);
J
Joao Moreno 已提交
147
		this._lifetimeDispose = dispose(this._lifetimeDispose);
148

A
Alex Dima 已提交
149 150 151 152
		let keys = Object.keys(this.contributions);
		for (let i = 0, len = keys.length; i < len; i++) {
			let contributionId = keys[i];
			this.contributions[contributionId].dispose();
153
		}
A
Alex Dima 已提交
154

155 156 157 158 159
		this.contributions = {};

		this._postDetachModelCleanup(this._detachModel());
		this._configuration.dispose();
		this._keybindingService.dispose();
A
Alex Dima 已提交
160
		this.emit(editorCommon.EventType.Disposed, {});
161 162 163
		super.dispose();
	}

A
Alex Dima 已提交
164
	public captureState(...flags:editorCommon.CodeEditorStateFlag[]): editorCommon.ICodeEditorState {
165 166 167
		return new EditorState(this, flags);
	}

168
	private _ariaLabelAppendMessage(): string {
A
Alex Dima 已提交
169
		let keybindings = this._keybindingService.lookupKeybindings(editorCommon.SHOW_ACCESSIBILITY_HELP_ACTION_ID);
170
		if (keybindings.length > 0) {
171
			return nls.localize('showAccessibilityHelp', "Press {0} if you are using a screen reader.", this._keybindingService.getAriaLabelFor(keybindings[0]));
172 173 174 175
		}
		return '';
	}

A
Alex Dima 已提交
176
	public updateOptions(newOptions:editorCommon.IEditorOptions): void {
177 178 179
		if (typeof newOptions.ariaLabel !== 'undefined') {
			newOptions.ariaLabel += this._ariaLabelAppendMessage();
		}
180 181 182 183 184 185 186 187
		this._configuration.updateOptions(newOptions);
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		} else {
			this._editorTabMovesFocusKey.reset();
		}
	}

A
Alex Dima 已提交
188
	public getConfiguration(): editorCommon.IInternalEditorOptions {
A
Alex Dima 已提交
189
		return this._configuration.editorClone;
190 191
	}

A
Alex Dima 已提交
192
	public getRawConfiguration(): editorCommon.IEditorOptions {
193 194 195 196 197 198
		return this._configuration.getRawOptions();
	}

	public getValue(options:{ preserveBOM:boolean; lineEnding:string; }=null): string {
		if (this.model) {
			var preserveBOM:boolean = (options && options.preserveBOM) ? true : false;
A
Alex Dima 已提交
199
			var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
200
			if (options && options.lineEnding && options.lineEnding === '\n') {
A
Alex Dima 已提交
201
				eolPreference = editorCommon.EndOfLinePreference.LF;
202
			} else if (options  && options.lineEnding && options.lineEnding === '\r\n') {
A
Alex Dima 已提交
203
				eolPreference = editorCommon.EndOfLinePreference.CRLF;
204 205 206 207 208 209 210 211 212 213 214 215
			}
			return this.model.getValue(eolPreference, preserveBOM);
		}
		return '';
	}

	public setValue(newValue:string): void {
		if (this.model) {
			this.model.setValue(newValue);
		}
	}

A
Alex Dima 已提交
216
	public getModel(): editorCommon.IModel {
217 218 219
		return this.model;
	}

A
Alex Dima 已提交
220
	public setModel(model:editorCommon.IModel = null): void {
221 222 223 224 225
		if (this.model === model) {
			// Current model is the new model
			return;
		}

A
Alex Dima 已提交
226
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.setModel');
227 228 229 230 231 232 233 234 235 236 237 238 239

		var detachedModel = this._detachModel();
		this._attachModel(model);

		var oldModelUrl: string = null;
		var newModelUrl: string = null;

		if (detachedModel) {
			oldModelUrl = detachedModel.getAssociatedResource().toString();
		}
		if (model) {
			newModelUrl = model.getAssociatedResource().toString();
		}
A
Alex Dima 已提交
240
		var e: editorCommon.IModelChangedEvent = {
241 242 243 244 245 246
			oldModelUrl: oldModelUrl,
			newModelUrl: newModelUrl
		};

		timerEvent.stop();

A
Alex Dima 已提交
247
		this.emit(editorCommon.EventType.ModelChanged, e);
248 249 250
		this._postDetachModelCleanup(detachedModel);
	}

A
Alex Dima 已提交
251
	public abstract getCenteredRangeInViewport(): editorCommon.IEditorRange;
252

A
Alex Dima 已提交
253
	public getVisibleColumnFromPosition(rawPosition:editorCommon.IPosition): number {
254 255 256 257
		if (!this.model) {
			return rawPosition.column;
		}

258 259
		let position = this.model.validatePosition(rawPosition);
		let tabSize = this.model.getOptions().tabSize;
260

261
		return CursorMoveHelper.visibleColumnFromColumn(this.model, position.lineNumber, position.column, tabSize) + 1;
262 263
	}

A
Alex Dima 已提交
264
	public getPosition(): editorCommon.IEditorPosition {
265 266 267 268 269 270
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getPosition().clone();
	}

A
Alex Dima 已提交
271
	public setPosition(position:editorCommon.IPosition, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
		if (!this.cursor) {
			return;
		}
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this.cursor.setSelections('api', [{
			selectionStartLineNumber: position.lineNumber,
			selectionStartColumn: position.column,
			positionLineNumber: position.lineNumber,
			positionColumn: position.column
		}]);
		if (reveal) {
			this.revealPosition(position, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
289
	private _sendRevealRange(range: editorCommon.IRange, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
290 291 292 293 294 295 296 297
		if (!this.model || !this.cursor) {
			return;
		}
		if (!Range.isIRange(range)) {
			throw new Error('Invalid arguments');
		}
		var validatedRange = this.model.validateRange(range);

A
Alex Dima 已提交
298
		var revealRangeEvent: editorCommon.ICursorRevealRangeEvent = {
299 300 301 302 303
			range: validatedRange,
			viewRange: null,
			verticalType: verticalType,
			revealHorizontal: revealHorizontal
		};
A
Alex Dima 已提交
304
		this.cursor.emit(editorCommon.EventType.CursorRevealRange, revealRangeEvent);
305 306 307 308 309 310 311 312
	}

	public revealLine(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
313
		}, editorCommon.VerticalRevealType.Simple, false);
314 315 316 317 318 319 320 321
	}

	public revealLineInCenter(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
322
		}, editorCommon.VerticalRevealType.Center, false);
323 324 325 326 327 328 329 330
	}

	public revealLineInCenterIfOutsideViewport(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
331
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, false);
332 333
	}

A
Alex Dima 已提交
334
	public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean=false, revealHorizontal:boolean=false): void {
335 336 337 338 339 340 341 342
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this._sendRevealRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
A
Alex Dima 已提交
343
		}, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
344 345
	}

A
Alex Dima 已提交
346
	public revealPositionInCenter(position: editorCommon.IPosition): void {
347 348 349 350 351 352 353 354
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this._sendRevealRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
A
Alex Dima 已提交
355
		}, editorCommon.VerticalRevealType.Center, true);
356 357
	}

A
Alex Dima 已提交
358
	public revealPositionInCenterIfOutsideViewport(position: editorCommon.IPosition): void {
359 360 361 362 363 364 365 366
		if (!Position.isIPosition(position)) {
			throw new Error('Invalid arguments');
		}
		this._sendRevealRange({
			startLineNumber: position.lineNumber,
			startColumn: position.column,
			endLineNumber: position.lineNumber,
			endColumn: position.column
A
Alex Dima 已提交
367
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
368 369
	}

A
Alex Dima 已提交
370
	public getSelection(): editorCommon.IEditorSelection {
371 372 373 374 375 376
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getSelection().clone();
	}

A
Alex Dima 已提交
377
	public getSelections(): editorCommon.IEditorSelection[] {
378 379 380 381
		if (!this.cursor) {
			return null;
		}
		var selections = this.cursor.getSelections();
A
Alex Dima 已提交
382
		var result:editorCommon.IEditorSelection[] = [];
383 384 385 386 387 388
		for (var i = 0, len = selections.length; i < len; i++) {
			result[i] = selections[i].clone();
		}
		return result;
	}

A
Alex Dima 已提交
389 390 391 392
	public setSelection(range:editorCommon.IRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
	public setSelection(editorRange:editorCommon.IEditorRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
	public setSelection(selection:editorCommon.ISelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
	public setSelection(editorSelection:editorCommon.IEditorSelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
393 394 395 396 397 398 399 400 401
	public setSelection(something:any, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
		var isSelection = Selection.isISelection(something);
		var isRange = Range.isIRange(something);

		if (!isSelection && !isRange) {
			throw new Error('Invalid arguments');
		}

		if (isSelection) {
A
Alex Dima 已提交
402
			this._setSelectionImpl(<editorCommon.ISelection>something, reveal, revealVerticalInCenter, revealHorizontal);
403 404
		} else if (isRange) {
			// act as if it was an IRange
A
Alex Dima 已提交
405
			var selection:editorCommon.ISelection = {
406 407 408 409 410 411 412 413 414
				selectionStartLineNumber: something.startLineNumber,
				selectionStartColumn: something.startColumn,
				positionLineNumber: something.endLineNumber,
				positionColumn: something.endColumn
			};
			this._setSelectionImpl(selection, reveal, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
415
	private _setSelectionImpl(sel:editorCommon.ISelection, reveal:boolean, revealVerticalInCenter:boolean, revealHorizontal:boolean): void {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
		if (!this.cursor) {
			return;
		}
		var selection = Selection.createSelection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
		this.cursor.setSelections('api', [selection]);
		if (reveal) {
			this.revealRange(selection, revealVerticalInCenter, revealHorizontal);
		}
	}

	public revealLines(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
432
		}, editorCommon.VerticalRevealType.Simple, false);
433 434 435 436 437 438 439 440
	}

	public revealLinesInCenter(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
441
		}, editorCommon.VerticalRevealType.Center, false);
442 443 444 445 446 447 448 449
	}

	public revealLinesInCenterIfOutsideViewport(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
450
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, false);
451 452
	}

A
Alex Dima 已提交
453 454
	public revealRange(range: editorCommon.IRange, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = true): void {
		this._sendRevealRange(range, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
455 456
	}

A
Alex Dima 已提交
457 458
	public revealRangeInCenter(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.Center, true);
459 460
	}

A
Alex Dima 已提交
461 462
	public revealRangeInCenterIfOutsideViewport(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
463 464
	}

A
Alex Dima 已提交
465
	public setSelections(ranges: editorCommon.ISelection[]): void {
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		if (!this.cursor) {
			return;
		}
		if (!ranges || ranges.length === 0) {
			throw new Error('Invalid arguments');
		}
		for (var i = 0, len = ranges.length; i < len; i++) {
			if (!Selection.isISelection(ranges[i])) {
				throw new Error('Invalid arguments');
			}
		}
		this.cursor.setSelections('api', ranges);
	}

	public abstract setScrollTop(newScrollTop:number): void;

	public abstract getScrollTop(): number;

	public abstract setScrollLeft(newScrollLeft:number): void;

	public abstract getScrollLeft(): number;

	public abstract getScrollWidth(): number;

	public abstract getScrollHeight(): number;

A
Alex Dima 已提交
492
	public abstract saveViewState(): editorCommon.ICodeEditorViewState;
493

A
Alex Dima 已提交
494
	public abstract restoreViewState(state:editorCommon.IEditorViewState): void;
495 496 497 498 499 500 501

	public onVisible(): void {
	}

	public onHide(): void {
	}

A
Alex Dima 已提交
502
	public abstract layout(dimension?:editorCommon.IDimension): void;
503 504 505 506 507 508 509 510 511 512 513 514 515

	public abstract focus(): void;

	public beginForcedWidgetFocus(): void {
		this.forcedWidgetFocusCount++;
	}

	public endForcedWidgetFocus(): void {
		this.forcedWidgetFocusCount--;
	}

	public abstract isFocused(): boolean;

A
Alex Dima 已提交
516
	public getContribution(id: string): editorCommon.IEditorContribution {
517 518 519
		return this.contributions[id] || null;
	}

A
Alex Dima 已提交
520
	public addAction(descriptor:editorCommon.IActionDescriptor): void {
521 522 523 524 525 526 527
		if (
			(typeof descriptor.id !== 'string')
			|| (typeof descriptor.label !== 'string')
			|| (typeof descriptor.run !== 'function')
		) {
			throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');
		}
528 529 530 531 532
		var action = this._instantiationService.createInstance(DynamicEditorAction, descriptor, this);
		this.contributions[action.getId()] = action;
	}

	public getActions(): IAction[] {
A
Alex Dima 已提交
533 534 535 536 537 538 539 540 541
		let result: IAction[] = [];

		let keys = Object.keys(this.contributions);
		for (let i = 0, len = keys.length; i < len; i++) {
			let id = keys[i];
			let contribution = <any>this.contributions[id];
			// contribution instanceof IAction
			if (isAction(contribution)) {
				result.push(<IAction>contribution);
542 543
			}
		}
A
Alex Dima 已提交
544

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
		return result;
	}

	public getAction(id:string): IAction {
		var contribution = <any>this.contributions[id];
		if (contribution) {
			// contribution instanceof IAction
			if (isAction(contribution)) {
				return <IAction>contribution;
			}
		}
		return null;
	}

	public trigger(source:string, handlerId:string, payload:any): void {
		var candidate = this.getAction(handlerId);
		if(candidate !== null) {
			if (candidate.enabled) {
563
				this._telemetryService.publicLog('editorActionInvoked', {name: candidate.label, id: candidate.id} );
564 565 566 567 568 569 570 571 572 573 574 575
				TPromise.as(candidate.run()).done(null, onUnexpectedError);
			}
		} else {
			// forward to handler dispatcher
			var r = this._configuration.handlerDispatcher.trigger(source, handlerId, payload);

			if (!r) {
//				console.warn('Returning false from ' + handlerId + ' wont do anything special...');
			}
		}
	}

A
Alex Dima 已提交
576
	public executeCommand(source: string, command: editorCommon.ICommand): boolean {
577
		// forward to handler dispatcher
A
Alex Dima 已提交
578
		return this._configuration.handlerDispatcher.trigger(source, editorCommon.Handler.ExecuteCommand, command);
579 580
	}

A
Alex Dima 已提交
581
	public executeEdits(source: string, edits: editorCommon.IIdentifiedSingleEditOperation[]): boolean {
582 583 584 585 586 587 588 589 590 591 592 593 594 595
		if (!this.cursor) {
			// no view, no cursor
			return false;
		}
		if (this._configuration.editor.readOnly) {
			// read only editor => sorry!
			return false;
		}
		this.model.pushEditOperations(this.cursor.getSelections(), edits, () => {
			return this.cursor.getSelections();
		});
		return true;
	}

A
Alex Dima 已提交
596
	public executeCommands(source: string, commands: editorCommon.ICommand[]): boolean {
597
		// forward to handler dispatcher
A
Alex Dima 已提交
598
		return this._configuration.handlerDispatcher.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
599 600
	}

A
Alex Dima 已提交
601
	public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any {
602 603 604 605 606 607 608 609
		if (!this.model) {
//			console.warn('Cannot change decorations on editor that is not attached to a model');
			// callback will not be called
			return null;
		}
		return this.model.changeDecorations(callback, this.id);
	}

A
Alex Dima 已提交
610
	public getLineDecorations(lineNumber: number): editorCommon.IModelDecoration[] {
611 612 613 614 615 616
		if (!this.model) {
			return null;
		}
		return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
	}

A
Alex Dima 已提交
617
	public deltaDecorations(oldDecorations:string[], newDecorations:editorCommon.IModelDeltaDecoration[]): string[] {
618 619 620 621 622 623 624 625 626 627 628
		if (!this.model) {
			return [];
		}

		if (oldDecorations.length === 0 && newDecorations.length === 0) {
			return oldDecorations;
		}

		return this.model.deltaDecorations(oldDecorations, newDecorations, this.id);
	}

A
Alex Dima 已提交
629
	public setDecorations(decorationTypeKey: string, ranges:editorCommon.IRangeWithMessage[]): void {
630 631
		var opts = this._codeEditorService.resolveDecorationType(decorationTypeKey);
		var oldDecorationIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
A
Alex Dima 已提交
632 633
		this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationIds, ranges.map((r) : editorCommon.IModelDeltaDecoration => {
			let decOpts: editorCommon.IModelDecorationOptions;
634
			if (r.hoverMessage) {
A
Alex Dima 已提交
635 636
				// TODO@Alex: avoid objects.clone
				decOpts = objects.clone(opts);
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
				decOpts.htmlMessage = r.hoverMessage;
			} else {
				decOpts = opts;
			}
			return {
				range: r.range,
				options: decOpts
			};
		}));
	}

	public removeDecorations(decorationTypeKey: string): void {
		if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
			this.deltaDecorations(this._decorationTypeKeysToIds[decorationTypeKey], []);
			delete this._decorationTypeKeysToIds[decorationTypeKey];
		}
	}

A
Alex Dima 已提交
655
	public addTypingListener(character:string, callback: () => void): ListenerUnbind {
656 657 658 659 660 661 662 663 664 665 666 667 668
		if (!this.cursor) {
			return () => {
				// no-op
			};
		}
		this.cursor.addTypingListener(character, callback);
		return () => {
			if (this.cursor) {
				this.cursor.removeTypingListener(character, callback);
			}
		};
	}

A
Alex Dima 已提交
669
	public getLayoutInfo(): editorCommon.IEditorLayoutInfo {
670 671 672
		return this._configuration.editor.layoutInfo;
	}

A
Alex Dima 已提交
673
	_attachModel(model:editorCommon.IModel): void {
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
		this.model = model ? model : null;
		this.listenersToRemove = [];
		this.viewModel = null;
		this.cursor = null;

		if (this.model) {
			this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
			this._langIdKey.set(this.model.getMode().getId());
			this.model.setStopLineTokenizationAfter(this._configuration.editor.stopLineTokenizationAfter);
			this._configuration.setIsDominatedByLongLines(this.model.isDominatedByLongLines(this._configuration.editor.longLineBoundary));

			this.model.onBeforeAttached();

			var hardWrappingLineMapperFactory = new CharacterHardWrappingLineMapperFactory(
				this._configuration.editor.wordWrapBreakBeforeCharacters,
				this._configuration.editor.wordWrapBreakAfterCharacters,
				this._configuration.editor.wordWrapBreakObtrusiveCharacters
			);

			var linesCollection = new SplitLinesCollection(
				this.model,
				hardWrappingLineMapperFactory,
696
				this.model.getOptions().tabSize,
697 698
				this._configuration.editor.wrappingInfo.wrappingColumn,
				this._configuration.editor.typicalFullwidthCharacterWidth / this._configuration.editor.typicalHalfwidthCharacterWidth,
A
Alex Dima 已提交
699
				editorCommon.wrappingIndentFromString(this._configuration.editor.wrappingIndent)
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
			);

			this.viewModel = new ViewModel(
				linesCollection,
				this.id,
				this._configuration,
				this.model,
				() => this.getCenteredRangeInViewport()
			);

			var viewModelHelper:IViewModelHelper = {
				viewModel: this.viewModel,
				convertModelPositionToViewPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertModelPositionToViewPosition(lineNumber, column);
				},
A
Alex Dima 已提交
715
				convertModelRangeToViewRange: (modelRange:editorCommon.IEditorRange) => {
716 717 718 719 720
					return this.viewModel.convertModelRangeToViewRange(modelRange);
				},
				convertViewToModelPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertViewPositionToModelPosition(lineNumber, column);
				},
A
Alex Dima 已提交
721 722 723
				convertViewSelectionToModelSelection: (viewSelection:editorCommon.ISelection) => {
					return this.viewModel.convertViewSelectionToModelSelection(viewSelection);
				},
A
Alex Dima 已提交
724
				validateViewPosition: (viewLineNumber:number, viewColumn:number, modelPosition:editorCommon.IEditorPosition) => {
725 726
					return this.viewModel.validateViewPosition(viewLineNumber, viewColumn, modelPosition);
				},
A
Alex Dima 已提交
727
				validateViewRange: (viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:editorCommon.IEditorRange) => {
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
					return this.viewModel.validateViewRange(viewStartLineNumber, viewStartColumn, viewEndLineNumber, viewEndColumn, modelRange);
				}
			};

			this.cursor = new Cursor(
				this.id,
				this._configuration,
				this.model,
				viewModelHelper,
				this._enableEmptySelectionClipboard()
			);

			this.viewModel.addEventSource(this.cursor);

			this._createView();

			this.listenersToRemove.push(this._getViewInternalEventBus().addBulkListener((events) => {
				for (var i = 0, len = events.length; i < len; i++) {
					var eventType = events[i].getType();
					var e = events[i].getData();

					switch (eventType) {
A
Alex Dima 已提交
750 751
						case editorCommon.EventType.ViewFocusGained:
							this.emit(editorCommon.EventType.EditorTextFocus);
752
							// In IE, the focus is not synchronous, so we give it a little help
A
Alex Dima 已提交
753
							this.emit(editorCommon.EventType.EditorFocus, {});
754 755 756 757 758 759 760 761 762 763
							break;

						case 'scroll':
							this.emit('scroll', e);
							break;

						case 'scrollSize':
							this.emit('scrollSize', e);
							break;

A
Alex Dima 已提交
764 765
						case editorCommon.EventType.ViewFocusLost:
							this.emit(editorCommon.EventType.EditorTextBlur);
766 767
							break;

A
Alex Dima 已提交
768 769
						case editorCommon.EventType.ContextMenu:
							this.emit(editorCommon.EventType.ContextMenu, e);
770 771
							break;

A
Alex Dima 已提交
772 773
						case editorCommon.EventType.MouseDown:
							this.emit(editorCommon.EventType.MouseDown, e);
774 775
							break;

A
Alex Dima 已提交
776 777
						case editorCommon.EventType.MouseUp:
							this.emit(editorCommon.EventType.MouseUp, e);
778 779
							break;

A
Alex Dima 已提交
780 781
						case editorCommon.EventType.KeyUp:
							this.emit(editorCommon.EventType.KeyUp, e);
782 783
							break;

A
Alex Dima 已提交
784 785
						case editorCommon.EventType.MouseMove:
							this.emit(editorCommon.EventType.MouseMove, e);
786 787
							break;

A
Alex Dima 已提交
788 789
						case editorCommon.EventType.MouseLeave:
							this.emit(editorCommon.EventType.MouseLeave, e);
790 791
							break;

A
Alex Dima 已提交
792 793
						case editorCommon.EventType.KeyDown:
							this.emit(editorCommon.EventType.KeyDown, e);
794 795
							break;

A
Alex Dima 已提交
796 797
						case editorCommon.EventType.ViewLayoutChanged:
							this.emit(editorCommon.EventType.EditorLayout, e);
798 799 800 801 802 803 804 805 806 807 808 809 810 811
							break;

						default:
//							console.warn("Unhandled view event: ", e);
					}
				}
			}));

			this.listenersToRemove.push(this.model.addBulkListener((events) => {
				for (var i = 0, len = events.length; i < len; i++) {
					var eventType = events[i].getType();
					var e = events[i].getData();

					switch (eventType) {
A
Alex Dima 已提交
812 813
						case editorCommon.EventType.ModelDecorationsChanged:
							this.emit(editorCommon.EventType.ModelDecorationsChanged, e);
814 815
							break;

A
Alex Dima 已提交
816
						case editorCommon.EventType.ModelModeChanged:
817 818
							this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
							this._langIdKey.set(this.model.getMode().getId());
A
Alex Dima 已提交
819
							this.emit(editorCommon.EventType.ModelModeChanged, e);
820 821
							break;

A
Alex Dima 已提交
822 823
						case editorCommon.EventType.ModelModeSupportChanged:
							this.emit(editorCommon.EventType.ModelModeSupportChanged, e);
824 825
							break;

A
Alex Dima 已提交
826
						case editorCommon.EventType.ModelContentChanged:
827
							// TODO@Alex
A
Alex Dima 已提交
828
							this.emit(editorCommon.EventType.ModelContentChanged, e);
829 830 831
							this.emit('change', {});
							break;

832 833 834 835
						case editorCommon.EventType.ModelOptionsChanged:
							this.emit(editorCommon.EventType.ModelOptionsChanged, e);
							break;

A
Alex Dima 已提交
836
						case editorCommon.EventType.ModelDispose:
837 838 839 840 841 842 843 844 845 846
							// Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
							this.setModel(null);
							break;

						default:
//							console.warn("Unhandled model event: ", e);
					}
				}
			}));

A
Alex Dima 已提交
847
			var _hasNonEmptySelection = (e: editorCommon.ICursorSelectionChangedEvent) => {
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
				var allSelections = [e.selection].concat(e.secondarySelections);
				return allSelections.some(s => !s.isEmpty());
			};

			this.listenersToRemove.push(this.cursor.addBulkListener((events) => {
				var updateHasMultipleCursors = false,
					hasMultipleCursors = false,
					updateHasNonEmptySelection = false,
					hasNonEmptySelection = false;

				for (var i = 0, len = events.length; i < len; i++) {
					var eventType = events[i].getType();
					var e = events[i].getData();

					switch (eventType) {
A
Alex Dima 已提交
863 864
						case editorCommon.EventType.CursorPositionChanged:
							var cursorPositionChangedEvent = <editorCommon.ICursorPositionChangedEvent>e;
865 866
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorPositionChangedEvent.secondaryPositions.length > 0);
A
Alex Dima 已提交
867
							this.emit(editorCommon.EventType.CursorPositionChanged, e);
868 869
							break;

A
Alex Dima 已提交
870 871
						case editorCommon.EventType.CursorSelectionChanged:
							var cursorSelectionChangedEvent = <editorCommon.ICursorSelectionChangedEvent>e;
872 873 874 875
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorSelectionChangedEvent.secondarySelections.length > 0);
							updateHasNonEmptySelection = true;
							hasNonEmptySelection = _hasNonEmptySelection(cursorSelectionChangedEvent);
A
Alex Dima 已提交
876
							this.emit(editorCommon.EventType.CursorSelectionChanged, e);
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
							break;

						default:
//							console.warn("Unhandled cursor event: ", e);
					}
				}

				if (updateHasMultipleCursors) {
					if (hasMultipleCursors) {
						this._hasMultipleSelectionsKey.set(true);
					} else {
						this._hasMultipleSelectionsKey.reset();
					}
				}
				if (updateHasNonEmptySelection) {
					if (hasNonEmptySelection) {
						this._hasNonEmptySelectionKey.set(true);
					} else {
						this._hasNonEmptySelectionKey.reset();
					}
				}
			}));
		} else {
			this.hasView = false;
		}
	}

	protected abstract _enableEmptySelectionClipboard(): boolean;

	protected abstract _createView(): void;

A
Alex Dima 已提交
908
	protected abstract _getViewInternalEventBus(): IEventEmitter;
909

A
Alex Dima 已提交
910
	_postDetachModelCleanup(detachedModel:editorCommon.IModel): void {
911 912 913 914 915 916
		if (detachedModel) {
			this._decorationTypeKeysToIds = {};
			detachedModel.removeAllDecorationsWithOwnerId(this.id);
		}
	}

A
Alex Dima 已提交
917
	protected _detachModel(): editorCommon.IModel {
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
		if (this.model) {
			this.model.onBeforeDetached();
		}

		this.hasView = false;

		this.listenersToRemove.forEach((element) => {
			element();
		});
		this.listenersToRemove = [];

		if (this.cursor) {
			this.cursor.dispose();
			this.cursor = null;
		}

		if (this.viewModel) {
			this.viewModel.dispose();
			this.viewModel = null;
		}

		var result = this.model;
		this.model = null;

		this.domElement.removeAttribute('data-mode-id');

		return result;
	}
}