commonCodeEditor.ts 31.3 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 11 12 13 14 15 16 17 18 19
import {EventEmitter, IEventEmitter, ListenerUnbind} from 'vs/base/common/eventEmitter';
import {IDisposable, disposeAll} from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import * as timer from 'vs/base/common/timer';
import {TPromise} from 'vs/base/common/winjs.base';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IKeybindingContextKey, IKeybindingScopeLocation, IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {CommonEditorConfiguration, IIndentationGuesser} from 'vs/editor/common/config/commonEditorConfig';
import {DefaultConfig} from 'vs/editor/common/config/defaultConfig';
20 21 22
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 已提交
23
import {EditorState} from 'vs/editor/common/core/editorState';
24
import {Position} from 'vs/editor/common/core/position';
A
Alex Dima 已提交
25
import {Range} from 'vs/editor/common/core/range';
26
import {Selection} from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
27 28 29 30 31 32
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';
33 34 35

var EDITOR_ID = 0;

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

	protected domElement: IKeybindingScopeLocation;

	protected id:number;

	_lifetimeDispose: IDisposable[];
	_configuration:CommonEditorConfiguration;

	_telemetryService:ITelemetryService;

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

	protected forcedWidgetFocusCount:number;

	// --- Members logically associated to a model
A
Alex Dima 已提交
52 53
	protected model:editorCommon.IModel;
	protected listenersToRemove:ListenerUnbind[];
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
	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,
74
		options:editorCommon.IEditorOptions,
75 76 77 78 79 80 81
		instantiationService: IInstantiationService,
		codeEditorService: ICodeEditorService,
		keybindingService: IKeybindingService,
		telemetryService: ITelemetryService
	) {
		super();

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

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

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

		this._lifetimeDispose = [];

		this._keybindingService = keybindingService.createScoped(domElement);
		this._editorIdContextKey = this._keybindingService.createKey('editorId', this.getId());
A
Alex Dima 已提交
93 94 95 96 97
		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);
98 99 100 101 102

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

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

108 109 110 111 112 113 114 115 116
		this._configuration = this._createConfiguration(options, (tabSize:number) => {
			if (this.model) {
				return this.model.guessIndentation(tabSize);
			}
			return null;
		});
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		}
A
Alex Dima 已提交
117
		this._lifetimeDispose.push(this._configuration.onDidChange((e) => this.emit(editorCommon.EventType.ConfigurationChanged, e)));
118 119 120 121 122 123 124 125

		this.forcedWidgetFocusCount = 0;

		this._telemetryService = telemetryService;
		this._instantiationService = instantiationService.createChild({
			keybindingService: this._keybindingService
		});

126
		this._attachModel(null);
127 128 129 130 131 132 133 134 135 136

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


		timerEvent.stop();

		this._codeEditorService.addCodeEditor(this);
	}

A
Alex Dima 已提交
137
	protected abstract _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions, indentationGuesser:IIndentationGuesser): CommonEditorConfiguration;
138 139 140 141 142 143

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

	public getEditorType(): string {
A
Alex Dima 已提交
144
		return editorCommon.EditorType.ICodeEditor;
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
	}

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

	public dispose(): void {
		this._codeEditorService.removeCodeEditor(this);
		this._lifetimeDispose = disposeAll(this._lifetimeDispose);

		var contributionId:string;
		for (contributionId in this.contributions) {
			if (this.contributions.hasOwnProperty(contributionId)) {
				this.contributions[contributionId].dispose();
			}
		}
		this.contributions = {};

		this._postDetachModelCleanup(this._detachModel());
		this._configuration.dispose();
		this._keybindingService.dispose();
A
Alex Dima 已提交
166
		this.emit(editorCommon.EventType.Disposed, {});
167 168 169
		super.dispose();
	}

A
Alex Dima 已提交
170
	public captureState(...flags:editorCommon.CodeEditorStateFlag[]): editorCommon.ICodeEditorState {
171 172 173
		return new EditorState(this, flags);
	}

174
	private _ariaLabelAppendMessage(): string {
A
Alex Dima 已提交
175
		let keybindings = this._keybindingService.lookupKeybindings(editorCommon.SHOW_ACCESSIBILITY_HELP_ACTION_ID);
176
		if (keybindings.length > 0) {
A
Alex Dima 已提交
177
			return nls.localize('showAccessibilityHelp', "Press {0} if you are using a screen reader.", this._keybindingService.getLabelFor(keybindings[0]));
178 179 180 181
		}
		return '';
	}

A
Alex Dima 已提交
182
	public updateOptions(newOptions:editorCommon.IEditorOptions): void {
183 184 185
		if (typeof newOptions.ariaLabel !== 'undefined') {
			newOptions.ariaLabel += this._ariaLabelAppendMessage();
		}
186 187 188 189 190 191 192 193
		this._configuration.updateOptions(newOptions);
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		} else {
			this._editorTabMovesFocusKey.reset();
		}
	}

A
Alex Dima 已提交
194
	public getConfiguration(): editorCommon.IInternalEditorOptions {
A
Alex Dima 已提交
195
		return this._configuration.editorClone;
196 197
	}

A
Alex Dima 已提交
198
	public getRawConfiguration(): editorCommon.IEditorOptions {
199 200 201
		return this._configuration.getRawOptions();
	}

A
Alex Dima 已提交
202
	public getIndentationOptions(): editorCommon.IInternalIndentationOptions {
A
Alex Dima 已提交
203 204 205 206 207
		let r = this._configuration.getIndentationOptions();
		return {
			tabSize: r.tabSize,
			insertSpaces: r.insertSpaces
		};
208 209 210 211 212 213 214 215 216
	}

	public normalizeIndentation(str:string): string {
		return this._configuration.normalizeIndentation(str);
	}

	public getValue(options:{ preserveBOM:boolean; lineEnding:string; }=null): string {
		if (this.model) {
			var preserveBOM:boolean = (options && options.preserveBOM) ? true : false;
A
Alex Dima 已提交
217
			var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
218
			if (options && options.lineEnding && options.lineEnding === '\n') {
A
Alex Dima 已提交
219
				eolPreference = editorCommon.EndOfLinePreference.LF;
220
			} else if (options  && options.lineEnding && options.lineEnding === '\r\n') {
A
Alex Dima 已提交
221
				eolPreference = editorCommon.EndOfLinePreference.CRLF;
222 223 224 225 226 227 228 229 230 231 232 233
			}
			return this.model.getValue(eolPreference, preserveBOM);
		}
		return '';
	}

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

A
Alex Dima 已提交
234
	public getModel(): editorCommon.IModel {
235 236 237
		return this.model;
	}

A
Alex Dima 已提交
238
	public setModel(model:editorCommon.IModel = null): void {
239 240 241 242 243
		if (this.model === model) {
			// Current model is the new model
			return;
		}

A
Alex Dima 已提交
244
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.setModel');
245 246 247 248 249 250 251 252 253 254 255 256 257

		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 已提交
258
		var e: editorCommon.IModelChangedEvent = {
259 260 261 262 263 264
			oldModelUrl: oldModelUrl,
			newModelUrl: newModelUrl
		};

		timerEvent.stop();

A
Alex Dima 已提交
265
		this.emit(editorCommon.EventType.ModelChanged, e);
266 267 268
		this._postDetachModelCleanup(detachedModel);
	}

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

A
Alex Dima 已提交
271
	public getVisibleColumnFromPosition(rawPosition:editorCommon.IPosition): number {
272 273 274 275 276 277 278 279 280
		if (!this.model) {
			return rawPosition.column;
		}

		var position = this.model.validatePosition(rawPosition);

		return CursorMoveHelper.visibleColumnFromColumn(this.model, position.lineNumber, position.column, this._configuration.getIndentationOptions().tabSize) + 1;
	}

A
Alex Dima 已提交
281
	public getPosition(): editorCommon.IEditorPosition {
282 283 284 285 286 287
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getPosition().clone();
	}

A
Alex Dima 已提交
288
	public setPosition(position:editorCommon.IPosition, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
		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 已提交
306
	private _sendRevealRange(range: editorCommon.IRange, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
307 308 309 310 311 312 313 314
		if (!this.model || !this.cursor) {
			return;
		}
		if (!Range.isIRange(range)) {
			throw new Error('Invalid arguments');
		}
		var validatedRange = this.model.validateRange(range);

A
Alex Dima 已提交
315
		var revealRangeEvent: editorCommon.ICursorRevealRangeEvent = {
316 317 318 319 320
			range: validatedRange,
			viewRange: null,
			verticalType: verticalType,
			revealHorizontal: revealHorizontal
		};
A
Alex Dima 已提交
321
		this.cursor.emit(editorCommon.EventType.CursorRevealRange, revealRangeEvent);
322 323 324 325 326 327 328 329
	}

	public revealLine(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
330
		}, editorCommon.VerticalRevealType.Simple, false);
331 332 333 334 335 336 337 338
	}

	public revealLineInCenter(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
339
		}, editorCommon.VerticalRevealType.Center, false);
340 341 342 343 344 345 346 347
	}

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

A
Alex Dima 已提交
351
	public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean=false, revealHorizontal:boolean=false): void {
352 353 354 355 356 357 358 359
		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 已提交
360
		}, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
361 362
	}

A
Alex Dima 已提交
363
	public revealPositionInCenter(position: editorCommon.IPosition): void {
364 365 366 367 368 369 370 371
		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 已提交
372
		}, editorCommon.VerticalRevealType.Center, true);
373 374
	}

A
Alex Dima 已提交
375
	public revealPositionInCenterIfOutsideViewport(position: editorCommon.IPosition): void {
376 377 378 379 380 381 382 383
		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 已提交
384
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
385 386
	}

A
Alex Dima 已提交
387
	public getSelection(): editorCommon.IEditorSelection {
388 389 390 391 392 393
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getSelection().clone();
	}

A
Alex Dima 已提交
394
	public getSelections(): editorCommon.IEditorSelection[] {
395 396 397 398
		if (!this.cursor) {
			return null;
		}
		var selections = this.cursor.getSelections();
A
Alex Dima 已提交
399
		var result:editorCommon.IEditorSelection[] = [];
400 401 402 403 404 405
		for (var i = 0, len = selections.length; i < len; i++) {
			result[i] = selections[i].clone();
		}
		return result;
	}

A
Alex Dima 已提交
406 407 408 409
	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;
410 411 412 413 414 415 416 417 418
	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 已提交
419
			this._setSelectionImpl(<editorCommon.ISelection>something, reveal, revealVerticalInCenter, revealHorizontal);
420 421
		} else if (isRange) {
			// act as if it was an IRange
A
Alex Dima 已提交
422
			var selection:editorCommon.ISelection = {
423 424 425 426 427 428 429 430 431
				selectionStartLineNumber: something.startLineNumber,
				selectionStartColumn: something.startColumn,
				positionLineNumber: something.endLineNumber,
				positionColumn: something.endColumn
			};
			this._setSelectionImpl(selection, reveal, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
432
	private _setSelectionImpl(sel:editorCommon.ISelection, reveal:boolean, revealVerticalInCenter:boolean, revealHorizontal:boolean): void {
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
		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 已提交
449
		}, editorCommon.VerticalRevealType.Simple, false);
450 451 452 453 454 455 456 457
	}

	public revealLinesInCenter(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
458
		}, editorCommon.VerticalRevealType.Center, false);
459 460 461 462 463 464 465 466
	}

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

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

A
Alex Dima 已提交
474 475
	public revealRangeInCenter(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.Center, true);
476 477
	}

A
Alex Dima 已提交
478 479
	public revealRangeInCenterIfOutsideViewport(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
480 481
	}

A
Alex Dima 已提交
482
	public setSelections(ranges: editorCommon.ISelection[]): void {
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
		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 已提交
509
	public abstract saveViewState(): editorCommon.ICodeEditorViewState;
510

A
Alex Dima 已提交
511
	public abstract restoreViewState(state:editorCommon.IEditorViewState): void;
512 513 514 515 516 517 518

	public onVisible(): void {
	}

	public onHide(): void {
	}

A
Alex Dima 已提交
519
	public abstract layout(dimension?:editorCommon.IDimension): void;
520 521 522 523 524 525 526 527 528 529 530 531 532

	public abstract focus(): void;

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

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

	public abstract isFocused(): boolean;

A
Alex Dima 已提交
533
	public getContribution(id: string): editorCommon.IEditorContribution {
534 535 536
		return this.contributions[id] || null;
	}

A
Alex Dima 已提交
537
	public addAction(descriptor:editorCommon.IActionDescriptor): void {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
		var action = this._instantiationService.createInstance(DynamicEditorAction, descriptor, this);
		this.contributions[action.getId()] = action;
	}

	public getActions(): IAction[] {
		var result: IAction[] = [];
		var id: string;
		for (id in this.contributions) {
			if (this.contributions.hasOwnProperty(id)) {
				var contribution = <any>this.contributions[id];
				// contribution instanceof IAction
				if (isAction(contribution)) {
					result.push(<IAction>contribution);
				}
			}
		}
		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) {
				this._telemetryService.publicLog('editorActionInvoked', {name: candidate.label} );
				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 已提交
585
	public executeCommand(source: string, command: editorCommon.ICommand): boolean {
586
		// forward to handler dispatcher
A
Alex Dima 已提交
587
		return this._configuration.handlerDispatcher.trigger(source, editorCommon.Handler.ExecuteCommand, command);
588 589
	}

A
Alex Dima 已提交
590
	public executeEdits(source: string, edits: editorCommon.IIdentifiedSingleEditOperation[]): boolean {
591 592 593 594 595 596 597 598 599 600 601 602 603 604
		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 已提交
605
	public executeCommands(source: string, commands: editorCommon.ICommand[]): boolean {
606
		// forward to handler dispatcher
A
Alex Dima 已提交
607
		return this._configuration.handlerDispatcher.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
608 609
	}

A
Alex Dima 已提交
610
	public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any {
611 612 613 614 615 616 617 618
		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 已提交
619
	public getLineDecorations(lineNumber: number): editorCommon.IModelDecoration[] {
620 621 622 623 624 625
		if (!this.model) {
			return null;
		}
		return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
	}

A
Alex Dima 已提交
626
	public deltaDecorations(oldDecorations:string[], newDecorations:editorCommon.IModelDeltaDecoration[]): string[] {
627 628 629 630 631 632 633 634 635 636 637
		if (!this.model) {
			return [];
		}

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

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

A
Alex Dima 已提交
638
	public setDecorations(decorationTypeKey: string, ranges:editorCommon.IRangeWithMessage[]): void {
639 640
		var opts = this._codeEditorService.resolveDecorationType(decorationTypeKey);
		var oldDecorationIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
A
Alex Dima 已提交
641 642
		this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationIds, ranges.map((r) : editorCommon.IModelDeltaDecoration => {
			let decOpts: editorCommon.IModelDecorationOptions;
643
			if (r.hoverMessage) {
A
Alex Dima 已提交
644 645
				// TODO@Alex: avoid objects.clone
				decOpts = objects.clone(opts);
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
				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 已提交
664
	public addTypingListener(character:string, callback: () => void): ListenerUnbind {
665 666 667 668 669 670 671 672 673 674 675 676 677
		if (!this.cursor) {
			return () => {
				// no-op
			};
		}
		this.cursor.addTypingListener(character, callback);
		return () => {
			if (this.cursor) {
				this.cursor.removeTypingListener(character, callback);
			}
		};
	}

A
Alex Dima 已提交
678
	public getLayoutInfo(): editorCommon.IEditorLayoutInfo {
679 680 681
		return this._configuration.editor.layoutInfo;
	}

A
Alex Dima 已提交
682
	_attachModel(model:editorCommon.IModel): void {
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
		this.model = model ? model : null;
		this.listenersToRemove = [];
		this.viewModel = null;
		this.cursor = null;

		if (this.model) {
			this._configuration.resetIndentationOptions();
			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,
				this._configuration.getIndentationOptions().tabSize,
				this._configuration.editor.wrappingInfo.wrappingColumn,
				this._configuration.editor.typicalFullwidthCharacterWidth / this._configuration.editor.typicalHalfwidthCharacterWidth,
A
Alex Dima 已提交
709
				editorCommon.wrappingIndentFromString(this._configuration.editor.wrappingIndent)
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
			);

			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 已提交
725
				convertModelRangeToViewRange: (modelRange:editorCommon.IEditorRange) => {
726 727 728 729 730
					return this.viewModel.convertModelRangeToViewRange(modelRange);
				},
				convertViewToModelPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertViewPositionToModelPosition(lineNumber, column);
				},
A
Alex Dima 已提交
731
				validateViewPosition: (viewLineNumber:number, viewColumn:number, modelPosition:editorCommon.IEditorPosition) => {
732 733
					return this.viewModel.validateViewPosition(viewLineNumber, viewColumn, modelPosition);
				},
A
Alex Dima 已提交
734
				validateViewRange: (viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:editorCommon.IEditorRange) => {
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
					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 已提交
757 758
						case editorCommon.EventType.ViewFocusGained:
							this.emit(editorCommon.EventType.EditorTextFocus);
759
							// In IE, the focus is not synchronous, so we give it a little help
A
Alex Dima 已提交
760
							this.emit(editorCommon.EventType.EditorFocus, {});
761 762 763 764 765 766 767 768 769 770
							break;

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

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

A
Alex Dima 已提交
771 772
						case editorCommon.EventType.ViewFocusLost:
							this.emit(editorCommon.EventType.EditorTextBlur);
773 774
							break;

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

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

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

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

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

A
Alex Dima 已提交
795 796
						case editorCommon.EventType.MouseLeave:
							this.emit(editorCommon.EventType.MouseLeave, e);
797 798
							break;

A
Alex Dima 已提交
799 800
						case editorCommon.EventType.KeyDown:
							this.emit(editorCommon.EventType.KeyDown, e);
801 802
							break;

A
Alex Dima 已提交
803 804
						case editorCommon.EventType.ViewLayoutChanged:
							this.emit(editorCommon.EventType.EditorLayout, e);
805 806 807 808 809 810 811 812 813 814 815 816 817 818
							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 已提交
819 820
						case editorCommon.EventType.ModelDecorationsChanged:
							this.emit(editorCommon.EventType.ModelDecorationsChanged, e);
821 822
							break;

A
Alex Dima 已提交
823
						case editorCommon.EventType.ModelModeChanged:
824 825
							this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
							this._langIdKey.set(this.model.getMode().getId());
A
Alex Dima 已提交
826
							this.emit(editorCommon.EventType.ModelModeChanged, e);
827 828
							break;

A
Alex Dima 已提交
829 830
						case editorCommon.EventType.ModelModeSupportChanged:
							this.emit(editorCommon.EventType.ModelModeSupportChanged, e);
831 832
							break;

A
Alex Dima 已提交
833
						case editorCommon.EventType.ModelContentChanged:
834
							// TODO@Alex
A
Alex Dima 已提交
835
							this.emit(editorCommon.EventType.ModelContentChanged, e);
836 837 838
							this.emit('change', {});
							break;

A
Alex Dima 已提交
839
						case editorCommon.EventType.ModelDispose:
840 841 842 843 844 845 846 847 848 849
							// 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 已提交
850
			var _hasNonEmptySelection = (e: editorCommon.ICursorSelectionChangedEvent) => {
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
				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 已提交
866 867
						case editorCommon.EventType.CursorPositionChanged:
							var cursorPositionChangedEvent = <editorCommon.ICursorPositionChangedEvent>e;
868 869
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorPositionChangedEvent.secondaryPositions.length > 0);
A
Alex Dima 已提交
870
							this.emit(editorCommon.EventType.CursorPositionChanged, e);
871 872
							break;

A
Alex Dima 已提交
873 874
						case editorCommon.EventType.CursorSelectionChanged:
							var cursorSelectionChangedEvent = <editorCommon.ICursorSelectionChangedEvent>e;
875 876 877 878
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorSelectionChangedEvent.secondarySelections.length > 0);
							updateHasNonEmptySelection = true;
							hasNonEmptySelection = _hasNonEmptySelection(cursorSelectionChangedEvent);
A
Alex Dima 已提交
879
							this.emit(editorCommon.EventType.CursorSelectionChanged, e);
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 908 909 910
							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 已提交
911
	protected abstract _getViewInternalEventBus(): IEventEmitter;
912

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

A
Alex Dima 已提交
920
	protected _detachModel(): editorCommon.IModel {
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 947 948 949
		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;
	}
}