commonCodeEditor.ts 36.1 KB
Newer Older
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import {onUnexpectedError} from 'vs/base/common/errors';
A
Alex Dima 已提交
8
import {EventEmitter, IEventEmitter} from 'vs/base/common/eventEmitter';
J
Joao Moreno 已提交
9
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
10 11
import * as timer from 'vs/base/common/timer';
import {TPromise} from 'vs/base/common/winjs.base';
12
import {ServicesAccessor, IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
13
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
14
import {ICommandService} from 'vs/platform/commands/common/commands';
A
Alex Dima 已提交
15
import {IContextKey, IContextKeyServiceTarget, IContextKeyService} from 'vs/platform/contextkey/common/contextkey';
A
Alex Dima 已提交
16
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
17
import {CommonEditorConfiguration} from 'vs/editor/common/config/commonEditorConfig';
A
Alex Dima 已提交
18
import {DefaultConfig} from 'vs/editor/common/config/defaultConfig';
19 20 21
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 已提交
22
import {EditorState} from 'vs/editor/common/core/editorState';
23
import {Position} from 'vs/editor/common/core/position';
A
Alex Dima 已提交
24
import {Range} from 'vs/editor/common/core/range';
25
import {Selection} from 'vs/editor/common/core/selection';
A
Alex Dima 已提交
26
import {DynamicEditorAction} from 'vs/editor/common/editorAction';
A
Alex Dima 已提交
27 28 29 30
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';
31
import {ViewModel} from 'vs/editor/common/viewModel/viewModelImpl';
M
Martin Aeschlimann 已提交
32
import {hash} from 'vs/base/common/hash';
33
import {EditorModeContext} from 'vs/editor/common/modes/editorModeContext';
34

A
Alex Dima 已提交
35 36
import EditorContextKeys = editorCommon.EditorContextKeys;

37 38
var EDITOR_ID = 0;

39
export abstract class CommonCodeEditor extends EventEmitter implements editorCommon.ICommonCodeEditor {
40

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

A
Alex Dima 已提交
87
	protected domElement: IContextKeyServiceTarget;
88 89 90 91 92 93 94 95

	protected id:number;

	_lifetimeDispose: IDisposable[];
	_configuration:CommonEditorConfiguration;

	_telemetryService:ITelemetryService;

A
Alex Dima 已提交
96 97
	protected _contributions:{ [key:string]:editorCommon.IEditorContribution; };
	protected _actions:{ [key:string]:editorCommon.IEditorAction; };
98 99

	// --- Members logically associated to a model
A
Alex Dima 已提交
100
	protected model:editorCommon.IModel;
A
Alex Dima 已提交
101
	protected listenersToRemove:IDisposable[];
102 103 104 105 106 107
	protected hasView: boolean;

	protected viewModel:ViewModel;
	protected cursor:Cursor;

	protected _instantiationService: IInstantiationService;
108
	protected _commandService: ICommandService;
109
	protected _contextKeyService: IContextKeyService;
110

111 112 113
	/**
	 * map from "parent" decoration type to live decoration ids.
	 */
114 115
	private _decorationTypeKeysToIds: {[decorationTypeKey:string]:string[]};
	private _decorationTypeSubtypes: {[decorationTypeKey:string]:{ [subtype:string]:boolean}};
116 117

	private _codeEditorService: ICodeEditorService;
A
Alex Dima 已提交
118 119 120 121 122 123 124
	private _editorIdContextKey: IContextKey<string>;
	protected _editorFocusContextKey: IContextKey<boolean>;
	private _editorTabMovesFocusKey: IContextKey<boolean>;
	private _editorReadonly: IContextKey<boolean>;
	private _hasMultipleSelectionsKey: IContextKey<boolean>;
	private _hasNonEmptySelectionKey: IContextKey<boolean>;
	private _langIdKey: IContextKey<string>;
125 126

	constructor(
A
Alex Dima 已提交
127
		domElement: IContextKeyServiceTarget,
128
		options: editorCommon.IEditorOptions,
129 130
		instantiationService: IInstantiationService,
		codeEditorService: ICodeEditorService,
131
		commandService: ICommandService,
132
		contextKeyService: IContextKeyService,
133 134 135 136
		telemetryService: ITelemetryService
	) {
		super();

A
Alex Dima 已提交
137 138
		this.domElement = domElement;

139 140 141
		this.id = (++EDITOR_ID);
		this._codeEditorService = codeEditorService;

A
Alex Dima 已提交
142
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.ctor');
143

144
		// listeners that are kept during the whole editor lifetime
145 146
		this._lifetimeDispose = [];

147
		this._commandService = commandService;
148
		this._contextKeyService = contextKeyService.createScoped(this.domElement);
149 150 151 152 153 154 155 156
		this._editorIdContextKey = this._contextKeyService.createKey('editorId', this.getId());
		this._editorFocusContextKey = EditorContextKeys.Focus.bindTo(this._contextKeyService);
		this._editorTabMovesFocusKey = EditorContextKeys.TabMovesFocus.bindTo(this._contextKeyService);
		this._editorReadonly = EditorContextKeys.ReadOnly.bindTo(this._contextKeyService);
		this._hasMultipleSelectionsKey = EditorContextKeys.HasMultipleSelections.bindTo(this._contextKeyService);
		this._hasNonEmptySelectionKey = EditorContextKeys.HasNonEmptySelection.bindTo(this._contextKeyService);
		this._langIdKey = EditorContextKeys.LanguageId.bindTo(this._contextKeyService);
		this._lifetimeDispose.push(new EditorModeContext(this, this._contextKeyService));
157 158

		this._decorationTypeKeysToIds = {};
159
		this._decorationTypeSubtypes = {};
160 161

		options = options || {};
162 163 164 165
		if (typeof options.ariaLabel === 'undefined') {
			options.ariaLabel = DefaultConfig.editor.ariaLabel;
		}

166
		this._configuration = this._createConfiguration(options);
167 168 169
		if (this._configuration.editor.tabFocusMode) {
			this._editorTabMovesFocusKey.set(true);
		}
170
		this._editorReadonly.set(this._configuration.editor.readOnly);
171 172 173 174 175 176 177 178
		this._lifetimeDispose.push(this._configuration.onDidChange((e) => {
			if (this._configuration.editor.tabFocusMode) {
				this._editorTabMovesFocusKey.set(true);
			} else {
				this._editorTabMovesFocusKey.reset();
			}
			this.emit(editorCommon.EventType.ConfigurationChanged, e);
		}));
179 180

		this._telemetryService = telemetryService;
181
		this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
182

183
		this._attachModel(null);
184

A
Alex Dima 已提交
185 186
		this._contributions = {};
		this._actions = {};
187 188 189 190 191 192

		timerEvent.stop();

		this._codeEditorService.addCodeEditor(this);
	}

193
	protected abstract _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration;
194 195 196 197 198 199

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

	public getEditorType(): string {
A
Alex Dima 已提交
200
		return editorCommon.EditorType.ICodeEditor;
201 202 203 204 205 206 207 208
	}

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

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

A
Alex Dima 已提交
211
		let keys = Object.keys(this._contributions);
A
Alex Dima 已提交
212 213
		for (let i = 0, len = keys.length; i < len; i++) {
			let contributionId = keys[i];
A
Alex Dima 已提交
214
			this._contributions[contributionId].dispose();
215
		}
A
Alex Dima 已提交
216
		this._contributions = {};
A
Alex Dima 已提交
217

A
Alex Dima 已提交
218 219
		// editor actions don't need to be disposed
		this._actions = {};
220 221 222

		this._postDetachModelCleanup(this._detachModel());
		this._configuration.dispose();
223
		this._contextKeyService.dispose();
A
Alex Dima 已提交
224
		this.emit(editorCommon.EventType.Disposed);
225 226 227
		super.dispose();
	}

A
Alex Dima 已提交
228
	public captureState(...flags:editorCommon.CodeEditorStateFlag[]): editorCommon.ICodeEditorState {
229 230 231
		return new EditorState(this, flags);
	}

232 233 234 235
	public invokeWithinContext<T>(fn:(accessor:ServicesAccessor)=>T): T {
		return this._instantiationService.invokeFunction(fn);
	}

A
Alex Dima 已提交
236
	public updateOptions(newOptions:editorCommon.IEditorOptions): void {
237
		this._configuration.updateOptions(newOptions);
238
		this._editorReadonly.set(this._configuration.editor.readOnly);
239
		this._editorTabMovesFocusKey.set(this._configuration.editor.tabFocusMode);
240 241
	}

242
	public getConfiguration(): editorCommon.InternalEditorOptions {
A
Alex Dima 已提交
243
		return this._configuration.editorClone;
244 245
	}

A
Alex Dima 已提交
246
	public getRawConfiguration(): editorCommon.IEditorOptions {
247 248 249 250 251 252
		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 已提交
253
			var eolPreference = editorCommon.EndOfLinePreference.TextDefined;
254
			if (options && options.lineEnding && options.lineEnding === '\n') {
A
Alex Dima 已提交
255
				eolPreference = editorCommon.EndOfLinePreference.LF;
256
			} else if (options  && options.lineEnding && options.lineEnding === '\r\n') {
A
Alex Dima 已提交
257
				eolPreference = editorCommon.EndOfLinePreference.CRLF;
258 259 260 261 262 263 264 265 266 267 268 269
			}
			return this.model.getValue(eolPreference, preserveBOM);
		}
		return '';
	}

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

A
Alex Dima 已提交
270
	public getModel(): editorCommon.IModel {
271 272 273
		return this.model;
	}

A
Alex Dima 已提交
274
	public setModel(model:editorCommon.IModel = null): void {
275 276 277 278 279
		if (this.model === model) {
			// Current model is the new model
			return;
		}

A
Alex Dima 已提交
280
		var timerEvent = timer.start(timer.Topic.EDITOR, 'CodeEditor.setModel');
281 282 283 284

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

A
Alex Dima 已提交
285
		var e: editorCommon.IModelChangedEvent = {
A
Alex Dima 已提交
286 287
			oldModelUrl: detachedModel ? detachedModel.uri : null,
			newModelUrl: model ? model.uri : null
288 289 290 291
		};

		timerEvent.stop();

A
Alex Dima 已提交
292
		this.emit(editorCommon.EventType.ModelChanged, e);
293 294 295
		this._postDetachModelCleanup(detachedModel);
	}

296
	public abstract getCenteredRangeInViewport(): Range;
297

298
	public abstract getCompletelyVisibleLinesRangeInViewport(): Range;
299

A
Alex Dima 已提交
300
	public getVisibleColumnFromPosition(rawPosition:editorCommon.IPosition): number {
301 302 303 304
		if (!this.model) {
			return rawPosition.column;
		}

305 306
		let position = this.model.validatePosition(rawPosition);
		let tabSize = this.model.getOptions().tabSize;
307

308
		return CursorMoveHelper.visibleColumnFromColumn(this.model, position.lineNumber, position.column, tabSize) + 1;
309 310
	}

A
Alex Dima 已提交
311
	public getPosition(): Position {
312 313 314 315 316 317
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getPosition().clone();
	}

A
Alex Dima 已提交
318
	public setPosition(position:editorCommon.IPosition, reveal:boolean = false, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void {
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
		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 已提交
336
	private _sendRevealRange(range: editorCommon.IRange, verticalType: editorCommon.VerticalRevealType, revealHorizontal: boolean): void {
337 338 339 340 341 342 343 344
		if (!this.model || !this.cursor) {
			return;
		}
		if (!Range.isIRange(range)) {
			throw new Error('Invalid arguments');
		}
		var validatedRange = this.model.validateRange(range);

A
Alex Dima 已提交
345
		var revealRangeEvent: editorCommon.ICursorRevealRangeEvent = {
346 347 348
			range: validatedRange,
			viewRange: null,
			verticalType: verticalType,
349 350
			revealHorizontal: revealHorizontal,
			revealCursor: false
351
		};
A
Alex Dima 已提交
352
		this.cursor.emit(editorCommon.EventType.CursorRevealRange, revealRangeEvent);
353 354 355 356 357 358 359 360
	}

	public revealLine(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
361
		}, editorCommon.VerticalRevealType.Simple, false);
362 363 364 365 366 367 368 369
	}

	public revealLineInCenter(lineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: lineNumber,
			startColumn: 1,
			endLineNumber: lineNumber,
			endColumn: 1
A
Alex Dima 已提交
370
		}, editorCommon.VerticalRevealType.Center, false);
371 372 373 374 375 376 377 378
	}

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

A
Alex Dima 已提交
382
	public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean=false, revealHorizontal:boolean=false): void {
383 384 385 386 387 388 389 390
		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 已提交
391
		}, revealVerticalInCenter ? editorCommon.VerticalRevealType.Center : editorCommon.VerticalRevealType.Simple, revealHorizontal);
392 393
	}

A
Alex Dima 已提交
394
	public revealPositionInCenter(position: editorCommon.IPosition): void {
395 396 397 398 399 400 401 402
		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 已提交
403
		}, editorCommon.VerticalRevealType.Center, true);
404 405
	}

A
Alex Dima 已提交
406
	public revealPositionInCenterIfOutsideViewport(position: editorCommon.IPosition): void {
407 408 409 410 411 412 413 414
		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 已提交
415
		}, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
416 417
	}

418
	public getSelection(): Selection {
419 420 421 422 423 424
		if (!this.cursor) {
			return null;
		}
		return this.cursor.getSelection().clone();
	}

425
	public getSelections(): Selection[] {
426 427 428 429
		if (!this.cursor) {
			return null;
		}
		var selections = this.cursor.getSelections();
430
		var result:Selection[] = [];
431 432 433 434 435 436
		for (var i = 0, len = selections.length; i < len; i++) {
			result[i] = selections[i].clone();
		}
		return result;
	}

A
Alex Dima 已提交
437
	public setSelection(range:editorCommon.IRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
438
	public setSelection(editorRange:Range, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
A
Alex Dima 已提交
439
	public setSelection(selection:editorCommon.ISelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
440
	public setSelection(editorSelection:Selection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void;
441 442 443 444 445 446 447 448 449
	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 已提交
450
			this._setSelectionImpl(<editorCommon.ISelection>something, reveal, revealVerticalInCenter, revealHorizontal);
451 452
		} else if (isRange) {
			// act as if it was an IRange
A
Alex Dima 已提交
453
			var selection:editorCommon.ISelection = {
454 455 456 457 458 459 460 461 462
				selectionStartLineNumber: something.startLineNumber,
				selectionStartColumn: something.startColumn,
				positionLineNumber: something.endLineNumber,
				positionColumn: something.endColumn
			};
			this._setSelectionImpl(selection, reveal, revealVerticalInCenter, revealHorizontal);
		}
	}

A
Alex Dima 已提交
463
	private _setSelectionImpl(sel:editorCommon.ISelection, reveal:boolean, revealVerticalInCenter:boolean, revealHorizontal:boolean): void {
464 465 466
		if (!this.cursor) {
			return;
		}
A
Alex Dima 已提交
467
		var selection = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
468 469 470 471 472 473 474 475 476 477 478 479
		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 已提交
480
		}, editorCommon.VerticalRevealType.Simple, false);
481 482 483 484 485 486 487 488
	}

	public revealLinesInCenter(startLineNumber: number, endLineNumber: number): void {
		this._sendRevealRange({
			startLineNumber: startLineNumber,
			startColumn: 1,
			endLineNumber: endLineNumber,
			endColumn: 1
A
Alex Dima 已提交
489
		}, editorCommon.VerticalRevealType.Center, false);
490 491 492 493 494 495 496 497
	}

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

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

A
Alex Dima 已提交
505 506
	public revealRangeInCenter(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.Center, true);
507 508
	}

A
Alex Dima 已提交
509 510
	public revealRangeInCenterIfOutsideViewport(range: editorCommon.IRange): void {
		this._sendRevealRange(range, editorCommon.VerticalRevealType.CenterIfOutsideViewport, true);
511 512
	}

A
Alex Dima 已提交
513
	public setSelections(ranges: editorCommon.ISelection[]): void {
514 515 516 517 518 519 520 521 522 523 524 525 526 527
		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);
	}

528 529
	public abstract getScrollWidth(): number;
	public abstract getScrollLeft(): number;
530

531
	public abstract getScrollHeight(): number;
532 533 534
	public abstract getScrollTop(): number;

	public abstract setScrollLeft(newScrollLeft:number): void;
535 536
	public abstract setScrollTop(newScrollTop:number): void;
	public abstract setScrollPosition(position: editorCommon.INewScrollPosition): void;
537

A
Alex Dima 已提交
538 539
	public abstract saveViewState(): editorCommon.ICodeEditorViewState;
	public abstract restoreViewState(state:editorCommon.IEditorViewState): void;
540 541 542 543 544 545 546

	public onVisible(): void {
	}

	public onHide(): void {
	}

A
Alex Dima 已提交
547
	public abstract layout(dimension?:editorCommon.IDimension): void;
548 549

	public abstract focus(): void;
550 551
	public abstract beginForcedWidgetFocus(): void;
	public abstract endForcedWidgetFocus(): void;
552
	public abstract isFocused(): boolean;
553 554
	public abstract hasWidgetFocus(): boolean;

A
Alex Dima 已提交
555 556
	public getContribution<T extends editorCommon.IEditorContribution>(id: string): T {
		return <T>(this._contributions[id] || null);
557 558
	}

A
Alex Dima 已提交
559
	public addAction(descriptor:editorCommon.IActionDescriptor): void {
560 561 562 563 564 565 566
		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!');
		}
A
Alex Dima 已提交
567 568
		let action = new DynamicEditorAction(descriptor, this);
		this._actions[action.id] = action;
569 570
	}

A
Alex Dima 已提交
571 572
	public getActions(): editorCommon.IEditorAction[] {
		let result: editorCommon.IEditorAction[] = [];
A
Alex Dima 已提交
573

A
Alex Dima 已提交
574
		let keys = Object.keys(this._actions);
A
Alex Dima 已提交
575 576
		for (let i = 0, len = keys.length; i < len; i++) {
			let id = keys[i];
A
Alex Dima 已提交
577
			result.push(this._actions[id]);
578
		}
A
Alex Dima 已提交
579

580 581 582
		return result;
	}

A
Alex Dima 已提交
583
	public getSupportedActions(): editorCommon.IEditorAction[] {
584
		let result = this.getActions();
585

A
Alex Dima 已提交
586
		result = result.filter(action => action.isSupported());
587 588 589 590

		return result;
	}

A
Alex Dima 已提交
591 592
	public getAction(id:string): editorCommon.IEditorAction {
		return this._actions[id] || null;
593 594 595
	}

	public trigger(source:string, handlerId:string, payload:any): void {
596
		payload = payload || {};
597
		var candidate = this.getAction(handlerId);
A
Alex Dima 已提交
598 599
		if (candidate !== null) {
			TPromise.as(candidate.run()).done(null, onUnexpectedError);
600
		} else {
A
Alex Dima 已提交
601 602
			if (!this.cursor) {
				return;
603
			}
A
Alex Dima 已提交
604
			this.cursor.trigger(source, handlerId, payload);
605 606 607
		}
	}

A
Alex Dima 已提交
608 609 610 611 612
	public executeCommand(source: string, command: editorCommon.ICommand): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommand, command);
613 614
	}

615
	public pushUndoStop(): boolean {
616 617 618 619 620 621 622 623
		if (!this.cursor) {
			// no view, no cursor
			return false;
		}
		if (this._configuration.editor.readOnly) {
			// read only editor => sorry!
			return false;
		}
624
		this.model.pushStackElement();
625 626 627 628 629 630 631 632 633 634 635 636 637
		return true;
	}

	public executeEdits(source: string, edits: editorCommon.IIdentifiedSingleEditOperation[]): boolean {
		if (!this.cursor) {
			// no view, no cursor
			return false;
		}
		if (this._configuration.editor.readOnly) {
			// read only editor => sorry!
			return false;
		}

638 639 640
		this.model.pushEditOperations(this.cursor.getSelections(), edits, () => {
			return this.cursor.getSelections();
		});
641

642 643 644
		return true;
	}

A
Alex Dima 已提交
645 646 647 648 649
	public executeCommands(source: string, commands: editorCommon.ICommand[]): void {
		if (!this.cursor) {
			return;
		}
		this.cursor.trigger(source, editorCommon.Handler.ExecuteCommands, commands);
650 651
	}

A
Alex Dima 已提交
652
	public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any {
653 654 655 656 657 658 659 660
		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 已提交
661
	public getLineDecorations(lineNumber: number): editorCommon.IModelDecoration[] {
662 663 664 665 666 667
		if (!this.model) {
			return null;
		}
		return this.model.getLineDecorations(lineNumber, this.id, this._configuration.editor.readOnly);
	}

A
Alex Dima 已提交
668
	public deltaDecorations(oldDecorations:string[], newDecorations:editorCommon.IModelDeltaDecoration[]): string[] {
669 670 671 672 673 674 675 676 677 678 679
		if (!this.model) {
			return [];
		}

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

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

M
Martin Aeschlimann 已提交
680 681
	public setDecorations(decorationTypeKey: string, decorationOptions:editorCommon.IDecorationOptions[]): void {

682 683 684
		let newDecorationsSubTypes: {[key:string]:boolean}= {};
		let oldDecorationsSubTypes = this._decorationTypeSubtypes[decorationTypeKey] || {};
		this._decorationTypeSubtypes[decorationTypeKey] = newDecorationsSubTypes;
M
Martin Aeschlimann 已提交
685

686
		let newModelDecorations :editorCommon.IModelDeltaDecoration[] = [];
M
Martin Aeschlimann 已提交
687

688
		for (let decorationOption of decorationOptions) {
M
Martin Aeschlimann 已提交
689
			let typeKey = decorationTypeKey;
690 691 692 693
			if (decorationOption.renderOptions) {
				// identify custom reder options by a hash code over all keys and values
				// For custom render options register a decoration type if necessary
				let subType = hash(decorationOption.renderOptions).toString(16);
694 695
				// The fact that `decorationTypeKey` appears in the typeKey has no influence
				// it is just a mechanism to get predictable and unique keys (repeatable for the same options and unique across clients)
M
Martin Aeschlimann 已提交
696
				typeKey = decorationTypeKey + '-' + subType;
697 698 699
				if (!oldDecorationsSubTypes[subType] && !newDecorationsSubTypes[subType]) {
					// decoration type did not exist before, register new one
					this._codeEditorService.registerDecorationType(typeKey, decorationOption.renderOptions, decorationTypeKey);
700
				}
701 702 703 704
				newDecorationsSubTypes[subType] = true;
			}
			let opts = this._codeEditorService.resolveDecorationOptions(typeKey, !!decorationOption.hoverMessage);
			if (decorationOption.hoverMessage) {
705
				opts.hoverMessage = decorationOption.hoverMessage;
M
Martin Aeschlimann 已提交
706
			}
707 708
			newModelDecorations.push({ range: decorationOption.range, options: opts });
		}
M
Martin Aeschlimann 已提交
709

710 711 712 713
		// remove decoration sub types that are no longer used, deregister decoration type if necessary
		for (let subType in oldDecorationsSubTypes) {
			if (!newDecorationsSubTypes[subType]) {
				this._codeEditorService.removeDecorationType(decorationTypeKey + '-' + subType);
M
Martin Aeschlimann 已提交
714 715
			}
		}
716 717 718 719

		// update all decorations
		let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey] || [];
		this._decorationTypeKeysToIds[decorationTypeKey] = this.deltaDecorations(oldDecorationsIds, newModelDecorations);
720 721 722
	}

	public removeDecorations(decorationTypeKey: string): void {
723 724 725 726
		// remove decorations for type and sub type
		let oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
		if (oldDecorationsIds) {
			this.deltaDecorations(oldDecorationsIds, []);
727
		}
728 729 730 731 732 733
		if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
			delete this._decorationTypeKeysToIds[decorationTypeKey];
		}
		if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
			delete this._decorationTypeSubtypes[decorationTypeKey];
		}
734 735
	}

A
Alex Dima 已提交
736
	public addTypingListener(character:string, callback: () => void): IDisposable {
737
		if (!this.cursor) {
A
Alex Dima 已提交
738 739 740 741
			return {
				dispose: () => {
					// no-op
				}
742 743 744
			};
		}
		this.cursor.addTypingListener(character, callback);
A
Alex Dima 已提交
745 746 747 748 749
		return {
			dispose: () => {
				if (this.cursor) {
					this.cursor.removeTypingListener(character, callback);
				}
750 751 752 753
			}
		};
	}

754
	public getLayoutInfo(): editorCommon.EditorLayoutInfo {
755 756 757
		return this._configuration.editor.layoutInfo;
	}

A
Alex Dima 已提交
758
	_attachModel(model:editorCommon.IModel): void {
759 760 761 762 763 764 765 766
		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 已提交
767
			this._configuration.setIsDominatedByLongLines(this.model.isDominatedByLongLines());
768 769 770 771

			this.model.onBeforeAttached();

			var hardWrappingLineMapperFactory = new CharacterHardWrappingLineMapperFactory(
772 773 774
				this._configuration.editor.wrappingInfo.wordWrapBreakBeforeCharacters,
				this._configuration.editor.wrappingInfo.wordWrapBreakAfterCharacters,
				this._configuration.editor.wrappingInfo.wordWrapBreakObtrusiveCharacters
775 776 777 778 779
			);

			var linesCollection = new SplitLinesCollection(
				this.model,
				hardWrappingLineMapperFactory,
780
				this.model.getOptions().tabSize,
781
				this._configuration.editor.wrappingInfo.wrappingColumn,
782
				this._configuration.editor.fontInfo.typicalFullwidthCharacterWidth / this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth,
783
				this._configuration.editor.wrappingInfo.wrappingIndent
784 785 786 787 788 789 790 791 792 793 794 795
			);

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

			var viewModelHelper:IViewModelHelper = {
				viewModel: this.viewModel,
796 797
				getCurrentCompletelyVisibleViewLinesRangeInViewport: () => {
					return this.viewModel.convertModelRangeToViewRange(this.getCompletelyVisibleLinesRangeInViewport());
798
				},
799
				getCurrentCompletelyVisibleModelLinesRangeInViewport: () => {
800
					return this.getCompletelyVisibleLinesRangeInViewport();
801
				},
802 803 804
				convertModelPositionToViewPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertModelPositionToViewPosition(lineNumber, column);
				},
805
				convertModelRangeToViewRange: (modelRange:Range) => {
806 807 808 809 810
					return this.viewModel.convertModelRangeToViewRange(modelRange);
				},
				convertViewToModelPosition: (lineNumber:number, column:number) => {
					return this.viewModel.convertViewPositionToModelPosition(lineNumber, column);
				},
A
Alex Dima 已提交
811 812 813
				convertViewSelectionToModelSelection: (viewSelection:editorCommon.ISelection) => {
					return this.viewModel.convertViewSelectionToModelSelection(viewSelection);
				},
814 815 816
				convertViewRangeToModelRange: (viewRange:Range) => {
					return this.viewModel.convertViewRangeToModelRange(viewRange);
				},
A
Alex Dima 已提交
817
				validateViewPosition: (viewLineNumber:number, viewColumn:number, modelPosition:Position) => {
818 819
					return this.viewModel.validateViewPosition(viewLineNumber, viewColumn, modelPosition);
				},
820
				validateViewRange: (viewStartLineNumber:number, viewStartColumn:number, viewEndLineNumber:number, viewEndColumn:number, modelRange:Range) => {
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
					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 已提交
837
			this.listenersToRemove.push(this._getViewInternalEventBus().addBulkListener2((events) => {
838 839 840 841 842
				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 已提交
843 844
						case editorCommon.EventType.ViewFocusGained:
							this.emit(editorCommon.EventType.EditorTextFocus);
845
							// In IE, the focus is not synchronous, so we give it a little help
A
Alex Dima 已提交
846
							this.emit(editorCommon.EventType.EditorFocus, {});
847 848 849 850 851 852
							break;

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

A
Alex Dima 已提交
853 854
						case editorCommon.EventType.ViewFocusLost:
							this.emit(editorCommon.EventType.EditorTextBlur);
855 856
							break;

A
Alex Dima 已提交
857 858
						case editorCommon.EventType.ContextMenu:
							this.emit(editorCommon.EventType.ContextMenu, e);
859 860
							break;

A
Alex Dima 已提交
861 862
						case editorCommon.EventType.MouseDown:
							this.emit(editorCommon.EventType.MouseDown, e);
863 864
							break;

A
Alex Dima 已提交
865 866
						case editorCommon.EventType.MouseUp:
							this.emit(editorCommon.EventType.MouseUp, e);
867 868
							break;

A
Alex Dima 已提交
869 870
						case editorCommon.EventType.KeyUp:
							this.emit(editorCommon.EventType.KeyUp, e);
871 872
							break;

A
Alex Dima 已提交
873 874
						case editorCommon.EventType.MouseMove:
							this.emit(editorCommon.EventType.MouseMove, e);
875 876
							break;

A
Alex Dima 已提交
877 878
						case editorCommon.EventType.MouseLeave:
							this.emit(editorCommon.EventType.MouseLeave, e);
879 880
							break;

A
Alex Dima 已提交
881 882
						case editorCommon.EventType.KeyDown:
							this.emit(editorCommon.EventType.KeyDown, e);
883 884
							break;

A
Alex Dima 已提交
885 886
						case editorCommon.EventType.ViewLayoutChanged:
							this.emit(editorCommon.EventType.EditorLayout, e);
887 888 889 890 891 892 893 894
							break;

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

A
Alex Dima 已提交
895
			this.listenersToRemove.push(this.model.addBulkListener((events) => {
896 897 898 899 900
				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 已提交
901 902
						case editorCommon.EventType.ModelDecorationsChanged:
							this.emit(editorCommon.EventType.ModelDecorationsChanged, e);
903 904
							break;

A
Alex Dima 已提交
905
						case editorCommon.EventType.ModelModeChanged:
906 907
							this.domElement.setAttribute('data-mode-id', this.model.getMode().getId());
							this._langIdKey.set(this.model.getMode().getId());
A
Alex Dima 已提交
908
							this.emit(editorCommon.EventType.ModelModeChanged, e);
909 910
							break;

A
Alex Dima 已提交
911 912
						case editorCommon.EventType.ModelModeSupportChanged:
							this.emit(editorCommon.EventType.ModelModeSupportChanged, e);
913 914
							break;

A
Alex Dima 已提交
915 916
						case editorCommon.EventType.ModelRawContentChanged:
							this.emit(editorCommon.EventType.ModelRawContentChanged, e);
917 918
							break;

919 920 921 922
						case editorCommon.EventType.ModelContentChanged2:
							this.emit(editorCommon.EventType.ModelContentChanged2, e);
							break;

923 924 925 926
						case editorCommon.EventType.ModelOptionsChanged:
							this.emit(editorCommon.EventType.ModelOptionsChanged, e);
							break;

A
Alex Dima 已提交
927
						case editorCommon.EventType.ModelDispose:
928 929 930 931 932 933 934 935 936 937
							// 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 已提交
938
			var _hasNonEmptySelection = (e: editorCommon.ICursorSelectionChangedEvent) => {
939 940 941 942
				var allSelections = [e.selection].concat(e.secondarySelections);
				return allSelections.some(s => !s.isEmpty());
			};

A
Alex Dima 已提交
943
			this.listenersToRemove.push(this.cursor.addBulkListener2((events) => {
944 945 946 947 948 949 950 951 952 953
				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 已提交
954 955
						case editorCommon.EventType.CursorPositionChanged:
							var cursorPositionChangedEvent = <editorCommon.ICursorPositionChangedEvent>e;
956 957
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorPositionChangedEvent.secondaryPositions.length > 0);
A
Alex Dima 已提交
958
							this.emit(editorCommon.EventType.CursorPositionChanged, e);
959 960
							break;

A
Alex Dima 已提交
961 962
						case editorCommon.EventType.CursorSelectionChanged:
							var cursorSelectionChangedEvent = <editorCommon.ICursorSelectionChangedEvent>e;
963 964 965 966
							updateHasMultipleCursors = true;
							hasMultipleCursors = (cursorSelectionChangedEvent.secondarySelections.length > 0);
							updateHasNonEmptySelection = true;
							hasNonEmptySelection = _hasNonEmptySelection(cursorSelectionChangedEvent);
A
Alex Dima 已提交
967
							this.emit(editorCommon.EventType.CursorSelectionChanged, e);
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
							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 已提交
999
	protected abstract _getViewInternalEventBus(): IEventEmitter;
1000

A
Alex Dima 已提交
1001
	_postDetachModelCleanup(detachedModel:editorCommon.IModel): void {
1002 1003
		if (detachedModel) {
			this._decorationTypeKeysToIds = {};
1004 1005 1006 1007 1008 1009 1010 1011 1012
			if (this._decorationTypeSubtypes) {
				for (let decorationType in this._decorationTypeSubtypes) {
					let subTypes = this._decorationTypeSubtypes[decorationType];
					for (let subType in subTypes) {
						this._codeEditorService.removeDecorationType(decorationType + '-' + subType);
					}
				}
				this._decorationTypeSubtypes = {};
			}
1013 1014 1015 1016
			detachedModel.removeAllDecorationsWithOwnerId(this.id);
		}
	}

A
Alex Dima 已提交
1017
	protected _detachModel(): editorCommon.IModel {
1018 1019 1020 1021 1022 1023
		if (this.model) {
			this.model.onBeforeDetached();
		}

		this.hasView = false;

A
Alex Dima 已提交
1024
		this.listenersToRemove = dispose(this.listenersToRemove);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043

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