vscode#languages TypeScript Examples
The following examples show how to use
vscode#languages.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RegisterProvider.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* RegisterProvider constructor.
*/
constructor() {
/**
* ALHoverProvider is providing Tooltip information for procedures and objects.
*/
languages.registerHoverProvider({
scheme: 'file',
language: 'al'
}, new ALHoverProvider());
/**
* ALDocCommentProvider is providing AL XML documentation templates after typing '///'.
*/
languages.registerCompletionItemProvider({
scheme: 'file',
language: 'al'
}, new ALDocCommentProvider(),
'/');
/**
* ALInheritDocDefinitionProvider is providing AL XML documentation for inherit objects.
*/
languages.registerDefinitionProvider({
scheme: 'file',
language: 'al'
}, new ALInheritDocDefinitionProvider());
/**
* ALDocumentationQuickFixProvider is providing CodeActions to fix broken or missing XML documentations.
*/
languages.registerCodeActionsProvider({
scheme: 'file',
language: 'al'
}, new ALDocumentationQuickFixProvider());
this.RegisterCodeActions();
}
Example #2
Source File: parser.ts From vscode-discord with MIT License | 6 votes |
public diagnosticsChange() {
const diag = languages.getDiagnostics();
let counted: number = 0;
diag.forEach((i) => {
if (i[1])
i[1].forEach((i) => {
if (
i.severity == DiagnosticSeverity.Warning ||
i.severity == DiagnosticSeverity.Error
)
counted++;
});
});
this.problems = counted;
}
Example #3
Source File: listener.ts From vscode-discord with MIT License | 6 votes |
public listen() {
// just make sure that no double registration happens
this.dispose();
const fileSwitch = window.onDidChangeActiveTextEditor,
fileEdit = workspace.onDidChangeTextDocument,
debugStart = debug.onDidStartDebugSession,
debugEnd = debug.onDidTerminateDebugSession,
diagnostictsChange = languages.onDidChangeDiagnostics;
if (this.config.get("showFile"))
this.disposables.push(
fileSwitch((e: TextEditor) => this.parser.fileSwitch(e)),
fileEdit((e: TextDocumentChangeEvent) =>
this.parser.fileEdit(e)
)
);
if (this.config.get("showDebugging"))
this.disposables.push(
debugStart(() => this.parser.toggleDebug()),
debugEnd(() => this.parser.toggleDebug())
);
if (this.config.get("showProblems"))
this.disposables.push(
diagnostictsChange(() => this.parser.diagnosticsChange())
);
}
Example #4
Source File: extension.test.ts From typescript-explicit-types with GNU General Public License v3.0 | 6 votes |
performTypeGeneration = async (element: string, document: TextDocument, { expectedType }: TypeGenerationOptions = {}) => {
let fileText = document.getText();
const f1Position = fileText.indexOf(element);
const wordRange = document.getWordRangeAtPosition(document.positionAt(f1Position));
if (!wordRange) {
assert.fail(`${element} not found in file`);
}
const actions = await executeCodeActionProvider(document.uri, wordRange);
const generateAction = actions?.find((action) => action.command!.command === commandId);
if (!generateAction) assert.fail('Generate action not found');
const command = generateAction.command!;
await commands.executeCommand.apply(null, [command.command, ...command.arguments!]);
if (expectedType) {
fileText = document.getText();
const res = fileText.includes(`${element}: ${expectedType}`);
assert.strictEqual(res, true);
} else {
const diagnostics = languages
.getDiagnostics(document.uri)
.filter((x) => [DiagnosticSeverity.Error, DiagnosticSeverity.Warning].includes(x.severity));
assert.strictEqual(diagnostics.length, 0, JSON.stringify(diagnostics));
}
}
Example #5
Source File: extension.ts From typescript-explicit-types with GNU General Public License v3.0 | 6 votes |
export function activate(context: ExtensionContext) {
const selector: DocumentFilter[] = [];
for (const language of ['typescript', 'typescriptreact']) {
selector.push({ language, scheme: 'file' });
selector.push({ language, scheme: 'untitled' });
}
const command = commands.registerCommand(commandId, commandHandler);
const codeActionProvider = languages.registerCodeActionsProvider(selector, new GenereateTypeProvider(), GenereateTypeProvider.metadata);
context.subscriptions.push(command);
context.subscriptions.push(codeActionProvider);
}
Example #6
Source File: completionProvider.ts From memo with MIT License | 6 votes |
activate = (context: ExtensionContext) =>
context.subscriptions.push(
languages.registerCompletionItemProvider(
'markdown',
{
provideCompletionItems,
resolveCompletionItem,
},
'[',
),
)
Example #7
Source File: infoview.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
private async sendPosition() {
const editor = window.activeTextEditor;
if (!editor) return
const loc = this.getLocation(editor);
if (languages.match(this.leanDocs, editor.document) === 0){
// language is not yet 'lean4', but the LeanClient will fire the didSetLanguage event
// in openLean4Document and that's when we can send the position to update the
// InfoView for the newly opened document.
return;
}
// actual editor
if (this.clientsFailed.size > 0){
const client = this.clientProvider.findClient(editor.document.uri.toString())
if (client) {
const folder = client.getWorkspaceFolder()
if (this.clientsFailed.has(folder)){
// send stopped event
const msg = this.clientsFailed.get(folder)
await this.webviewPanel?.api.serverStopped(msg || '');
return;
} else {
await this.updateStatus(loc)
}
}
} else {
await this.updateStatus(loc)
}
}
Example #8
Source File: infoview.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
private async autoOpen() : Promise<boolean> {
if (!this.webviewPanel && !this.autoOpened && getInfoViewAutoOpen() && window.activeTextEditor) {
// only auto-open for lean files, not for markdown.
if (languages.match(this.leanDocs, window.activeTextEditor.document)) {
// remember we've auto opened during this session so if user closes it it remains closed.
this.autoOpened = true;
await this.openPreview(window.activeTextEditor);
return true;
}
}
return false;
}
Example #9
Source File: docview.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
private async example(file: string) {
const uri = Uri.parse(file)
if (uri.scheme === 'http' || uri.scheme === 'https') {
const data = await this.httpGet(uri);
void this.tryIt('-- example \n' + data);
} else {
const doc = await workspace.openTextDocument(Uri.parse(file));
void languages.setTextDocumentLanguage(doc, 'lean4')
await window.showTextDocument(doc, ViewColumn.One);
}
}
Example #10
Source File: AbbreviationRewriterFeature.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
private shouldEnableRewriterForEditor(editor: TextEditor): boolean {
if (!this.config.inputModeEnabled.get()) {
return false;
}
if (!languages.match(this.config.languages.get(), editor.document)) {
return false;
}
return true;
}
Example #11
Source File: index.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
constructor() {
const config = new AbbreviationConfig();
this.abbreviations = new AbbreviationProvider(config);
this.disposables.push(
autorunDisposable((disposables) => {
disposables.push(
languages.registerHoverProvider(
config.languages.get(),
new AbbreviationHoverProvider(config, this.abbreviations)
)
);
}),
new AbbreviationRewriterFeature(config, this.abbreviations)
);
}
Example #12
Source File: holes.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
constructor(private server: Server, private leanDocs: DocumentSelector) {
this.subscriptions.push(
this.collection = languages.createDiagnosticCollection('lean holes'),
commands.registerCommand(this.executeHoleCommand, (file, line, column, action) =>
this.execute(file, line, column, action)),
languages.registerCodeActionsProvider(this.leanDocs, this),
window.onDidChangeVisibleTextEditors(() => this.refresh()),
this.server.statusChanged.on(() => this.refresh()),
);
}
Example #13
Source File: holes.ts From vscode-lean4 with Apache License 2.0 | 6 votes |
private async refresh() {
const ress = await Promise.all(window.visibleTextEditors
.filter((editor) => languages.match(this.leanDocs, editor.document))
.map((editor) => this.server.allHoleCommands(editor.document.fileName)));
this.holes = [];
for (const res of ress) {
[].push.apply(this.holes, res.holes);
}
const holesPerFile = new Map<string, HoleCommands[]>();
for (const hole of this.holes) {
if (!holesPerFile.get(hole.file)) { holesPerFile.set(hole.file, []); }
holesPerFile.get(hole.file).push(hole);
}
this.collection.clear();
for (const file of holesPerFile.keys()) {
this.collection.set(Uri.file(file),
holesPerFile.get(file).map((hole) =>
new Diagnostic(mkRange(hole),
'Hole: ' + hole.results.map((a) => a.name).join('/'),
DiagnosticSeverity.Hint)));
}
}
Example #14
Source File: index.ts From vscode-dbt-power-user with MIT License | 6 votes |
constructor(
private modelDefinitionProvider: ModelDefinitionProvider,
private macroDefinitionProvider: MacroDefinitionProvider,
private sourceDefinitionProvider: SourceDefinitionProvider
) {
this.disposables.push(
languages.registerDefinitionProvider(
DBTPowerUserExtension.DBT_MODE,
this.modelDefinitionProvider
),
languages.registerDefinitionProvider(
DBTPowerUserExtension.DBT_MODE,
this.macroDefinitionProvider
),
languages.registerDefinitionProvider(
DBTPowerUserExtension.DBT_MODE,
this.sourceDefinitionProvider
)
);
}
Example #15
Source File: documentHighlights.ts From vscode-todo-md with MIT License | 6 votes |
export function updateDocumentHighlights() {
Global.documentHighlightsDisposable?.dispose();
Global.documentHighlightsDisposable = languages.registerDocumentHighlightProvider(
getTodoMdFileDocumentSelector(),
{
provideDocumentHighlights(document, position) {
const wordRange = getWordRangeAtPosition(document, position);
if (!wordRange) {
return [];
}
const wordText = document.getText(wordRange);
const word = parseWord(wordText, position.line, wordRange.start.character);
let resultRanges: Range[] = [];
if (word.type === 'tags') {
resultRanges = getAllTagRangesInDocument(word, position);
} else if (word.type === 'context') {
resultRanges = getAllContextRangesInDocument(word, position);
} else if (word.type === 'project') {
resultRanges = getAllProjectRangesInDocument(word, position);
}
return resultRanges.map(range => new DocumentHighlight(range, DocumentHighlightKind.Read));
},
},
);
}
Example #16
Source File: extension.ts From al-objid with MIT License | 6 votes |
export function activate(context: ExtensionContext) {
ConsumptionWarnings.instance.setContext(context);
Telemetry.instance.setContext(context);
context.subscriptions.push(
...registerCommands(),
// Tree views
new RangeExplorerView("ninja-rangeExplorer"),
// CodeActions provider
languages.registerCodeActionsProvider("jsonc", new ObjIdConfigActionProvider()),
// Other VS Code features
languages.registerCompletionItemProvider("al", new NextObjectIdCompletionProvider()),
// Other Ninja features
WorkspaceManager.instance,
AuthorizationStatusBar.instance.getDisposables(),
Output.instance.getDisposables(),
Config.instance.getDisposables(),
new PollingHandler(),
new NewsHandler(context),
new HttpStatusHandler(context).getDisposables(),
ParserConnector.instance,
Diagnostics.instance,
ConsumptionCache.instance
);
ReleaseNotesHandler.instance.check(context);
}
Example #17
Source File: registerCFGLinter.ts From sourcepawn-vscode with MIT License | 6 votes |
export function registerCFGLinter(context: ExtensionContext) {
context.subscriptions.push(languages.createDiagnosticCollection("cfg"));
context.subscriptions.push(
window.onDidChangeActiveTextEditor((editor) => {
if (editor) {
refreshCfgDiagnostics(editor.document);
}
})
);
context.subscriptions.push(
Workspace.onDidCloseTextDocument((document) => {
cfgDiagnostics.delete(document.uri);
})
);
}
Example #18
Source File: registerSPLinter.ts From sourcepawn-vscode with MIT License | 6 votes |
export function registerSPLinter(context: ExtensionContext) {
context.subscriptions.push(languages.createDiagnosticCollection("compiler"));
context.subscriptions.push(
window.onDidChangeActiveTextEditor((editor) => {
if (editor) {
refreshDiagnostics(editor.document);
refreshCfgDiagnostics(editor.document);
}
})
);
context.subscriptions.push(
Workspace.onDidCloseTextDocument((document) => {
compilerDiagnostics.delete(document.uri);
delete throttles[document.uri.path];
})
);
}
Example #19
Source File: extension.ts From plugin-vscode with Apache License 2.0 | 6 votes |
registerPreInitHandlers(): any {
// We need to restart VSCode if we change plugin configurations.
workspace.onDidChangeConfiguration((params: ConfigurationChangeEvent) => {
if (params.affectsConfiguration(BALLERINA_HOME) ||
params.affectsConfiguration(OVERRIDE_BALLERINA_HOME)) {
this.showMsgAndRestart(CONFIG_CHANGED);
}
});
languages.setLanguageConfiguration('ballerina', {
onEnterRules: [
{
beforeText: new RegExp('^\\s*#'),
action: {
appendText: '# ',
indentAction: IndentAction.None,
}
}
]
});
}
Example #20
Source File: activator.ts From plugin-vscode with Apache License 2.0 | 6 votes |
export function activate(ballerinaExtInstance: BallerinaExtension) {
if (!ballerinaExtInstance.context || !ballerinaExtInstance.langClient || !ballerinaExtInstance.isSwanLake) {
return;
}
ballerinaExtInstance.context!.subscriptions.push(new StringSplitFeature(new StringSplitter(),
ballerinaExtInstance));
if (ballerinaExtInstance.isAllCodeLensEnabled() || ballerinaExtInstance.isExecutorCodeLensEnabled()) {
languages.registerCodeLensProvider([{ language: LANGUAGE.BALLERINA }], new ExecutorCodeLensProvider(ballerinaExtInstance));
}
}
Example #21
Source File: referenceProvider.ts From vscode-todo-md with MIT License | 6 votes |
export function updateReferenceProvider() {
Global.referenceProviderDisposable?.dispose();
Global.referenceProviderDisposable = languages.registerReferenceProvider(
getTodoMdFileDocumentSelector(),
{
provideReferences(document, position, context) {
const range = getWordRangeAtPosition(document, position);
if (!range) {
return undefined;
}
const word = document.getText(range);
const parsedWord = parseWord(word, position.line, range.start.character);
let resultRanges: Range[] = [];
if (parsedWord.type === 'tags') {
resultRanges = getAllTagRangesInDocument(parsedWord, position);
} else if (parsedWord.type === 'project') {
resultRanges = getAllProjectRangesInDocument(parsedWord, position);
} else if (parsedWord.type === 'context') {
resultRanges = getAllContextRangesInDocument(parsedWord, position);
}
return resultRanges.map(r => new Location(document.uri, r));
},
},
);
}
Example #22
Source File: extension.ts From format-imports-vscode with MIT License | 6 votes |
// This method is called when your extension is activated.
// Your extension is activated the very first time the command is executed.
export function activate(context: ExtensionContext) {
initChannel();
const log = initLog(vscChannel);
log.info('os:', osInfo());
log.info('vscode:', vscodeInfo());
// log.info('extensions:', extensionsInfo());
const sortCommand = commands.registerTextEditorCommand(
'tsImportSorter.command.sortImports',
sortImportsByCommand,
);
const beforeSave = workspace.onWillSaveTextDocument(sortImportsBeforeSavingDocument);
context.subscriptions.push(
sortCommand,
beforeSave,
languages.registerCodeActionsProvider(
['javascript', 'javascriptreact', 'typescript', 'typescriptreact'],
new SortActionProvider(),
{ providedCodeActionKinds: SortActionProvider.ACTION_KINDS },
),
);
// let lastActiveDocument: TextDocument | undefined;
// const editorChanged = window.onDidChangeActiveTextEditor(event => {
// window.showInformationMessage(lastActiveDocument?.fileName ?? 'nil');
// lastActiveDocument = event?.document;
// });
// const focusChanged = window.onDidChangeWindowState(event => {
// if (event.focused) return;
// window.showInformationMessage('Focus changed: ' + lastActiveDocument?.fileName);
// });
// context.subscriptions.push(editorChanged, focusChanged);
}
Example #23
Source File: codeActionProvider.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
function activate(context: ExtensionContext) {
context.subscriptions.push(
languages.registerCodeActionsProvider(
"markdown",
doctorFrontmatterProvider
),
languages.registerCodeActionsProvider("markdown", refactorProvider)
);
}
Example #24
Source File: completionProvider.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
activate = (context: ExtensionContext) => {
context.subscriptions.push(
languages.registerCompletionItemProvider(
"markdown",
{
provideCompletionItems,
},
"[", // for wikilinks and references
"#", // for hashtags
"@" // for user tags
)
);
context.subscriptions.push(
languages.registerCompletionItemProvider(
"markdown",
{
provideCompletionItems: provideBlockCompletionItems,
},
"#",
"^"
)
);
}
Example #25
Source File: index.ts From vscode-dbt-power-user with MIT License | 6 votes |
constructor(
private macroAutocompletionProvider: MacroAutocompletionProvider,
private modelAutocompletionProvider: ModelAutocompletionProvider,
private sourceAutocompletionProvider: SourceAutocompletionProvider
) {
this.disposables.push(
languages.registerCompletionItemProvider(
DBTPowerUserExtension.DBT_MODE,
this.macroAutocompletionProvider
),
languages.registerCompletionItemProvider(
DBTPowerUserExtension.DBT_MODE,
this.modelAutocompletionProvider,
"'",
'"'
),
languages.registerCompletionItemProvider(
DBTPowerUserExtension.DBT_MODE,
this.sourceAutocompletionProvider,
"'",
'"'
),
);
}
Example #26
Source File: renameProvider.ts From vscode-todo-md with MIT License | 5 votes |
export function updateRenameProvider() {
Global.renameProviderDisposable?.dispose();
Global.renameProviderDisposable = languages.registerRenameProvider(
getTodoMdFileDocumentSelector(),
{
provideRenameEdits(document, position, newName) {
const range = getWordRangeAtPosition(document, position);
if (!range) {
return undefined;
}
const word = document.getText(range);
const parsedWord = parseWord(word, position.line, range.start.character);
if (parsedWord.type === 'tags') {
const allTagRanges = getAllTagRangesInDocument(parsedWord, position);
const edit = new WorkspaceEdit();
newName = newName[0] === '#' ? newName : `#${newName}`;
for (const tagRange of allTagRanges) {
edit.replace(document.uri, tagRange, newName);
}
return edit;
} else if (parsedWord.type === 'project') {
const allProjectRanges = getAllProjectRangesInDocument(parsedWord, position);
const edit = new WorkspaceEdit();
newName = newName[0] === '+' ? newName : `+${newName}`;
for (const projectRange of allProjectRanges) {
edit.replace(document.uri, projectRange, newName);
}
return edit;
} else if (parsedWord.type === 'context') {
const allContextRanges = getAllContextRangesInDocument(parsedWord, position);
const edit = new WorkspaceEdit();
newName = newName[0] === '@' ? newName : `@${newName}`;
for (const projectRange of allContextRanges) {
edit.replace(document.uri, projectRange, newName);
}
return edit;
}
return undefined;
},
// async prepareRename(document, position) {// Not worth it
// const range = getWordRangeAtPosition(document, position);
// if (!range) {
// return undefined;
// }
// const word = document.getText(range);
// const parsedWord = parseWord(word, position.line, range.start.character);
// if (parsedWord.type !== 'tags' && parsedWord.type !== 'project' && parsedWord.type !== 'context') {
// return Promise.reject('You cannot rename this element');
// }
// return {
// range,
// placeholder: word.slice(1),
// };
// },
},
);
}
Example #27
Source File: events.ts From vscode-todo-md with MIT License | 5 votes |
/**
* Match Uri of editor against a glob specified by user.
*/
export function isTheRightFileName(editor: TextEditor): boolean {
return languages.match({
pattern: $config.activatePattern,
}, editor.document) !== 0;
}
Example #28
Source File: stripeLinter.ts From vscode-stripe with MIT License | 5 votes |
diagnosticCollection: DiagnosticCollection =
languages.createDiagnosticCollection('StripeHardCodedAPIKeys')
Example #29
Source File: Diagnostics.ts From al-objid with MIT License | 5 votes |
private constructor() {
this._diagnostics = languages.createDiagnosticCollection("al-objid");
}