extHostTextEditor.ts 14.8 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';
J
Johannes Rieken 已提交
9 10 11
import { readonly, illegalArgument } from 'vs/base/common/errors';
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';
14
import { ISingleEditOperation, TextEditorCursorStyle, IRange } from 'vs/editor/common/editorCommon';
J
Johannes Rieken 已提交
15
import { IResolvedTextEditorConfiguration, ITextEditorConfigurationUpdate } from 'vs/workbench/api/node/mainThreadEditor';
16
import * as TypeConverters from './extHostTypeConverters';
J
Johannes Rieken 已提交
17
import { MainThreadEditorsShape } from './extHost.protocol';
18
import * as vscode from 'vscode';
E
Erich Gamma 已提交
19

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

J
Johannes Rieken 已提交
22
	private static _Keys = new IdGenerator('TextEditorDecorationType');
E
Erich Gamma 已提交
23

24
	private _proxy: MainThreadEditorsShape;
E
Erich Gamma 已提交
25 26
	public key: string;

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

	public dispose(): void {
34
		this._proxy.$removeTextEditorDecorationType(this.key);
E
Erich Gamma 已提交
35 36 37 38 39 40 41 42 43 44 45 46
	}
}

export interface ITextEditOperation {
	range: Range;
	text: string;
	forceMoveMarkers: boolean;
}

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

export class TextEditorEdit {

	private _documentVersionId: number;
	private _collectedEdits: ITextEditOperation[];
56
	private _setEndOfLine: EndOfLine;
57 58
	private _undoStopBefore: boolean;
	private _undoStopAfter: boolean;
E
Erich Gamma 已提交
59

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

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

	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 已提交
85
		} else {
E
Erich Gamma 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
			throw new Error('Unrecognized location');
		}

		this._collectedEdits.push({
			range: range,
			text: value,
			forceMoveMarkers: false
		});
	}

	insert(location: Position, value: string): void {
		this._collectedEdits.push({
			range: new Range(location, location),
			text: value,
			forceMoveMarkers: true
		});
	}

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

		if (location instanceof Range) {
			range = location;
A
Alex Dima 已提交
109
		} else {
E
Erich Gamma 已提交
110 111 112 113 114 115 116 117 118
			throw new Error('Unrecognized location');
		}

		this._collectedEdits.push({
			range: range,
			text: null,
			forceMoveMarkers: true
		});
	}
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 144 145 146 147 148 149 150 151 152 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
export class ExtHostTextEditorOptions implements vscode.TextEditorOptions {

	private _proxy: MainThreadEditorsShape;
	private _id: string;

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

	constructor(proxy: MainThreadEditorsShape, id: string, source: IResolvedTextEditorConfiguration) {
		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

316 317 318
	private readonly _proxy: MainThreadEditorsShape;
	private readonly _id: string;
	private readonly _documentData: ExtHostDocumentData;
E
Erich Gamma 已提交
319 320

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

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

	dispose() {
335 336
		ok(!this._disposed);
		this._disposed = true;
E
Erich Gamma 已提交
337 338 339
	}

	@deprecated('TextEditor.show') show(column: vscode.ViewColumn) {
340
		this._proxy.$tryShowEditor(this._id, TypeConverters.fromViewColumn(column));
E
Erich Gamma 已提交
341 342 343
	}

	@deprecated('TextEditor.hide') hide() {
344
		this._proxy.$tryHideEditor(this._id);
E
Erich Gamma 已提交
345 346 347 348 349
	}

	// ---- the document

	get document(): vscode.TextDocument {
350
		return this._documentData.document;
E
Erich Gamma 已提交
351 352 353 354 355 356 357 358
	}

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

	// ---- options

359
	get options(): vscode.TextEditorOptions {
E
Erich Gamma 已提交
360 361 362
		return this._options;
	}

363
	set options(value: vscode.TextEditorOptions) {
364 365 366
		if (!this._disposed) {
			this._options.assign(value);
		}
E
Erich Gamma 已提交
367 368
	}

369
	_acceptOptions(options: IResolvedTextEditorConfiguration): void {
370
		ok(!this._disposed);
371
		this._options._accept(options);
E
Erich Gamma 已提交
372 373
	}

374 375 376 377 378 379 380 381 382 383 384
	// ---- view column

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

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

	_acceptViewColumn(value: vscode.ViewColumn) {
385
		ok(!this._disposed);
386 387 388
		this._viewColumn = value;
	}

E
Erich Gamma 已提交
389 390 391 392 393 394 395 396
	// ---- selections

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

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

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

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

J
Johannes Rieken 已提交
415
	setDecorations(decorationType: vscode.TextEditorDecorationType, ranges: Range[] | vscode.DecorationOptions[]): void {
E
Erich Gamma 已提交
416
		this._runOnProxy(
417
			() => this._proxy.$trySetDecorations(
E
Erich Gamma 已提交
418 419 420 421 422 423 424 425
				this._id,
				decorationType.key,
				TypeConverters.fromRangeOrRangeWithMessage(ranges)
			),
			true
		);
	}

J
Johannes Rieken 已提交
426
	revealRange(range: Range, revealType: vscode.TextEditorRevealType): void {
E
Erich Gamma 已提交
427
		this._runOnProxy(
428
			() => this._proxy.$tryRevealRange(
E
Erich Gamma 已提交
429 430
				this._id,
				TypeConverters.fromRange(range),
A
Alex Dima 已提交
431
				(revealType || TextEditorRevealType.Default)
E
Erich Gamma 已提交
432 433 434 435 436 437 438
			),
			true
		);
	}

	private _trySetSelection(silent: boolean): TPromise<vscode.TextEditor> {
		let selection = this._selections.map(TypeConverters.fromSelection);
439
		return this._runOnProxy(() => this._proxy.$trySetSelections(this._id, selection), silent);
E
Erich Gamma 已提交
440 441
	}

J
Johannes Rieken 已提交
442
	_acceptSelections(selections: Selection[]): void {
443
		ok(!this._disposed);
E
Erich Gamma 已提交
444 445 446 447 448
		this._selections = selections;
	}

	// ---- editing

449
	edit(callback: (edit: TextEditorEdit) => void, options: { undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Thenable<boolean> {
450 451 452
		if (this._disposed) {
			return TPromise.wrapError<boolean>('TextEditor#edit not possible on closed editors');
		}
453 454 455
		let edit = new TextEditorEdit(this._documentData.document, options);
		callback(edit);
		return this._applyEdit(edit);
E
Erich Gamma 已提交
456 457
	}

458
	private _applyEdit(editBuilder: TextEditorEdit): TPromise<boolean> {
J
Johannes Rieken 已提交
459
		let editData = editBuilder.finalize();
E
Erich Gamma 已提交
460 461

		// prepare data for serialization
B
Benjamin Pasero 已提交
462
		let edits: ISingleEditOperation[] = editData.edits.map((edit) => {
E
Erich Gamma 已提交
463 464 465 466 467 468 469
			return {
				range: TypeConverters.fromRange(edit.range),
				text: edit.text,
				forceMoveMarkers: edit.forceMoveMarkers
			};
		});

470 471 472 473 474
		return this._proxy.$tryApplyEdits(this._id, editData.documentVersionId, edits, {
			setEndOfLine: editData.setEndOfLine,
			undoStopBefore: editData.undoStopBefore,
			undoStopAfter: editData.undoStopAfter
		});
E
Erich Gamma 已提交
475 476
	}

477
	insertSnippet(snippet: SnippetString, where?: Position | Position[] | Range | Range[], options: { undoStopBefore: boolean; undoStopAfter: boolean; } = { undoStopBefore: true, undoStopAfter: true }): Thenable<boolean> {
478 479 480
		if (this._disposed) {
			return TPromise.wrapError<boolean>('TextEditor#insertSnippet not possible on closed editors');
		}
481
		let ranges: IRange[];
482 483

		if (!where || (Array.isArray(where) && where.length === 0)) {
484 485 486
			ranges = this._selections.map(TypeConverters.fromRange);

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

490 491 492 493 494 495 496 497
		} 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 已提交
498
					const { lineNumber, column } = TypeConverters.fromPosition(posOrRange);
499 500 501 502
					ranges.push({ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column });
				}
			}
		}
503

504
		return this._proxy.$tryInsertSnippet(this._id, snippet.value, ranges, options);
505 506
	}

E
Erich Gamma 已提交
507 508
	// ---- util

J
Johannes Rieken 已提交
509
	private _runOnProxy(callback: () => TPromise<any>, silent: boolean): TPromise<ExtHostTextEditor> {
510 511 512 513 514 515 516 517
		if (this._disposed) {
			if (!silent) {
				return TPromise.wrapError(silent);
			} else {
				console.warn('TextEditor is closed/disposed');
				return TPromise.as(undefined);
			}
		}
E
Erich Gamma 已提交
518 519 520 521 522
		return callback().then(() => this, err => {
			if (!silent) {
				return TPromise.wrapError(silent);
			}
			console.warn(err);
523
			return undefined;
E
Erich Gamma 已提交
524 525 526
		});
	}
}
527 528 529 530 531 532

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