commonCodeEditor.ts 32.8 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';

A
Alex Dima 已提交
7
import {IAction, IActionProvider, isAction} from 'vs/base/common/actions';
8
import {onUnexpectedError} from 'vs/base/common/errors';
A
Alex Dima 已提交
9
import {EventEmitter, IEventEmitter} from 'vs/base/common/eventEmitter';
J
Joao Moreno 已提交
10
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
11 12 13
import * as objects from 'vs/base/common/objects';
import * as timer from 'vs/base/common/timer';
import {TPromise} from 'vs/base/common/winjs.base';
14
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
15
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
A
Alex Dima 已提交
16 17
import {IKeybindingContextKey, IKeybindingScopeLocation, IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
18
import {CommonEditorConfiguration} from 'vs/editor/common/config/commonEditorConfig';
A
Alex Dima 已提交
19
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
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';
32
import {ViewModel} from 'vs/editor/common/viewModel/viewModelImpl';
33 34 35

var EDITOR_ID = 0;

A
Alex Dima 已提交
36
export abstract class CommonCodeEditor extends EventEmitter implements IActionProvider, editorCommon.ICommonCodeEditor {
37

A
Alex Dima 已提交
38 39 40 41 42
	public onDidChangeModelRawContent(listener: (e:editorCommon.IModelContentChangedEvent)=>void): IDisposable {
		return this.addListener2(editorCommon.EventType.ModelRawContentChanged, listener);
	}
	public onDidChangeModelContent(listener: (e:editorCommon.IModelContentChangedEvent2)=>void): IDisposable {
		return this.addListener2(editorCommon.EventType.ModelContentChanged2, listener);
A
Alex Dima 已提交
43
	}
A
Alex Dima 已提交
44
	public onDidChangeModelMode(listener: (e:editorCommon.IModelModeChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
45 46
		return this.addListener2(editorCommon.EventType.ModelModeChanged, listener);
	}
A
Alex Dima 已提交
47
	public onDidChangeModelOptions(listener: (e:editorCommon.IModelOptionsChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
48 49
		return this.addListener2(editorCommon.EventType.ModelOptionsChanged, listener);
	}
A
Alex Dima 已提交
50
	public onDidChangeModelModeSupport(listener: (e:editorCommon.IModeSupportChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
51 52
		return this.addListener2(editorCommon.EventType.ModelModeSupportChanged, listener);
	}
A
Alex Dima 已提交
53
	public onDidChangeModelDecorations(listener: (e:editorCommon.IModelDecorationsChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
54 55
		return this.addListener2(editorCommon.EventType.ModelDecorationsChanged, listener);
	}
A
Alex Dima 已提交
56
	public onDidChangeConfiguration(listener: (e:editorCommon.IConfigurationChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
57 58
		return this.addListener2(editorCommon.EventType.ConfigurationChanged, listener);
	}
A
Alex Dima 已提交
59
	public onDidChangeModel(listener: (e:editorCommon.IModelChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
60 61
		return this.addListener2(editorCommon.EventType.ModelChanged, listener);
	}
A
Alex Dima 已提交
62
	public onDidChangeCursorPosition(listener: (e:editorCommon.ICursorPositionChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
63 64
		return this.addListener2(editorCommon.EventType.CursorPositionChanged, listener);
	}
A
Alex Dima 已提交
65
	public onDidChangeCursorSelection(listener: (e:editorCommon.ICursorSelectionChangedEvent)=>void): IDisposable {
A
Alex Dima 已提交
66 67
		return this.addListener2(editorCommon.EventType.CursorSelectionChanged, listener);
	}
A
Alex Dima 已提交
68
	public onDidFocusEditorText(listener: ()=>void): IDisposable {
A
Alex Dima 已提交
69 70
		return this.addListener2(editorCommon.EventType.EditorTextFocus, listener);
	}
A
Alex Dima 已提交
71
	public onDidBlurEditorText(listener: ()=>void): IDisposable {
A
Alex Dima 已提交
72 73
		return this.addListener2(editorCommon.EventType.EditorTextBlur, listener);
	}
A
Alex Dima 已提交
74
	public onDidFocusEditor(listener: ()=>void): IDisposable {
A
Alex Dima 已提交
75 76
		return this.addListener2(editorCommon.EventType.EditorFocus, listener);
	}
A
Alex Dima 已提交
77
	public onDidBlurEditor(listener: ()=>void): IDisposable {
A
Alex Dima 已提交
78 79 80 81 82 83
		return this.addListener2(editorCommon.EventType.EditorBlur, listener);
	}
	public onDidDispose(listener: ()=>void): IDisposable {
		return this.addListener2(editorCommon.EventType.Disposed, listener);
	}

84 85 86 87 88 89 90 91 92
	protected domElement: IKeybindingScopeLocation;

	protected id:number;

	_lifetimeDispose: IDisposable[];
	_configuration:CommonEditorConfiguration;

	_telemetryService:ITelemetryService;

A
Alex Dima 已提交
93
	protected contributions:{ [key:string]:editorCommon.IEditorContribution; };
94 95

	// --- Members logically associated to a model
A
Alex Dima 已提交
96
	protected model:editorCommon.IModel;
A
Alex Dima 已提交
97
	protected listenersToRemove:IDisposable[];
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
	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,
118
		options:editorCommon.IEditorOptions,
119 120 121 122 123 124 125
		instantiationService: IInstantiationService,
		codeEditorService: ICodeEditorService,
		keybindingService: IKeybindingService,
		telemetryService: ITelemetryService
	) {
		super();

A
Alex Dima 已提交
126 127
		this.domElement = domElement;

128 129 130
		this.id = (++EDITOR_ID);
		this._codeEditorService = codeEditorService;

A
Alex Dima 已提交
131
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.ctor');
132 133 134 135 136

		this._lifetimeDispose = [];

		this._keybindingService = keybindingService.createScoped(domElement);
		this._editorIdContextKey = this._keybindingService.createKey('editorId', this.getId());
A
Alex Dima 已提交
137 138 139 140 141
		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);
142 143 144 145 146

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

		options = options || {};
147 148 149 150
		if (typeof options.ariaLabel === 'undefined') {
			options.ariaLabel = DefaultConfig.editor.ariaLabel;
		}

151
		this._configuration = this._createConfiguration(options);
152 153 154
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		}
A
Alex Dima 已提交
155
		this._lifetimeDispose.push(this._configuration.onDidChange((e) => this.emit(editorCommon.EventType.ConfigurationChanged, e)));
156 157

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

160
		this._attachModel(null);
161 162 163 164 165 166 167 168 169 170

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


		timerEvent.stop();

		this._codeEditorService.addCodeEditor(this);
	}

171
	protected abstract _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration;
172 173 174 175 176 177

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

	public getEditorType(): string {
A
Alex Dima 已提交
178
		return editorCommon.EditorType.ICodeEditor;
179 180 181 182 183 184 185 186
	}

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

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

A
Alex Dima 已提交
189 190 191 192
		let keys = Object.keys(this.contributions);
		for (let i = 0, len = keys.length; i < len; i++) {
			let contributionId = keys[i];
			this.contributions[contributionId].dispose();
193
		}
A
Alex Dima 已提交
194

195 196 197 198 199
		this.contributions = {};

		this._postDetachModelCleanup(this._detachModel());
		this._configuration.dispose();
		this._keybindingService.dispose();
A
Alex Dima 已提交
200
		this.emit(editorCommon.EventType.Disposed);
201 202 203
		super.dispose();
	}

A
Alex Dima 已提交
204
	public captureState(...flags:editorCommon.CodeEditorStateFlag[]): editorCommon.ICodeEditorState {
205 206 207
		return new EditorState(this, flags);
	}

A
Alex Dima 已提交
208
	public updateOptions(newOptions:editorCommon.IEditorOptions): void {
209 210 211 212 213 214 215 216
		this._configuration.updateOptions(newOptions);
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		} else {
			this._editorTabMovesFocusKey.reset();
		}
	}

217
	public getConfiguration(): editorCommon.InternalEditorOptions {
A
Alex Dima 已提交
218
		return this._configuration.editorClone;
219 220
	}

A
Alex Dima 已提交
221
	public getRawConfiguration(): editorCommon.IEditorOptions {
222 223 224 225 226 227
		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 已提交
228
			var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
229
			if (options && options.lineEnding && options.lineEnding === '\n') {
A
Alex Dima 已提交
230
				eolPreference = editorCommon.EndOfLinePreference.LF;
231
			} else if (options  && options.lineEnding && options.lineEnding === '\r\n') {
A
Alex Dima 已提交
232
				eolPreference = editorCommon.EndOfLinePreference.CRLF;
233 234 235 236 237 238 239 240 241 242 243 244
			}
			return this.model.getValue(eolPreference, preserveBOM);
		}
		return '';
	}

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

A
Alex Dima 已提交
245
	public getModel(): editorCommon.IModel {
246 247 248
		return this.model;
	}

A
Alex Dima 已提交
249
	public setModel(model:editorCommon.IModel = null): void {
250 251 252 253 254
		if (this.model === model) {
			// Current model is the new model
			return;
		}

A
Alex Dima 已提交
255
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.setModel');
256 257 258 259 260 261 262 263

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

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

		if (detachedModel) {
264
			oldModelUrl = detachedModel.uri.toString();
265 266
		}
		if (model) {
267
			newModelUrl = model.uri.toString();
268
		}
A
Alex Dima 已提交
269
		var e: editorCommon.IModelChangedEvent = {
270 271 272 273 274 275
			oldModelUrl: oldModelUrl,
			newModelUrl: newModelUrl
		};

		timerEvent.stop();

A
Alex Dima 已提交
276
		this.emit(editorCommon.EventType.ModelChanged, e);
277 278 279
		this._postDetachModelCleanup(detachedModel);
	}

280
	public abstract getCenteredRangeInViewport(): Range;
281

A
Alex Dima 已提交
282
	public getVisibleColumnFromPosition(rawPosition:editorCommon.IPosition): number {
283 284 285 286
		if (!this.model) {
			return rawPosition.column;
		}

287 288
		let position = this.model.validatePosition(rawPosition);
		let tabSize = this.model.getOptions().tabSize;
289

290
		return CursorMoveHelper.visibleColumnFromColumn(this.model, position.lineNumber, position.column, tabSize) + 1;
291 292
	}

A
Alex Dima 已提交
293
	public getPosition(): Position {
294 295 296 297 298 299
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getPosition().clone();
	}

A
Alex Dima 已提交
300
	public setPosition(position:editorCommon.IPosition, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
		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 已提交
318
	private _sendRevealRange(range: editorCommon.IRange, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
319 320 321 322 323 324 325 326
		if (!this.model || !this.cursor) {
			return;
		}
		if (!Range.isIRange(range)) {
			throw new Error('Invalid arguments');
		}
		var validatedRange = this.model.validateRange(range);

A
Alex Dima 已提交
327
		var revealRangeEvent: editorCommon.ICursorRevealRangeEvent = {
328 329 330 331 332
			range: validatedRange,
			viewRange: null,
			verticalType: verticalType,
			revealHorizontal: revealHorizontal
		};
A
Alex Dima 已提交
333
		this.cursor.emit(editorCommon.EventType.CursorRevealRange, revealRangeEvent);
334 335 336 337 338 339 340 341
	}

	public revealLine(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
342
		}, editorCommon.VerticalRevealType.Simple, false);
343 344 345 346 347 348 349 350
	}

	public revealLineInCenter(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
351
		}, editorCommon.VerticalRevealType.Center, false);
352 353 354 355 356 357 358 359
	}

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

A
Alex Dima 已提交
363
	public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean=false, revealHorizontal:boolean=false): 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
		}, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
373 374
	}

A
Alex Dima 已提交
375
	public revealPositionInCenter(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.Center, true);
385 386
	}

A
Alex Dima 已提交
387
	public revealPositionInCenterIfOutsideViewport(position: editorCommon.IPosition): void {
388 389 390 391 392 393 394 395
		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 已提交
396
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
397 398
	}

399
	public getSelection(): Selection {
400 401 402 403 404 405
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getSelection().clone();
	}

406
	public getSelections(): Selection[] {
407 408 409 410
		if (!this.cursor) {
			return null;
		}
		var selections = this.cursor.getSelections();
411
		var result:Selection[] = [];
412 413 414 415 416 417
		for (var i = 0, len = selections.length; i < len; i++) {
			result[i] = selections[i].clone();
		}
		return result;
	}

A
Alex Dima 已提交
418
	public setSelection(range:editorCommon.IRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
419
	public setSelection(editorRange:Range, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
A
Alex Dima 已提交
420
	public setSelection(selection:editorCommon.ISelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
421
	public setSelection(editorSelection:Selection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
422 423 424 425 426 427 428 429 430
	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 已提交
431
			this._setSelectionImpl(<editorCommon.ISelection>something, reveal, revealVerticalInCenter, revealHorizontal);
432 433
		} else if (isRange) {
			// act as if it was an IRange
A
Alex Dima 已提交
434
			var selection:editorCommon.ISelection = {
435 436 437 438 439 440 441 442 443
				selectionStartLineNumber: something.startLineNumber,
				selectionStartColumn: something.startColumn,
				positionLineNumber: something.endLineNumber,
				positionColumn: something.endColumn
			};
			this._setSelectionImpl(selection, reveal, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
444
	private _setSelectionImpl(sel:editorCommon.ISelection, reveal:boolean, revealVerticalInCenter:boolean, revealHorizontal:boolean): void {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
		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 已提交
461
		}, editorCommon.VerticalRevealType.Simple, false);
462 463 464 465 466 467 468 469
	}

	public revealLinesInCenter(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
470
		}, editorCommon.VerticalRevealType.Center, false);
471 472 473 474 475 476 477 478
	}

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

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

A
Alex Dima 已提交
486 487
	public revealRangeInCenter(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.Center, true);
488 489
	}

A
Alex Dima 已提交
490 491
	public revealRangeInCenterIfOutsideViewport(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
492 493
	}

A
Alex Dima 已提交
494
	public setSelections(ranges: editorCommon.ISelection[]): void {
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);
	}

509 510
	public abstract getScrollWidth(): number;
	public abstract getScrollLeft(): number;
511

512
	public abstract getScrollHeight(): number;
513 514 515
	public abstract getScrollTop(): number;

	public abstract setScrollLeft(newScrollLeft:number): void;
516 517
	public abstract setScrollTop(newScrollTop:number): void;
	public abstract setScrollPosition(position: editorCommon.INewScrollPosition): void;
518

A
Alex Dima 已提交
519 520
	public abstract saveViewState(): editorCommon.ICodeEditorViewState;
	public abstract restoreViewState(state:editorCommon.IEditorViewState): void;
521 522 523 524 525 526 527

	public onVisible(): void {
	}

	public onHide(): void {
	}

A
Alex Dima 已提交
528
	public abstract layout(dimension?:editorCommon.IDimension): void;
529 530

	public abstract focus(): void;
531 532
	public abstract beginForcedWidgetFocus(): void;
	public abstract endForcedWidgetFocus(): void;
533
	public abstract isFocused(): boolean;
534 535
	public abstract hasWidgetFocus(): boolean;

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

A
Alex Dima 已提交
540
	public addAction(descriptor:editorCommon.IActionDescriptor): void {
541 542 543 544 545 546 547
		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!');
		}
548 549 550 551 552
		var action = this._instantiationService.createInstance(DynamicEditorAction, descriptor, this);
		this.contributions[action.getId()] = action;
	}

	public getActions(): IAction[] {
A
Alex Dima 已提交
553 554 555 556 557 558 559 560 561
		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);
562 563
			}
		}
A
Alex Dima 已提交
564

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
		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 {
580
		payload = payload || {};
581 582 583
		var candidate = this.getAction(handlerId);
		if(candidate !== null) {
			if (candidate.enabled) {
584
				this._telemetryService.publicLog('editorActionInvoked', {name: candidate.label, id: candidate.id} );
585 586 587
				TPromise.as(candidate.run()).done(null, onUnexpectedError);
			}
		} else {
A
Alex Dima 已提交
588 589
			if (!this.cursor) {
				return;
590
			}
A
Alex Dima 已提交
591
			this.cursor.trigger(source, handlerId, payload);
592 593 594
		}
	}

A
Alex Dima 已提交
595 596 597 598 599
	public executeCommand(source: string, command: editorCommon.ICommand): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command);
600 601
	}

A
Alex Dima 已提交
602
	public executeEdits(source: string, edits: editorCommon.IIdentifiedSingleEditOperation[]): boolean {
603 604 605 606 607 608 609 610
		if (!this.cursor) {
			// no view, no cursor
			return false;
		}
		if (this._configuration.editor.readOnly) {
			// read only editor => sorry!
			return false;
		}
611
		this.model.pushStackElement();
612 613 614
		this.model.pushEditOperations(this.cursor.getSelections(), edits, () => {
			return this.cursor.getSelections();
		});
615
		this.model.pushStackElement();
616 617 618
		return true;
	}

A
Alex Dima 已提交
619 620 621 622 623
	public executeCommands(source: string, commands: editorCommon.ICommand[]): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
624 625
	}

A
Alex Dima 已提交
626
	public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any {
627 628 629 630 631 632 633 634
		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 已提交
635
	public getLineDecorations(lineNumber: number): editorCommon.IModelDecoration[] {
636 637 638 639 640 641
		if (!this.model) {
			return null;
		}
		return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
	}

A
Alex Dima 已提交
642
	public deltaDecorations(oldDecorations:string[], newDecorations:editorCommon.IModelDeltaDecoration[]): string[] {
643 644 645 646 647 648 649 650 651 652 653
		if (!this.model) {
			return [];
		}

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

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

A
Alex Dima 已提交
654
	public setDecorations(decorationTypeKey: string, ranges:editorCommon.IRangeWithMessage[]): void {
655 656
		var opts = this._codeEditorService.resolveDecorationType(decorationTypeKey);
		var oldDecorationIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
A
Alex Dima 已提交
657 658
		this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationIds, ranges.map((r) : editorCommon.IModelDeltaDecoration => {
			let decOpts: editorCommon.IModelDecorationOptions;
659
			if (r.hoverMessage) {
A
Alex Dima 已提交
660 661
				// TODO@Alex: avoid objects.clone
				decOpts = objects.clone(opts);
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
				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 已提交
680
	public addTypingListener(character:string, callback: () => void): IDisposable {
681
		if (!this.cursor) {
A
Alex Dima 已提交
682 683 684 685
			return {
				dispose: () => {
					// no-op
				}
686 687 688
			};
		}
		this.cursor.addTypingListener(character, callback);
A
Alex Dima 已提交
689 690 691 692 693
		return {
			dispose: () => {
				if (this.cursor) {
					this.cursor.removeTypingListener(character, callback);
				}
694 695 696 697
			}
		};
	}

698
	public getLayoutInfo(): editorCommon.EditorLayoutInfo {
699 700 701
		return this._configuration.editor.layoutInfo;
	}

A
Alex Dima 已提交
702
	_attachModel(model:editorCommon.IModel): void {
703 704 705 706 707 708 709 710
		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());
A
Alex Dima 已提交
711
			this._configuration.setIsDominatedByLongLines(this.model.isDominatedByLongLines());
712 713 714 715

			this.model.onBeforeAttached();

			var hardWrappingLineMapperFactory = new CharacterHardWrappingLineMapperFactory(
716 717 718
				this._configuration.editor.wrappingInfo.wordWrapBreakBeforeCharacters,
				this._configuration.editor.wrappingInfo.wordWrapBreakAfterCharacters,
				this._configuration.editor.wrappingInfo.wordWrapBreakObtrusiveCharacters
719 720 721 722 723
			);

			var linesCollection = new SplitLinesCollection(
				this.model,
				hardWrappingLineMapperFactory,
724
				this.model.getOptions().tabSize,
725
				this._configuration.editor.wrappingInfo.wrappingColumn,
726
				this._configuration.editor.fontInfo.typicalFullwidthCharacterWidth / this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,
727
				this._configuration.editor.wrappingInfo.wrappingIndent
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
			);

			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);
				},
743
				convertModelRangeToViewRange: (modelRange:Range) => {
744 745 746 747 748
					return this.viewModel.convertModelRangeToViewRange(modelRange);
				},
				convertViewToModelPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertViewPositionToModelPosition(lineNumber, column);
				},
A
Alex Dima 已提交
749 750 751
				convertViewSelectionToModelSelection: (viewSelection:editorCommon.ISelection) => {
					return this.viewModel.convertViewSelectionToModelSelection(viewSelection);
				},
A
Alex Dima 已提交
752
				validateViewPosition: (viewLineNumber:number, viewColumn:number, modelPosition:Position) => {
753 754
					return this.viewModel.validateViewPosition(viewLineNumber, viewColumn, modelPosition);
				},
755
				validateViewRange: (viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:Range) => {
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
					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();

A
Alex Dima 已提交
772
			this.listenersToRemove.push(this._getViewInternalEventBus().addBulkListener2((events) => {
773 774 775 776 777
				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 已提交
778 779
						case editorCommon.EventType.ViewFocusGained:
							this.emit(editorCommon.EventType.EditorTextFocus);
780
							// In IE, the focus is not synchronous, so we give it a little help
A
Alex Dima 已提交
781
							this.emit(editorCommon.EventType.EditorFocus, {});
782 783 784 785 786 787
							break;

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

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

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

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

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

A
Alex Dima 已提交
804 805
						case editorCommon.EventType.KeyUp:
							this.emit(editorCommon.EventType.KeyUp, e);
806 807
							break;

A
Alex Dima 已提交
808 809
						case editorCommon.EventType.MouseMove:
							this.emit(editorCommon.EventType.MouseMove, e);
810 811
							break;

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

A
Alex Dima 已提交
816 817
						case editorCommon.EventType.KeyDown:
							this.emit(editorCommon.EventType.KeyDown, e);
818 819
							break;

A
Alex Dima 已提交
820 821
						case editorCommon.EventType.ViewLayoutChanged:
							this.emit(editorCommon.EventType.EditorLayout, e);
822 823 824 825 826 827 828 829
							break;

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

A
Alex Dima 已提交
830
			this.listenersToRemove.push(this.model.addBulkListener((events) => {
831 832 833 834 835
				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 已提交
836 837
						case editorCommon.EventType.ModelDecorationsChanged:
							this.emit(editorCommon.EventType.ModelDecorationsChanged, e);
838 839
							break;

A
Alex Dima 已提交
840
						case editorCommon.EventType.ModelModeChanged:
841 842
							this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
							this._langIdKey.set(this.model.getMode().getId());
A
Alex Dima 已提交
843
							this.emit(editorCommon.EventType.ModelModeChanged, e);
844 845
							break;

A
Alex Dima 已提交
846 847
						case editorCommon.EventType.ModelModeSupportChanged:
							this.emit(editorCommon.EventType.ModelModeSupportChanged, e);
848 849
							break;

A
Alex Dima 已提交
850 851
						case editorCommon.EventType.ModelRawContentChanged:
							this.emit(editorCommon.EventType.ModelRawContentChanged, e);
852 853
							break;

854 855 856 857
						case editorCommon.EventType.ModelOptionsChanged:
							this.emit(editorCommon.EventType.ModelOptionsChanged, e);
							break;

A
Alex Dima 已提交
858
						case editorCommon.EventType.ModelDispose:
859 860 861 862 863 864 865 866 867 868
							// 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 已提交
869
			var _hasNonEmptySelection = (e: editorCommon.ICursorSelectionChangedEvent) => {
870 871 872 873
				var allSelections = [e.selection].concat(e.secondarySelections);
				return allSelections.some(s => !s.isEmpty());
			};

A
Alex Dima 已提交
874
			this.listenersToRemove.push(this.cursor.addBulkListener2((events) => {
875 876 877 878 879 880 881 882 883 884
				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 已提交
885 886
						case editorCommon.EventType.CursorPositionChanged:
							var cursorPositionChangedEvent = <editorCommon.ICursorPositionChangedEvent>e;
887 888
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorPositionChangedEvent.secondaryPositions.length > 0);
A
Alex Dima 已提交
889
							this.emit(editorCommon.EventType.CursorPositionChanged, e);
890 891
							break;

A
Alex Dima 已提交
892 893
						case editorCommon.EventType.CursorSelectionChanged:
							var cursorSelectionChangedEvent = <editorCommon.ICursorSelectionChangedEvent>e;
894 895 896 897
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorSelectionChangedEvent.secondarySelections.length > 0);
							updateHasNonEmptySelection = true;
							hasNonEmptySelection = _hasNonEmptySelection(cursorSelectionChangedEvent);
A
Alex Dima 已提交
898
							this.emit(editorCommon.EventType.CursorSelectionChanged, e);
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
							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 已提交
930
	protected abstract _getViewInternalEventBus(): IEventEmitter;
931

A
Alex Dima 已提交
932
	_postDetachModelCleanup(detachedModel:editorCommon.IModel): void {
933 934 935 936 937 938
		if (detachedModel) {
			this._decorationTypeKeysToIds = {};
			detachedModel.removeAllDecorationsWithOwnerId(this.id);
		}
	}

A
Alex Dima 已提交
939
	protected _detachModel(): editorCommon.IModel {
940 941 942 943 944 945
		if (this.model) {
			this.model.onBeforeDetached();
		}

		this.hasView = false;

A
Alex Dima 已提交
946
		this.listenersToRemove = dispose(this.listenersToRemove);
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

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