inspectTMScopes.ts 10.0 KB
Newer Older
A
Alex Dima 已提交
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 'vs/css!./inspectTMScopes';
A
Alex Dima 已提交
8 9 10
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { Disposable } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
11
import { escape } from 'vs/base/common/strings';
A
Alex Dima 已提交
12 13 14 15 16 17 18 19 20 21 22
import { Position } from 'vs/editor/common/core/position';
import { ICommonCodeEditor, IEditorContribution, IModel } from 'vs/editor/common/editorCommon';
import { editorAction, EditorAction, ServicesAccessor } from 'vs/editor/common/editorCommonExtensions';
import { ICodeEditor, ContentWidgetPositionPreference, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { editorContribution } from 'vs/editor/browser/editorBrowserExtensions';
import { TPromise } from 'vs/base/common/winjs.base';
import { IGrammar, StackElement, IToken } from 'vscode-textmate';
import { ITextMateService } from 'vs/editor/node/textMate/textMateService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { TokenMetadata } from 'vs/editor/common/model/tokensBinaryEncoding';
import { TokenizationRegistry, LanguageIdentifier, FontStyle, StandardTokenType } from 'vs/editor/common/modes';
A
Alex Dima 已提交
23
import { CharCode } from 'vs/base/common/charCode';
A
Alex Dima 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

@editorContribution
class InspectTMScopesController extends Disposable implements IEditorContribution {

	private static ID = 'editor.contrib.inspectTMScopes';

	public static get(editor: ICommonCodeEditor): InspectTMScopesController {
		return editor.getContribution<InspectTMScopesController>(InspectTMScopesController.ID);
	}

	private _editor: ICodeEditor;
	private _textMateService: ITextMateService;
	private _modeService: IModeService;
	private _widget: InspectTMScopesWidget;

	constructor(
		editor: ICodeEditor,
		@ITextMateService textMateService: ITextMateService,
		@IModeService modeService: IModeService
	) {
		super();
		this._editor = editor;
		this._textMateService = textMateService;
		this._modeService = modeService;
		this._widget = null;

		this._register(this._editor.onDidChangeModel((e) => this.stop()));
		this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
	}

	public getId(): string {
		return InspectTMScopesController.ID;
	}

	public dispose(): void {
		this.stop();
		super.dispose();
	}

	public launch(): void {
		if (this._widget) {
			return;
		}
		if (!this._editor.getModel()) {
			return;
		}
		this._widget = new InspectTMScopesWidget(this._editor, this._textMateService, this._modeService);
	}

	public stop(): void {
		if (this._widget) {
			this._widget.dispose();
			this._widget = null;
		}
	}
}

@editorAction
class InspectTMScopes extends EditorAction {

	constructor() {
		super({
			id: 'editor.action.inspectTMScopes',
			label: nls.localize('inspectTMScopes', "Developer: Inspect TM Scopes"),
			alias: 'Developer: Inspect TM Scopes',
			precondition: null
		});
	}

	public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void {
		let controller = InspectTMScopesController.get(editor);
		if (controller) {
			controller.launch();
		}
	}
}

interface ICompleteLineTokenization {
	startState: StackElement;
	tokens1: IToken[];
	tokens2: Uint32Array;
	endState: StackElement;
}

interface IDecodedMetadata {
	languageIdentifier: LanguageIdentifier;
	tokenType: StandardTokenType;
	fontStyle: FontStyle;
	foreground: string;
	background: string;
}

A
Alex Dima 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
function renderTokenText(tokenText: string): string {
	let result: string = '';
	for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
		let charCode = tokenText.charCodeAt(charIndex);
		switch (charCode) {
			case CharCode.Tab:
				result += '&rarr;';
				break;

			case CharCode.Space:
				result += '&middot;';
				break;

			case CharCode.LessThan:
				result += '&lt;';
				break;

			case CharCode.GreaterThan:
				result += '&gt;';
				break;

			case CharCode.Ampersand:
				result += '&amp;';
				break;

			default:
				result += String.fromCharCode(charCode);
		}
	}
	return result;
}

A
Alex Dima 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
class InspectTMScopesWidget extends Disposable implements IContentWidget {

	private static _ID = 'editor.contrib.inspectTMScopesWidget';

	public allowEditorOverflow = true;

	private _editor: ICodeEditor;
	private _modeService: IModeService;
	private _model: IModel;
	private _domNode: HTMLElement;
	private _grammar: TPromise<IGrammar>;

	constructor(
		editor: ICodeEditor,
		textMateService: ITextMateService,
		modeService: IModeService
	) {
		super();
		this._editor = editor;
		this._modeService = modeService;
		this._model = this._editor.getModel();
		this._domNode = document.createElement('div');
A
Alex Dima 已提交
170
		this._domNode.className = 'tm-inspect-widget';
A
Alex Dima 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
		this._grammar = textMateService.createGrammar(this._model.getLanguageIdentifier().language);
		this._beginCompute(this._editor.getPosition());
		this._register(this._editor.onDidChangeCursorPosition((e) => this._beginCompute(this._editor.getPosition())));
		this._editor.addContentWidget(this);
	}

	public dispose(): void {
		this._editor.removeContentWidget(this);
	}

	public getId(): string {
		return InspectTMScopesWidget._ID;
	}

	private _beginCompute(position: Position): void {
		dom.clearNode(this._domNode);
		this._domNode.appendChild(document.createTextNode(nls.localize('inspectTMScopesWidget.loading', "Loading...")));
		this._grammar.then((grammar) => this._compute(grammar, position));
		this._editor.layoutContentWidget(this);
	}

	private _compute(grammar: IGrammar, position: Position): void {
		let data = this._getTokensAtLine(grammar, position.lineNumber);
A
Alex Dima 已提交
194

A
Alex Dima 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
		let token1Index = 0;
		for (let i = data.tokens1.length - 1; i >= 0; i--) {
			let t = data.tokens1[i];
			if (position.column - 1 >= t.startIndex) {
				token1Index = i;
				break;
			}
		}

		let token2Index = 0;
		for (let i = (data.tokens2.length >>> 1); i >= 0; i--) {
			if (position.column - 1 >= data.tokens2[(i << 1)]) {
				token2Index = i;
				break;
			}
		}

		let tokenStartIndex = data.tokens1[token1Index].startIndex;
		let tokenEndIndex = data.tokens1[token1Index].endIndex;
		let tokenText = this._model.getLineContent(position.lineNumber).substring(tokenStartIndex, tokenEndIndex);
A
Alex Dima 已提交
215
		let metadata = this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]);
A
Alex Dima 已提交
216

A
Alex Dima 已提交
217 218
		let result = '';
		result += `<h2 class="tm-token">${renderTokenText(tokenText)}<span class="tm-token-length">(${tokenText.length} ${tokenText.length === 1 ? 'char' : 'chars'})</span></h2>`;
A
Alex Dima 已提交
219

A
Alex Dima 已提交
220
		result += `<hr style="clear:both"/>`;
A
Alex Dima 已提交
221

A
Alex Dima 已提交
222 223 224 225 226 227 228 229 230
		result += `<table class="tm-metadata-table"><tbody>`;
		result += `<tr><td class="tm-metadata-key">language</td><td class="tm-metadata-value">${escape(metadata.languageIdentifier.language)}</td>`;
		result += `<tr><td class="tm-metadata-key">token type</td><td class="tm-metadata-value">${this._tokenTypeToString(metadata.tokenType)}</td>`;
		result += `<tr><td class="tm-metadata-key">font style</td><td class="tm-metadata-value">${this._fontStyleToString(metadata.fontStyle)}</td>`;
		result += `<tr><td class="tm-metadata-key">foreground</td><td class="tm-metadata-value">${metadata.foreground}</td>`;
		result += `<tr><td class="tm-metadata-key">background</td><td class="tm-metadata-value">${metadata.background}</td>`;
		result += `</tbody></table>`;

		result += `<hr/>`;
A
Alex Dima 已提交
231 232 233

		result += `<ul>`;
		for (let i = data.tokens1[token1Index].scopes.length - 1; i >= 0; i--) {
A
Alex Dima 已提交
234
			result += `<li>${escape(data.tokens1[token1Index].scopes[i])}</li>`;
A
Alex Dima 已提交
235 236 237
		}
		result += `</ul>`;

A
Alex Dima 已提交
238
		this._domNode.innerHTML = result;
A
Alex Dima 已提交
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
	}

	private _decodeMetadata(metadata: number): IDecodedMetadata {
		let colorMap = TokenizationRegistry.getColorMap();
		let languageId = TokenMetadata.getLanguageId(metadata);
		let tokenType = TokenMetadata.getTokenType(metadata);
		let fontStyle = TokenMetadata.getFontStyle(metadata);
		let foreground = TokenMetadata.getForeground(metadata);
		let background = TokenMetadata.getBackground(metadata);
		return {
			languageIdentifier: this._modeService.getLanguageIdentifier(languageId),
			tokenType: tokenType,
			fontStyle: fontStyle,
			foreground: colorMap[foreground],
			background: colorMap[background]
		};
	}

	private _tokenTypeToString(tokenType: StandardTokenType): string {
		switch (tokenType) {
			case StandardTokenType.Other: return 'Other';
			case StandardTokenType.Comment: return 'Comment';
			case StandardTokenType.String: return 'String';
			case StandardTokenType.RegEx: return 'RegEx';
		}
		return '??';
	}

	private _fontStyleToString(fontStyle: FontStyle): string {
		let r = '';
		if (fontStyle & FontStyle.Italic) {
			r += 'italic ';
		}
		if (fontStyle & FontStyle.Bold) {
			r += 'bold ';
		}
		if (fontStyle & FontStyle.Underline) {
			r += 'underline ';
		}
A
Alex Dima 已提交
278 279
		if (r.length === 0) {
			r = '---';
A
Alex Dima 已提交
280
		}
A
Alex Dima 已提交
281
		return r;
A
Alex Dima 已提交
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 314 315 316 317 318 319
	}

	private _getTokensAtLine(grammar: IGrammar, lineNumber: number): ICompleteLineTokenization {
		let stateBeforeLine = this._getStateBeforeLine(grammar, lineNumber);

		let tokenizationResult1 = grammar.tokenizeLine(this._model.getLineContent(lineNumber), stateBeforeLine);
		let tokenizationResult2 = grammar.tokenizeLine2(this._model.getLineContent(lineNumber), stateBeforeLine);

		return {
			startState: stateBeforeLine,
			tokens1: tokenizationResult1.tokens,
			tokens2: tokenizationResult2.tokens,
			endState: tokenizationResult1.ruleStack
		};
	}

	private _getStateBeforeLine(grammar: IGrammar, lineNumber: number): StackElement {
		let state: StackElement = null;

		for (let i = 1; i < lineNumber; i++) {
			let tokenizationResult = grammar.tokenizeLine(this._model.getLineContent(i), state);
			state = tokenizationResult.ruleStack;
		}

		return state;
	}

	public getDomNode(): HTMLElement {
		return this._domNode;
	}

	public getPosition(): IContentWidgetPosition {
		return {
			position: this._editor.getPosition(),
			preference: [ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.ABOVE]
		};
	}
}