inspectTMScopes.ts 10.9 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';
24 25
import { findMatchingThemeRule } from 'vs/editor/electron-browser/textMate/TMHelper';
import { IThemeService } from 'vs/workbench/services/themes/common/themeService';
A
Alex Dima 已提交
26 27 28 29 30 31 32 33 34 35 36 37

@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;
38
	private _themeService: IThemeService;
A
Alex Dima 已提交
39 40 41 42 43 44
	private _modeService: IModeService;
	private _widget: InspectTMScopesWidget;

	constructor(
		editor: ICodeEditor,
		@ITextMateService textMateService: ITextMateService,
45 46
		@IModeService modeService: IModeService,
		@IThemeService themeService: IThemeService
A
Alex Dima 已提交
47 48 49 50
	) {
		super();
		this._editor = editor;
		this._textMateService = textMateService;
51
		this._themeService = themeService;
A
Alex Dima 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
		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;
		}
75
		this._widget = new InspectTMScopesWidget(this._editor, this._textMateService, this._modeService, this._themeService);
A
Alex Dima 已提交
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 116 117 118 119 120
	}

	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 已提交
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 148 149 150 151 152
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 已提交
153 154 155 156 157 158
class InspectTMScopesWidget extends Disposable implements IContentWidget {

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

	public allowEditorOverflow = true;

159
	private _isDisposed: boolean;
A
Alex Dima 已提交
160 161
	private _editor: ICodeEditor;
	private _modeService: IModeService;
162
	private _themeService: IThemeService;
A
Alex Dima 已提交
163 164 165 166 167 168 169
	private _model: IModel;
	private _domNode: HTMLElement;
	private _grammar: TPromise<IGrammar>;

	constructor(
		editor: ICodeEditor,
		textMateService: ITextMateService,
170 171
		modeService: IModeService,
		themeService: IThemeService
A
Alex Dima 已提交
172 173
	) {
		super();
174
		this._isDisposed = false;
A
Alex Dima 已提交
175 176
		this._editor = editor;
		this._modeService = modeService;
177
		this._themeService = themeService;
A
Alex Dima 已提交
178 179
		this._model = this._editor.getModel();
		this._domNode = document.createElement('div');
A
Alex Dima 已提交
180
		this._domNode.className = 'tm-inspect-widget';
A
Alex Dima 已提交
181 182 183 184 185 186 187
		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 {
188
		this._isDisposed = true;
A
Alex Dima 已提交
189
		this._editor.removeContentWidget(this);
190
		super.dispose();
A
Alex Dima 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203
	}

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

	private _compute(grammar: IGrammar, position: Position): void {
204 205 206
		if (this._isDisposed) {
			return;
		}
A
Alex Dima 已提交
207
		let data = this._getTokensAtLine(grammar, position.lineNumber);
A
Alex Dima 已提交
208

A
Alex Dima 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
		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;
			}
		}

226 227
		let result = '';

A
Alex Dima 已提交
228 229 230
		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 已提交
231
		result += `<h2 class="tm-token">${renderTokenText(tokenText)}<span class="tm-token-length">(${tokenText.length} ${tokenText.length === 1 ? 'char' : 'chars'})</span></h2>`;
A
Alex Dima 已提交
232

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

235
		let metadata = this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]);
A
Alex Dima 已提交
236 237 238 239 240 241 242 243
		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>`;

M
Martin Aeschlimann 已提交
244 245 246 247 248 249 250
		let theme = this._themeService.getColorTheme();
		result += `<hr/>`;
		let matchingRule = findMatchingThemeRule(theme, data.tokens1[token1Index].scopes);
		if (matchingRule) {
			result += `<code class="tm-theme-selector">${matchingRule.rawSelector}\n${JSON.stringify(matchingRule.settings, null, '\t')}</code>`;
		} else {
			result += `<span class="tm-theme-selector">No theme selector.</span>`;
251 252
		}

A
Alex Dima 已提交
253
		result += `<hr/>`;
A
Alex Dima 已提交
254 255 256

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

261

A
Alex Dima 已提交
262
		this._domNode.innerHTML = result;
263
		this._editor.layoutContentWidget(this);
A
Alex Dima 已提交
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
	}

	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 已提交
303 304
		if (r.length === 0) {
			r = '---';
A
Alex Dima 已提交
305
		}
A
Alex Dima 已提交
306
		return r;
A
Alex Dima 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
	}

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