extHostTextEditor.ts 16.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

J
Johannes Rieken 已提交
7

8
import { ok } from 'vs/base/common/assert';
9
import { readonly, illegalArgument } from 'vs/base/common/errors';
J
Johannes Rieken 已提交
10 11
import { IdGenerator } from 'vs/base/common/idGenerator';
import { TPromise } from 'vs/base/common/winjs.base';
J
Johannes Rieken 已提交
12 13
import { ExtHostDocumentData } from 'vs/workbench/api/node/extHostDocumentData';
import { Selection, Range, Position, EndOfLine, TextEditorRevealType, TextEditorLineNumbersStyle, SnippetString } from './extHostTypes';
A
Alex Dima 已提交
14
import { ISingleEditOperation } from 'vs/editor/common/model';
15
import * as TypeConverters from './extHostTypeConverters';
16
import { MainThreadTextEditorsShape, IResolvedTextEditorConfiguration, ITextEditorConfigurationUpdate } from './extHost.protocol';
17
import * as vscode from 'vscode';
18 19
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
import { IRange } from 'vs/editor/common/core/range';
E
Erich Gamma 已提交
20

J
Johannes Rieken 已提交
21
export class TextEditorDecorationType implements vscode.TextEditorDecorationType {
E
Erich Gamma 已提交
22

23
	private static readonly _Keys = new IdGenerator('TextEditorDecorationType');
E
Erich Gamma 已提交
24

25
	private _proxy: MainThreadTextEditorsShape;
E
Erich Gamma 已提交
26 27
	public key: string;

28
	constructor(proxy: MainThreadTextEditorsShape, options: vscode.DecorationRenderOptions) {
J
Johannes Rieken 已提交
29
		this.key = TextEditorDecorationType._Keys.nextId();
E
Erich Gamma 已提交
30
		this._proxy = proxy;
31
		this._proxy.$registerTextEditorDecorationType(this.key, <any>/* URI vs Uri */ options);
E
Erich Gamma 已提交
32 33 34
	}

	public dispose(): void {
35
		this._proxy.$removeTextEditorDecorationType(this.key);
E
Erich Gamma 已提交
36 37 38 39
	}
}

export interface ITextEditOperation {
40
	range: vscode.Range;
E
Erich Gamma 已提交
41 42 43 44 45 46 47
	text: string;
	forceMoveMarkers: boolean;
}

export interface IEditData {
	documentVersionId: number;
	edits: ITextEditOperation[];
48
	setEndOfLine: EndOfLine;
J
Johannes Rieken 已提交
49 50
	undoStopBefore: boolean;
	undoStopAfter: boolean;
E
Erich Gamma 已提交
51 52 53 54
}

export class TextEditorEdit {

55 56
	private readonly _document: vscode.TextDocument;
	private readonly _documentVersionId: number;
E
Erich Gamma 已提交
57
	private _collectedEdits: ITextEditOperation[];
58
	private _setEndOfLine: EndOfLine;
59 60
	private readonly _undoStopBefore: boolean;
	private readonly _undoStopAfter: boolean;
E
Erich Gamma 已提交
61

J
Johannes Rieken 已提交
62
	constructor(document: vscode.TextDocument, options: { undoStopBefore: boolean; undoStopAfter: boolean; }) {
63
		this._document = document;
E
Erich Gamma 已提交
64 65
		this._documentVersionId = document.version;
		this._collectedEdits = [];
66
		this._setEndOfLine = 0;
67 68
		this._undoStopBefore = options.undoStopBefore;
		this._undoStopAfter = options.undoStopAfter;
E
Erich Gamma 已提交
69 70 71 72 73
	}

	finalize(): IEditData {
		return {
			documentVersionId: this._documentVersionId,
74
			edits: this._collectedEdits,
75 76 77
			setEndOfLine: this._setEndOfLine,
			undoStopBefore: this._undoStopBefore,
			undoStopAfter: this._undoStopAfter
E
Erich Gamma 已提交
78 79 80 81 82 83 84 85 86 87
		};
	}

	replace(location: Position | Range | Selection, value: string): void {
		let range: Range = null;

		if (location instanceof Position) {
			range = new Range(location, location);
		} else if (location instanceof Range) {
			range = location;
A
Alex Dima 已提交
88
		} else {
E
Erich Gamma 已提交
89 90 91
			throw new Error('Unrecognized location');
		}

92
		this._pushEdit(range, value, false);
E
Erich Gamma 已提交
93 94 95
	}

	insert(location: Position, value: string): void {
96
		this._pushEdit(new Range(location, location), value, true);
E
Erich Gamma 已提交
97 98 99 100 101 102 103
	}

	delete(location: Range | Selection): void {
		let range: Range = null;

		if (location instanceof Range) {
			range = location;
A
Alex Dima 已提交
104
		} else {
E
Erich Gamma 已提交
105 106 107
			throw new Error('Unrecognized location');
		}

108 109 110 111 112
		this._pushEdit(range, null, true);
	}

	private _pushEdit(range: Range, text: string, forceMoveMarkers: boolean): void {
		let validRange = this._document.validateRange(range);
E
Erich Gamma 已提交
113
		this._collectedEdits.push({
114 115 116
			range: validRange,
			text: text,
			forceMoveMarkers: forceMoveMarkers
E
Erich Gamma 已提交
117 118
		});
	}
119

J
Johannes Rieken 已提交
120
	setEndOfLine(endOfLine: EndOfLine): void {
121
		if (endOfLine !== EndOfLine.LF && endOfLine !== EndOfLine.CRLF) {
J
Johannes Rieken 已提交
122
			throw illegalArgument('endOfLine');
123 124 125 126
		}

		this._setEndOfLine = endOfLine;
	}
E
Erich Gamma 已提交
127 128 129
}


J
Johannes Rieken 已提交
130
function deprecated(name: string, message: string = 'Refer to the documentation for further details.') {
E
Erich Gamma 已提交
131 132
	return (target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) => {
		const originalMethod = descriptor.value;
J
Johannes Rieken 已提交
133
		descriptor.value = function (...args: any[]) {
E
Erich Gamma 已提交
134 135
			console.warn(`[Deprecation Warning] method '${name}' is deprecated and should no longer be used. ${message}`);
			return originalMethod.apply(this, args);
B
Benjamin Pasero 已提交
136
		};
E
Erich Gamma 已提交
137 138

		return descriptor;
B
Benjamin Pasero 已提交
139
	};
E
Erich Gamma 已提交
140 141
}

142 143
export class ExtHostTextEditorOptions implements vscode.TextEditorOptions {

144
	private _proxy: MainThreadTextEditorsShape;
145 146 147 148 149 150 151
	private _id: string;

	private _tabSize: number;
	private _insertSpaces: boolean;
	private _cursorStyle: TextEditorCursorStyle;
	private _lineNumbers: TextEditorLineNumbersStyle;

152
	constructor(proxy: MainThreadTextEditorsShape, id: string, source: IResolvedTextEditorConfiguration) {
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
		this._proxy = proxy;
		this._id = id;
		this._accept(source);
	}

	public _accept(source: IResolvedTextEditorConfiguration): void {
		this._tabSize = source.tabSize;
		this._insertSpaces = source.insertSpaces;
		this._cursorStyle = source.cursorStyle;
		this._lineNumbers = source.lineNumbers;
	}

	public get tabSize(): number | string {
		return this._tabSize;
	}

	private _validateTabSize(value: number | string): number | 'auto' | null {
		if (value === 'auto') {
			return 'auto';
		}
		if (typeof value === 'number') {
			let r = Math.floor(value);
			return (r > 0 ? r : null);
		}
		if (typeof value === 'string') {
			let r = parseInt(value, 10);
			if (isNaN(r)) {
				return null;
			}
			return (r > 0 ? r : null);
		}
		return null;
	}

	public set tabSize(value: number | string) {
		let tabSize = this._validateTabSize(value);
		if (tabSize === null) {
			// ignore invalid call
			return;
		}
		if (typeof tabSize === 'number') {
			if (this._tabSize === tabSize) {
				// nothing to do
				return;
			}
			// reflect the new tabSize value immediately
			this._tabSize = tabSize;
		}
		warnOnError(this._proxy.$trySetOptions(this._id, {
			tabSize: tabSize
		}));
	}

	public get insertSpaces(): boolean | string {
		return this._insertSpaces;
	}

	private _validateInsertSpaces(value: boolean | string): boolean | 'auto' {
		if (value === 'auto') {
			return 'auto';
		}
		return (value === 'false' ? false : Boolean(value));
	}

	public set insertSpaces(value: boolean | string) {
		let insertSpaces = this._validateInsertSpaces(value);
		if (typeof insertSpaces === 'boolean') {
			if (this._insertSpaces === insertSpaces) {
				// nothing to do
				return;
			}
			// reflect the new insertSpaces value immediately
			this._insertSpaces = insertSpaces;
		}
		warnOnError(this._proxy.$trySetOptions(this._id, {
			insertSpaces: insertSpaces
		}));
	}

	public get cursorStyle(): TextEditorCursorStyle {
		return this._cursorStyle;
	}

	public set cursorStyle(value: TextEditorCursorStyle) {
		if (this._cursorStyle === value) {
			// nothing to do
			return;
		}
		this._cursorStyle = value;
		warnOnError(this._proxy.$trySetOptions(this._id, {
			cursorStyle: value
		}));
	}

	public get lineNumbers(): TextEditorLineNumbersStyle {
		return this._lineNumbers;
	}

	public set lineNumbers(value: TextEditorLineNumbersStyle) {
		if (this._lineNumbers === value) {
			// nothing to do
			return;
		}
		this._lineNumbers = value;
		warnOnError(this._proxy.$trySetOptions(this._id, {
			lineNumbers: value
		}));
	}

	public assign(newOptions: vscode.TextEditorOptions) {
		let bulkConfigurationUpdate: ITextEditorConfigurationUpdate = {};
		let hasUpdate = false;

		if (typeof newOptions.tabSize !== 'undefined') {
			let tabSize = this._validateTabSize(newOptions.tabSize);
			if (tabSize === 'auto') {
				hasUpdate = true;
				bulkConfigurationUpdate.tabSize = tabSize;
			} else if (typeof tabSize === 'number' && this._tabSize !== tabSize) {
				// reflect the new tabSize value immediately
				this._tabSize = tabSize;
				hasUpdate = true;
				bulkConfigurationUpdate.tabSize = tabSize;
			}
		}

		if (typeof newOptions.insertSpaces !== 'undefined') {
			let insertSpaces = this._validateInsertSpaces(newOptions.insertSpaces);
			if (insertSpaces === 'auto') {
				hasUpdate = true;
				bulkConfigurationUpdate.insertSpaces = insertSpaces;
			} else if (this._insertSpaces !== insertSpaces) {
				// reflect the new insertSpaces value immediately
				this._insertSpaces = insertSpaces;
				hasUpdate = true;
				bulkConfigurationUpdate.insertSpaces = insertSpaces;
			}
		}

		if (typeof newOptions.cursorStyle !== 'undefined') {
			if (this._cursorStyle !== newOptions.cursorStyle) {
				this._cursorStyle = newOptions.cursorStyle;
				hasUpdate = true;
				bulkConfigurationUpdate.cursorStyle = newOptions.cursorStyle;
			}
		}

		if (typeof newOptions.lineNumbers !== 'undefined') {
			if (this._lineNumbers !== newOptions.lineNumbers) {
				this._lineNumbers = newOptions.lineNumbers;
				hasUpdate = true;
				bulkConfigurationUpdate.lineNumbers = newOptions.lineNumbers;
			}
		}

		if (hasUpdate) {
			warnOnError(this._proxy.$trySetOptions(this._id, bulkConfigurationUpdate));
		}
	}
}

J
Johannes Rieken 已提交
314
export class ExtHostTextEditor implements vscode.TextEditor {
E
Erich Gamma 已提交
315

M
Matt Bierner 已提交
316
	public readonly editorType = 'texteditor';
317 318

	private readonly _proxy: MainThreadTextEditorsShape;
319 320
	private readonly _id: string;
	private readonly _documentData: ExtHostDocumentData;
E
Erich Gamma 已提交
321 322

	private _selections: Selection[];
323
	private _options: ExtHostTextEditorOptions;
324
	private _viewColumn: vscode.ViewColumn;
325
	private _disposed: boolean = false;
E
Erich Gamma 已提交
326

327 328
	get id(): string { return this._id; }

329
	constructor(proxy: MainThreadTextEditorsShape, id: string, document: ExtHostDocumentData, selections: Selection[], options: IResolvedTextEditorConfiguration, viewColumn: vscode.ViewColumn) {
E
Erich Gamma 已提交
330 331
		this._proxy = proxy;
		this._id = id;
332
		this._documentData = document;
E
Erich Gamma 已提交
333
		this._selections = selections;
334
		this._options = new ExtHostTextEditorOptions(this._proxy, this._id, options);
335
		this._viewColumn = viewColumn;
E
Erich Gamma 已提交
336 337 338
	}

	dispose() {
339 340
		ok(!this._disposed);
		this._disposed = true;
E
Erich Gamma 已提交
341 342 343
	}

	@deprecated('TextEditor.show') show(column: vscode.ViewColumn) {
344
		this._proxy.$tryShowEditor(this._id, TypeConverters.fromViewColumn(column));
E
Erich Gamma 已提交
345 346 347
	}

	@deprecated('TextEditor.hide') hide() {
348
		this._proxy.$tryHideEditor(this._id);
E
Erich Gamma 已提交
349 350 351 352 353
	}

	// ---- the document

	get document(): vscode.TextDocument {
354
		return this._documentData.document;
E
Erich Gamma 已提交
355 356 357 358 359 360 361 362
	}

	set document(value) {
		throw readonly('document');
	}

	// ---- options

363
	get options(): vscode.TextEditorOptions {
E
Erich Gamma 已提交
364 365 366
		return this._options;
	}

367
	set options(value: vscode.TextEditorOptions) {
368 369 370
		if (!this._disposed) {
			this._options.assign(value);
		}
E
Erich Gamma 已提交
371 372
	}

373
	_acceptOptions(options: IResolvedTextEditorConfiguration): void {
374
		ok(!this._disposed);
375
		this._options._accept(options);
E
Erich Gamma 已提交
376 377
	}

378 379 380 381 382 383 384 385 386 387 388
	// ---- view column

	get viewColumn(): vscode.ViewColumn {
		return this._viewColumn;
	}

	set viewColumn(value) {
		throw readonly('viewColumn');
	}

	_acceptViewColumn(value: vscode.ViewColumn) {
389
		ok(!this._disposed);
390 391 392
		this._viewColumn = value;
	}

E
Erich Gamma 已提交
393 394 395 396 397 398 399 400
	// ---- selections

	get selection(): Selection {
		return this._selections && this._selections[0];
	}

	set selection(value: Selection) {
		if (!(value instanceof Selection)) {
J
Johannes Rieken 已提交
401
			throw illegalArgument('selection');
E
Erich Gamma 已提交
402 403
		}
		this._selections = [value];
404
		this._trySetSelection();
E
Erich Gamma 已提交
405 406 407 408 409 410 411 412
	}

	get selections(): Selection[] {
		return this._selections;
	}

	set selections(value: Selection[]) {
		if (!Array.isArray(value) || value.some(a => !(a instanceof Selection))) {
J
Johannes Rieken 已提交
413
			throw illegalArgument('selections');
E
Erich Gamma 已提交
414 415
		}
		this._selections = value;
416
		this._trySetSelection();
E
Erich Gamma 已提交
417 418
	}

419
	setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
E
Erich Gamma 已提交
420
		this._runOnProxy(
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
			() => {
				if (TypeConverters.isDecorationOptionsArr(ranges)) {
					return this._proxy.$trySetDecorations(
						this._id,
						decorationType.key,
						TypeConverters.fromRangeOrRangeWithMessage(ranges)
					);
				} else {
					let _ranges: number[] = new Array<number>(4 * ranges.length);
					for (let i = 0, len = ranges.length; i < len; i++) {
						const range = ranges[i];
						_ranges[4 * i] = range.start.line + 1;
						_ranges[4 * i + 1] = range.start.character + 1;
						_ranges[4 * i + 2] = range.end.line + 1;
						_ranges[4 * i + 3] = range.end.character + 1;
					}
					return this._proxy.$trySetDecorationsFast(
						this._id,
						decorationType.key,
440
						_ranges
441 442 443
					);
				}
			}
E
Erich Gamma 已提交
444 445 446
		);
	}

J
Johannes Rieken 已提交
447
	revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
E
Erich Gamma 已提交
448
		this._runOnProxy(
449
			() => this._proxy.$tryRevealRange(
E
Erich Gamma 已提交
450 451
				this._id,
				TypeConverters.fromRange(range),
A
Alex Dima 已提交
452
				(revealType || TextEditorRevealType.Default)
453
			)
E
Erich Gamma 已提交
454 455 456
		);
	}

457
	private _trySetSelection(): TPromise<vscode.TextEditor> {
E
Erich Gamma 已提交
458
		let selection = this._selections.map(TypeConverters.fromSelection);
459
		return this._runOnProxy(() => this._proxy.$trySetSelections(this._id, selection));
E
Erich Gamma 已提交
460 461
	}

J
Johannes Rieken 已提交
462
	_acceptSelections(selections: Selection[]): void {
463
		ok(!this._disposed);
E
Erich Gamma 已提交
464 465 466 467 468
		this._selections = selections;
	}

	// ---- editing

469
	edit(callback: (edit: TextEditorEdit) => void, options: { undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Thenable<boolean> {
470
		if (this._disposed) {
471
			return TPromise.wrapError<boolean>(new Error('TextEditor#edit not possible on closed editors'));
472
		}
473 474 475
		let edit = new TextEditorEdit(this._documentData.document, options);
		callback(edit);
		return this._applyEdit(edit);
E
Erich Gamma 已提交
476 477
	}

478
	private _applyEdit(editBuilder: TextEditorEdit): TPromise<boolean> {
J
Johannes Rieken 已提交
479
		let editData = editBuilder.finalize();
E
Erich Gamma 已提交
480

481 482 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 509 510
		// check that the edits are not overlapping (i.e. illegal)
		let editRanges = editData.edits.map(edit => edit.range);

		// sort ascending (by end and then by start)
		editRanges.sort((a, b) => {
			if (a.end.line === b.end.line) {
				if (a.end.character === b.end.character) {
					if (a.start.line === b.start.line) {
						return a.start.character - b.start.character;
					}
					return a.start.line - b.start.line;
				}
				return a.end.character - b.end.character;
			}
			return a.end.line - b.end.line;
		});

		// check that no edits are overlapping
		for (let i = 0, count = editRanges.length - 1; i < count; i++) {
			const rangeEnd = editRanges[i].end;
			const nextRangeStart = editRanges[i + 1].start;

			if (nextRangeStart.isBefore(rangeEnd)) {
				// overlapping ranges
				return TPromise.wrapError<boolean>(
					new Error('Overlapping ranges are not allowed!')
				);
			}
		}

E
Erich Gamma 已提交
511
		// prepare data for serialization
B
Benjamin Pasero 已提交
512
		let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
E
Erich Gamma 已提交
513 514 515 516 517 518 519
			return {
				range: TypeConverters.fromRange(edit.range),
				text: edit.text,
				forceMoveMarkers: edit.forceMoveMarkers
			};
		});

520 521 522 523 524
		return this._proxy.$tryApplyEdits(this._id, editData.documentVersionId, edits, {
			setEndOfLine: editData.setEndOfLine,
			undoStopBefore: editData.undoStopBefore,
			undoStopAfter: editData.undoStopAfter
		});
E
Erich Gamma 已提交
525 526
	}

527
	insertSnippet(snippet: SnippetString, where?: Position | Position[] | Range | Range[], options: { undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Thenable<boolean> {
528
		if (this._disposed) {
529
			return TPromise.wrapError<boolean>(new Error('TextEditor#insertSnippet not possible on closed editors'));
530
		}
531
		let ranges: IRange[];
532 533

		if (!where || (Array.isArray(where) && where.length === 0)) {
534 535 536
			ranges = this._selections.map(TypeConverters.fromRange);

		} else if (where instanceof Position) {
J
Johannes Rieken 已提交
537
			const { lineNumber, column } = TypeConverters.fromPosition(where);
538
			ranges = [{ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column }];
539

540 541 542 543 544 545 546 547
		} else if (where instanceof Range) {
			ranges = [TypeConverters.fromRange(where)];
		} else {
			ranges = [];
			for (const posOrRange of where) {
				if (posOrRange instanceof Range) {
					ranges.push(TypeConverters.fromRange(posOrRange));
				} else {
J
Johannes Rieken 已提交
548
					const { lineNumber, column } = TypeConverters.fromPosition(posOrRange);
549 550 551 552
					ranges.push({ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column });
				}
			}
		}
553

554
		return this._proxy.$tryInsertSnippet(this._id, snippet.value, ranges, options);
555 556
	}

E
Erich Gamma 已提交
557 558
	// ---- util

559
	private _runOnProxy(callback: () => TPromise<any>): TPromise<ExtHostTextEditor> {
560
		if (this._disposed) {
561 562
			console.warn('TextEditor is closed/disposed');
			return TPromise.as(undefined);
563
		}
E
Erich Gamma 已提交
564
		return callback().then(() => this, err => {
R
Ron Buckton 已提交
565 566
			if (!(err instanceof Error && err.name === 'DISPOSED')) {
				console.warn(err);
567
			}
R
Ron Buckton 已提交
568
			return null;
E
Erich Gamma 已提交
569 570 571
		});
	}
}
572 573 574 575 576 577

function warnOnError(promise: TPromise<any>): void {
	promise.then(null, (err) => {
		console.warn(err);
	});
}