本文整理汇总了TypeScript中vscode.languages类的典型用法代码示例。如果您正苦于以下问题:TypeScript languages类的具体用法?TypeScript languages怎么用?TypeScript languages使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了languages类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: isJava8
isJava8(javaExecutablePath).then(eight => {
if (!eight) {
VSCode.window.showErrorMessage('Java language support requires Java 8 (using ' + javaExecutablePath + ')');
return;
}
// Options to control the language client
let clientOptions: LanguageClientOptions = {
// Register the server for java documents
documentSelector: ['java'],
synchronize: {
// Synchronize the setting section 'java' to the server
// NOTE: this currently doesn't do anything
configurationSection: 'java',
// Notify the server about file changes to 'javaconfig.json' files contain in the workspace
fileEvents: [
VSCode.workspace.createFileSystemWatcher('**/javaconfig.json'),
VSCode.workspace.createFileSystemWatcher('**/*.java')
]
}
}
function createServer(): Promise<StreamInfo> {
return new Promise((resolve, reject) => {
PortFinder.getPort((err, port) => {
let fatJar = Path.resolve(context.extensionPath, "out", "fat-jar.jar");
let args = [
'-cp', fatJar,
'-Djavacs.port=' + port,
'org.javacs.Main'
];
console.log(javaExecutablePath + ' ' + args.join(' '));
Net.createServer(socket => {
console.log('Child process connected on port ' + port);
resolve({
reader: socket,
writer: socket
});
}).listen(port, () => {
let options = { stdio: 'inherit', cwd: VSCode.workspace.rootPath };
// Start the child java process
ChildProcess.execFile(javaExecutablePath, args, options);
});
});
});
}
// Create the language client and start the client.
let client = new LanguageClient('Language Server Example', createServer, clientOptions);
let disposable = client.start();
// Push the disposable to the context's subscriptions so that the
// client can be deactivated on extension deactivation
context.subscriptions.push(disposable);
// Set indentation rules
VSCode.languages.setLanguageConfiguration('java', {
indentationRules: {
// ^(.*\*/)?\s*\}.*$
decreaseIndentPattern: /^(.*\*\/)?\s*\}.*$/,
// ^.*\{[^}"']*$
increaseIndentPattern: /^.*\{[^}"']*$/
},
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')'],
],
onEnterRules: [
{
// e.g. /** | */
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: VSCode.IndentAction.IndentOutdent, appendText: ' * ' }
},
{
// e.g. /** ...|
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: VSCode.IndentAction.None, appendText: ' * ' }
},
{
// e.g. * ...|
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: VSCode.IndentAction.None, appendText: '* ' }
},
{
// e.g. */|
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: VSCode.IndentAction.None, removeText: 1 }
//.........这里部分代码省略.........
示例2: registerCompletion
export function registerCompletion(ext: ExtensionState) {
ext.context.subscriptions.push(vscode.languages.registerCompletionItemProvider(
{ language: 'haskell', scheme: 'file' } , new HaskellCompletion(ext), ' '));
}
示例3: onEditor
function onEditor(editor: vscode.TextEditor): void {
if (!editor || !vscode.languages.match(selector, editor.document)) {
item.hide();
return;
}
const file = client.asAbsolutePath(editor.document.uri);
isOpen(file).then(value => {
if (!value) {
return;
}
return client.execute('projectInfo', { file, needFileNameList: true }).then(res => {
let {configFileName, fileNames} = res.body;
if (projectHinted[configFileName] === true) {
return;
}
if (!configFileName && vscode.workspace.rootPath) {
exists(join(vscode.workspace.rootPath, 'jsconfig.json'), exists => {
// don't hint if there is a global jsconfig-file. We can get here due
// to TypeScript bugs or jsconfig configurations
if (exists) {
return;
}
currentHint = {
message: localize('hintCreate', "Create a jsconfig.json to enable richer IntelliSense and code navigation across the entire workspace."),
options: [{
title: localize('ignore.cmdCreate', 'Ignore'),
execute: () => {
client.logTelemetry('js.hintProjectCreation.ignored');
projectHinted[configFileName] = true;
projectHintIgnoreList.push(configFileName);
memento.update('projectHintIgnoreList', projectHintIgnoreList);
item.hide();
}
}, {
title: localize('cmdCreate', "Create jsconfig.json"),
execute: () => {
client.logTelemetry('js.hintProjectCreation.accepted');
projectHinted[configFileName] = true;
item.hide();
return vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + encodeURIComponent(join(vscode.workspace.rootPath, 'jsconfig.json'))))
.then(doc => vscode.window.showTextDocument(doc, vscode.ViewColumn.Three))
.then(editor => editor.edit(builder => builder.insert(new vscode.Position(0, 0), defaultConfig)));
}
}]
};
item.text = '$(light-bulb)';
item.tooltip = localize('hintCreate.tooltip', "Create a jsconfig.json to enable richer IntelliSense and code navigation across the entire workspace.");
item.color = '#A5DF3B';
item.show();
client.logTelemetry('js.hintProjectCreation');
});
} else if (fileNames.length > fileLimit) {
let largeRoots = computeLargeRoots(configFileName, fileNames).map(f => `'/${f}/'`).join(', ');
currentHint = {
message: largeRoots.length > 0
? localize('hintExclude', "For better performance exclude folders with many files, like: {0}", largeRoots)
: localize('hintExclude.generic', "For better performance exclude folders with many files."),
options: [{
title: localize('open', "Configure Excludes"),
execute: () => {
client.logTelemetry('js.hintProjectExcludes.accepted');
projectHinted[configFileName] = true;
item.hide();
return vscode.workspace.openTextDocument(configFileName)
.then(vscode.window.showTextDocument);
}
}]
};
item.tooltip = currentHint.message;
item.text = localize('large.label', "Configure Excludes");
item.tooltip = localize('hintExclude.tooltip', "For better performance exclude folders with many files.");
item.color = '#A5DF3B';
item.show();
client.logTelemetry('js.hintProjectExcludes');
} else {
item.hide();
}
});
}).catch(err => {
console.log(err);
});
}
示例4:
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (!editor || !vscode.languages.match(CLANG_MODE, editor.document)) return;
confTester.test(editor.document.languageId);
}, null, subscriptions);
示例5: activate
export function activate(context: ExtensionContext) {
let toDispose = context.subscriptions;
let packageInfo = getPackageInfo(context);
let telemetryReporter: TelemetryReporter = packageInfo && new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);
if (telemetryReporter) {
toDispose.push(telemetryReporter);
}
// The server is implemented in node
let serverModule = context.asAbsolutePath(path.join('server', 'out', 'htmlServerMain.js'));
// The debug options for the server
let debugOptions = { execArgv: ['--nolazy', '--inspect=6004'] };
// If the extension is launch in debug mode the debug server options are use
// Otherwise the run options are used
let serverOptions: ServerOptions = {
run: { module: serverModule, transport: TransportKind.ipc },
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};
let documentSelector = ['html', 'handlebars', 'razor'];
let embeddedLanguages = { css: true, javascript: true };
// Options to control the language client
let clientOptions: LanguageClientOptions = {
documentSelector,
synchronize: {
configurationSection: ['html', 'css', 'javascript'], // the settings to synchronize
},
initializationOptions: {
embeddedLanguages
}
};
// Create the language client and start the client.
let client = new LanguageClient('html', localize('htmlserver.name', 'HTML Language Server'), serverOptions, clientOptions);
client.registerFeature(new ConfigurationFeature(client));
let disposable = client.start();
toDispose.push(disposable);
client.onReady().then(() => {
disposable = languages.registerColorProvider(documentSelector, {
provideDocumentColors(document: TextDocument): Thenable<ColorInformation[]> {
let params: DocumentColorParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
};
return client.sendRequest(DocumentColorRequest.type, params).then(symbols => {
return symbols.map(symbol => {
let range = client.protocol2CodeConverter.asRange(symbol.range);
let color = new Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
return new ColorInformation(range, color);
});
});
},
provideColorPresentations(document: TextDocument, colorInfo: ColorInformation): Thenable<ColorPresentation[]> {
let params: ColorPresentationParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
colorInfo: { range: client.code2ProtocolConverter.asRange(colorInfo.range), color: colorInfo.color }
};
return client.sendRequest(ColorPresentationRequest.type, params).then(presentations => {
return presentations.map(p => {
let presentation = new ColorPresentation(p.label);
presentation.textEdit = p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit);
presentation.additionalTextEdits = p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
return presentation;
});
});
}
});
toDispose.push(disposable);
let tagRequestor = (document: TextDocument, position: Position) => {
let param = client.code2ProtocolConverter.asTextDocumentPositionParams(document, position);
return client.sendRequest(TagCloseRequest.type, param);
};
disposable = activateTagClosing(tagRequestor, { html: true, handlebars: true, razor: true }, 'html.autoClosingTags');
toDispose.push(disposable);
disposable = client.onTelemetry(e => {
if (telemetryReporter) {
telemetryReporter.sendTelemetryEvent(e.key, e.data);
}
});
toDispose.push(disposable);
});
languages.setLanguageConfiguration('html', {
indentationRules: {
increaseIndentPattern: /<(?!\?|(?:area|base|br|col|frame|hr|html|img|input|link|meta|param)\b|[^>]*\/>)([-_\.A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*<\/\1>)|<!--(?!.*-->)|\{[^}"']*$/,
decreaseIndentPattern: /^\s*(<\/(?!html)[-_\.A-Za-z0-9]+\b[^>]*>|-->|\})/
},
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g,
onEnterRules: [
{
beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'),
afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i,
action: { indentAction: IndentAction.IndentOutdent }
},
{
//.........这里部分代码省略.........
示例6: DefinitionMetadataDocumentProvider
disposables.push(server.onServerStart(() => {
// register language feature provider on start
const definitionMetadataDocumentProvider = new DefinitionMetadataDocumentProvider();
definitionMetadataDocumentProvider.register();
localDisposables.push(definitionMetadataDocumentProvider);
const definitionProvider = new DefinitionProvider(server, definitionMetadataDocumentProvider);
localDisposables.push(vscode.languages.registerDefinitionProvider(documentSelector, definitionProvider));
localDisposables.push(vscode.languages.registerDefinitionProvider({ scheme: definitionMetadataDocumentProvider.scheme }, definitionProvider));
localDisposables.push(vscode.languages.registerImplementationProvider(documentSelector, new ImplementationProvider(server)));
const testManager = new TestManager(server, eventStream);
localDisposables.push(testManager);
localDisposables.push(vscode.languages.registerCodeLensProvider(documentSelector, new CodeLensProvider(server, testManager)));
localDisposables.push(vscode.languages.registerDocumentHighlightProvider(documentSelector, new DocumentHighlightProvider(server)));
localDisposables.push(vscode.languages.registerDocumentSymbolProvider(documentSelector, new DocumentSymbolProvider(server)));
localDisposables.push(vscode.languages.registerReferenceProvider(documentSelector, new ReferenceProvider(server)));
localDisposables.push(vscode.languages.registerHoverProvider(documentSelector, new HoverProvider(server)));
localDisposables.push(vscode.languages.registerRenameProvider(documentSelector, new RenameProvider(server)));
if (options.useFormatting) {
localDisposables.push(vscode.languages.registerDocumentRangeFormattingEditProvider(documentSelector, new FormatProvider(server)));
localDisposables.push(vscode.languages.registerOnTypeFormattingEditProvider(documentSelector, new FormatProvider(server), '}', ';'));
}
localDisposables.push(vscode.languages.registerCompletionItemProvider(documentSelector, new CompletionItemProvider(server), '.', ' '));
localDisposables.push(vscode.languages.registerWorkspaceSymbolProvider(new WorkspaceSymbolProvider(server)));
localDisposables.push(vscode.languages.registerSignatureHelpProvider(documentSelector, new SignatureHelpProvider(server), '(', ','));
const codeActionProvider = new CodeActionProvider(server);
localDisposables.push(codeActionProvider);
localDisposables.push(vscode.languages.registerCodeActionsProvider(documentSelector, codeActionProvider));
localDisposables.push(reportDiagnostics(server, advisor));
localDisposables.push(forwardChanges(server));
}));
示例7:
Object.keys(includedLanguages).forEach(language => {
const provider = vscode.languages.registerCompletionItemProvider(language, completionProvider, ...LANGUAGE_MODES[includedLanguages[language]]);
context.subscriptions.push(provider);
});
示例8: WorkspaceSymbolProvider
this.description.modeIds.forEach(modeId => {
let selector: DocumentFilter = { scheme: 'file', language: modeId };
languages.registerCompletionItemProvider(selector, this.completionItemProvider, '.');
languages.registerHoverProvider(selector, hoverProvider);
languages.registerDefinitionProvider(selector, definitionProvider);
languages.registerDocumentHighlightProvider(selector, documentHighlightProvider);
languages.registerReferenceProvider(selector, referenceProvider);
languages.registerDocumentSymbolProvider(selector, documentSymbolProvider);
languages.registerSignatureHelpProvider(selector, signatureHelpProvider, '(', ',');
languages.registerRenameProvider(selector, renameProvider);
languages.registerDocumentRangeFormattingEditProvider(selector, this.formattingProvider);
languages.registerOnTypeFormattingEditProvider(selector, this.formattingProvider, ';', '}', '\n');
languages.registerWorkspaceSymbolProvider(new WorkspaceSymbolProvider(client, modeId));
languages.setLanguageConfiguration(modeId, {
indentationRules: {
// ^(.*\*/)?\s*\}.*$
decreaseIndentPattern: /^(.*\*\/)?\s*\}.*$/,
// ^.*\{[^}"']*$
increaseIndentPattern: /^.*\{[^}"']*$/
},
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')'],
],
onEnterRules: [
{
// e.g. /** | */
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: IndentAction.IndentOutdent, appendText: ' * ' }
},
{
// e.g. /** ...|
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: IndentAction.None, appendText: ' * ' }
},
{
// e.g. * ...|
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: IndentAction.None, appendText: '* ' }
},
{
// e.g. */|
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
},
{
// e.g. *-----*/|
beforeText: /^(\t|(\ \ ))*\ \*[^/]*\*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
}
],
__electricCharacterSupport: {
docComment: { scope: 'comment.documentation', open: '/**', lineStart: ' * ', close: ' */' }
},
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"', notIn: ['string'] },
{ open: '\'', close: '\'', notIn: ['string', 'comment'] },
{ open: '`', close: '`', notIn: ['string', 'comment'] }
]
});
});
示例9: ConfigurationDependentRegistration
return new ConfigurationDependentRegistration('jsDocCompletion', 'enabled', () => {
return vscode.languages.registerCompletionItemProvider(selector,
new JsDocCompletionProvider(client),
'*');
});
示例10: activate
//.........这里部分代码省略.........
return doc.getText();
}, error => {
return Promise.reject(error);
});
} else {
const headers = { 'Accept-Encoding': 'gzip, deflate' };
return xhr({ url: uriPath, followRedirects: 5, headers }).then(response => {
return response.responseText;
}, (error: XHRResponse) => {
return Promise.reject(error.responseText || getErrorStatusDescription(error.status) || error.toString());
});
}
});
let handleContentChange = (uri: Uri) => {
if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
}
};
let handleActiveEditorChange = (activeEditor?: TextEditor) => {
if (!activeEditor) {
return;
}
const activeDocUri = activeEditor.document.uri.toString();
if (activeDocUri && fileSchemaErrors.has(activeDocUri)) {
schemaResolutionErrorStatusBarItem.show();
} else {
schemaResolutionErrorStatusBarItem.hide();
}
};
toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
toDispose.push(workspace.onDidCloseTextDocument(d => {
handleContentChange(d.uri);
fileSchemaErrors.delete(d.uri.toString());
}));
toDispose.push(window.onDidChangeActiveTextEditor(handleActiveEditorChange));
let handleRetryResolveSchemaCommand = () => {
if (window.activeTextEditor) {
schemaResolutionErrorStatusBarItem.text = '$(watch)';
const activeDocUri = window.activeTextEditor.document.uri.toString();
client.sendRequest(ForceValidateRequest.type, activeDocUri).then((diagnostics) => {
const schemaErrorIndex = diagnostics.findIndex(candidate => candidate.code === /* SchemaResolveError */ 0x300);
if (schemaErrorIndex !== -1) {
// Show schema resolution errors in status bar only; ref: #51032
const schemaResolveDiagnostic = diagnostics[schemaErrorIndex];
fileSchemaErrors.set(activeDocUri, schemaResolveDiagnostic.message);
} else {
schemaResolutionErrorStatusBarItem.hide();
}
schemaResolutionErrorStatusBarItem.text = '$(alert)';
});
}
};
toDispose.push(commands.registerCommand('_json.retryResolveSchema', handleRetryResolveSchemaCommand));
client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));
extensions.onDidChange(_ => {
client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));
});
documentSelector.forEach(selector => {
toDispose.push(languages.registerSelectionRangeProvider(selector, {
async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[]> {
const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(document);
const rawResult = await client.sendRequest<SelectionRange[][]>('$/textDocument/selectionRanges', { textDocument, positions: positions.map(client.code2ProtocolConverter.asPosition) });
if (Array.isArray(rawResult)) {
return rawResult.map(rawSelectionRanges => {
return rawSelectionRanges.reduceRight((parent: SelectionRange | undefined, selectionRange: SelectionRange) => {
return {
range: client.protocol2CodeConverter.asRange(selectionRange.range),
parent,
};
}, undefined)!;
});
}
return [];
}
}));
});
});
let languageConfiguration: LanguageConfiguration = {
wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|[^\s{}\[\],:]+/,
indentationRules: {
increaseIndentPattern: /^.*(\{[^}]*|\[[^\]]*)$/,
decreaseIndentPattern: /^\s*[}\]],?\s*$/
}
};
languages.setLanguageConfiguration('json', languageConfiguration);
languages.setLanguageConfiguration('jsonc', languageConfiguration);
}