vscode#CancellationToken TypeScript Examples
The following examples show how to use
vscode#CancellationToken.
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: utils.ts From memo with MIT License | 7 votes |
findNonIgnoredFiles = async (
include: GlobPattern,
excludeParam?: string | null,
maxResults?: number,
token?: CancellationToken,
): Promise<Uri[]> => {
const exclude = [
...Object.keys(getConfigProperty('search.exclude', {})),
...Object.keys(getConfigProperty('file.exclude', {})),
...(typeof excludeParam === 'string' ? [excludeParam] : []),
].join(',');
const files = await workspace.findFiles(include, `{${exclude}}`, maxResults, token);
return files;
}
Example #2
Source File: utils.ts From joplin-utils with MIT License | 7 votes |
findNonIgnoredFiles = async (
include: GlobPattern,
excludeParam?: string | null,
maxResults?: number,
token?: CancellationToken,
): Promise<Uri[]> => {
const exclude = [
...Object.keys(getConfigProperty('search.exclude', {})),
...Object.keys(getConfigProperty('file.exclude', {})),
...(typeof excludeParam === 'string' ? [excludeParam] : []),
].join(',')
return workspace.findFiles(include, `{${exclude}}`, maxResults, token)
}
Example #3
Source File: comment-lens-provider.ts From vscode-code-review with MIT License | 6 votes |
public provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]> {
return this.exportFactory.getFilesContainingComments().then((filesWithComments) => {
const codeLenses: CodeLens[] = [];
filesWithComments.forEach((el) => {
if (document.fileName.endsWith(el.data.group)) {
el.data.lines.forEach((csvEntry) => {
const fileSection: ReviewFileExportSection = {
group: csvEntry.filename,
lines: el.data.lines,
};
const csvRef: CsvEntry | undefined = csvEntry;
const prio = Number(csvEntry.priority); // be sure the value is a number
const priorityString = prio
? ` | Priority: ${csvEntry.priority}${symbolForPriority(Number(csvEntry.priority))}`
: '';
const command: Command = {
title: `Code Review: ${csvEntry.title}${priorityString}`,
tooltip: csvEntry.comment,
command: 'codeReview.openSelection',
arguments: [fileSection, csvRef],
};
rangesFromStringDefinition(csvEntry.lines).forEach((range: Range) => {
codeLenses.push(new CodeLens(range, command));
});
});
}
});
return codeLenses;
});
}
Example #4
Source File: spHoverProvider.ts From sourcepawn-vscode with MIT License | 6 votes |
export function hoverProvider(
itemsRepo: ItemsRepository,
document: TextDocument,
position: Position,
token: CancellationToken
): Hover | undefined {
const items = itemsRepo.getItemFromPosition(document, position);
orderItems(items);
if (items.length > 0 && items[0].toHover()) {
return items[0].toHover() as Hover;
}
return undefined;
}
Example #5
Source File: modelDefinitionProvider.ts From vscode-dbt-power-user with MIT License | 6 votes |
provideDefinition(
document: TextDocument,
position: Position,
token: CancellationToken
): ProviderResult<Definition | DefinitionLink[]> {
return new Promise((resolve, reject) => {
const hover = document.getText(document.getWordRangeAtPosition(position));
const word = document.getText(
document.getWordRangeAtPosition(
position,
ModelDefinitionProvider.IS_REF
)
);
if (word !== undefined && hover !== "ref") {
const dbtModel = word.match(ModelDefinitionProvider.GET_DBT_MODEL);
if (dbtModel && dbtModel.length === 1) {
const definition = this.getDefinitionFor(dbtModel[0], document.uri);
resolve(definition);
return;
}
}
reject();
});
}
Example #6
Source File: runner.ts From yash with MIT License | 6 votes |
export function runSafeAsync<T>(func: () => Thenable<T>, errorVal: T, errorMessage: string, token: CancellationToken): Thenable<T> {
return new Promise<T>((resolve) => {
setImmediate(async () => {
if (token.isCancellationRequested) {
resolve(cancelValue());
}
return func().then(result => {
if (token.isCancellationRequested) {
resolve(cancelValue());
return;
} else {
resolve(result);
}
}, e => {
console.error(formatError(errorMessage, e));
resolve(errorVal);
});
});
});
}
Example #7
Source File: index.ts From vscode-dbt-power-user with MIT License | 6 votes |
private async executeCommand(
command: DBTCommand,
token?: CancellationToken
): Promise<CommandProcessExecution> {
const { args, cwd } = command.processExecutionParams;
const configText = await workspace.getConfiguration();
const config = JSON.parse(JSON.stringify(configText));
let envVars = {};
if (config.terminal !== undefined && config.terminal.integrated !== undefined && config.terminal.integrated.env !== undefined) {
const env = config.terminal.integrated.env;
for (let prop in env) {
envVars = {
...process.env,
...envVars,
...env[prop],
};
}
}
if (command.commandAsString !== undefined) {
this.terminal.log(`> Executing task: ${command.commandAsString}\n\r`);
if (command.focus) {
this.terminal.show(true);
}
}
return this.commandProcessExecutionFactory.createCommandProcessExecution(
this.pythonPath!,
args,
cwd,
token,
envVars
);
}
Example #8
Source File: command.ts From flatpak-vscode with MIT License | 6 votes |
/**
* Spawn this with using node-pty
* @param terminal Where the output stream will be sent
* @param token For cancellation. This will send SIGINT on the process when cancelled.
*/
spawn(terminal: OutputTerminal, token: CancellationToken): Promise<void> {
const iPty = pty.spawn(this.program, this.args, {
cwd: this.cwd,
})
iPty.onData((data) => {
terminal.append(data)
})
return new Promise((resolve, reject) => {
token.onCancellationRequested(() => {
iPty.kill('SIGINT')
})
iPty.onExit(({ exitCode, signal }) => {
if (exitCode !== 0) {
reject(new Error(`Child process exited with code ${exitCode}`))
return
}
if (signal === 2) { // SIGINT
reject(new Canceled())
return
}
resolve()
})
})
}
Example #9
Source File: utopia-fs.ts From utopia with MIT License | 6 votes |
// FileSearchProvider
async provideFileSearchResults(
query: FileSearchQuery,
options: FileSearchOptions,
_token: CancellationToken,
): Promise<Uri[]> {
// TODO Support all search options
const { result: foundPaths } = await this.filterFilePaths(query.pattern, options.maxResults)
return foundPaths.map((p) => toUtopiaURI(this.projectID, p))
}
Example #10
Source File: spDocCompletions.ts From sourcepawn-vscode with MIT License | 6 votes |
public async provideCompletionItems(
document: TextDocument,
position: Position,
token: CancellationToken
): Promise<CompletionItem[] | undefined> {
if (!document) {
return undefined;
}
let { signature, indent } = await getFullParams(document, position);
if (signature === undefined) {
return undefined;
}
let functionDesc = signature.parameters.map((e) => e.label.toString());
let DocCompletionItem = new SpDocCompletionItem(
position,
functionDesc,
indent
);
return [DocCompletionItem];
}
Example #11
Source File: commandProcessExecution.ts From vscode-dbt-power-user with MIT License | 6 votes |
constructor(
command: string,
args?: string[],
cwd?: string,
token?: CancellationToken,
envVars?: EnvVars
) {
this.commandProcess = spawn(command, args, { cwd: cwd, env: envVars });
if (token !== undefined) {
this.disposables.push(
token.onCancellationRequested(() => {
this.commandProcess.kill("SIGINT");
})
);
}
}
Example #12
Source File: testUtilsV3.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
export function stubCancellationToken(): CancellationToken {
return {
isCancellationRequested: false,
onCancellationRequested: () => {
return {
dispose: () => {},
};
},
};
}
Example #13
Source File: modelAutocompletionProvider.ts From vscode-dbt-power-user with MIT License | 6 votes |
provideCompletionItems(
document: TextDocument,
position: Position,
token: CancellationToken,
context: CompletionContext
): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
const linePrefix = document
.lineAt(position)
.text.substr(0, position.character);
if (
linePrefix.match(ModelAutocompletionProvider.ENDS_WITH_REF) &&
isEnclosedWithinCodeBlock(document, position)
) {
return this.getAutoCompleteItems(document.uri);
}
return undefined;
}
Example #14
Source File: gopExtraInfo.ts From vscode-goplus with Apache License 2.0 | 6 votes |
public provideHover(document: TextDocument, position: Position, token: CancellationToken): Thenable<Hover> {
if (!this.goPlusConfig) {
this.goPlusConfig = getGoPlusConfig(document.uri);
}
let goPlusConfig = this.goPlusConfig;
// Temporary fix to fall back to godoc if guru is the set docsTool
if (goPlusConfig['docsTool'] === 'guru') {
goPlusConfig = Object.assign({}, goPlusConfig, { docsTool: 'godoc' });
}
return definitionLocation(document, position, goPlusConfig, true, token).then(
(definitionInfo) => {
if (definitionInfo == null) {
return null;
}
const lines = definitionInfo.declarationlines
.filter((line) => line !== '')
.map((line) => line.replace(/\t/g, ' '));
let text;
text = lines.join('\n').replace(/\n+$/, '');
const hoverTexts = new vscode.MarkdownString();
hoverTexts.appendCodeblock(text, 'go');
if (definitionInfo.doc != null) {
hoverTexts.appendMarkdown(definitionInfo.doc);
}
const hover = new Hover(hoverTexts);
return hover;
},
() => {
return null;
}
);
}
Example #15
Source File: macroAutocompletionProvider.ts From vscode-dbt-power-user with MIT License | 6 votes |
provideCompletionItems(
document: TextDocument,
position: Position,
token: CancellationToken,
context: CompletionContext
): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
const range = document.getWordRangeAtPosition(position);
if (range && isEnclosedWithinCodeBlock(document, range)) {
return this.getAutoCompleteItems(document.uri);
}
return undefined;
}
Example #16
Source File: extension.ts From vscode-riscv-venus with MIT License | 6 votes |
/**
* Massage a debug configuration just before a debug session is being launched,
* e.g. add all missing attributes to the debug configuration.
*/
resolveDebugConfiguration(folder: WorkspaceFolder | undefined, config: DebugConfiguration, token?: CancellationToken): ProviderResult<DebugConfiguration> {
// if launch.json is missing or empty
if (!config.type && !config.request && !config.name) {
const editor = vscode.window.activeTextEditor;
if (editor && editor.document.languageId === 'riscv') {
config.type = 'venus';
config.name = 'Launch';
config.request = 'launch';
config.program = '${file}';
config.stopOnEntry = true;
}
}
if (!config.program) {
return vscode.window.showInformationMessage("Cannot find a program to debug").then(_ => {
return undefined; // abort launch
});
}
return config;
}
Example #17
Source File: DrawioEditorProviderBinary.ts From vscode-drawio with GNU General Public License v3.0 | 6 votes |
public async resolveCustomEditor(
document: DrawioBinaryDocument,
webviewPanel: WebviewPanel,
token: CancellationToken
): Promise<void> {
try {
const editor =
await this.drawioEditorService.createDrawioEditorInWebview(
webviewPanel,
{ kind: "drawio", document },
{ isReadOnly: false }
);
document.setDrawioClient(editor.drawioClient);
} catch (e) {
window.showErrorMessage(`Failed to open diagram: ${e}`);
throw e;
}
}
Example #18
Source File: spDefinitionProvider.ts From sourcepawn-vscode with MIT License | 6 votes |
export function definitionsProvider(
itemsRepo: ItemsRepository,
document: TextDocument,
position: Position,
token: CancellationToken
): LocationLink[] {
const items = itemsRepo.getItemFromPosition(document, position);
if (items.length > 0) {
return items
.map((e) => e.toDefinitionItem())
.filter((e) => e !== undefined);
}
return [];
}
Example #19
Source File: HttpRequestHandler.ts From vscode-file-downloader with MIT License | 6 votes |
public async get(
url: string,
timeoutInMs: number,
retries: number,
retryDelayInMs: number,
cancellationToken?: CancellationToken,
onDownloadProgressChange?: (downloadedBytes: number, totalBytes: number) => void
): Promise<Readable> {
const requestFn = () => this.getRequestHelper(
url,
timeoutInMs,
cancellationToken,
onDownloadProgressChange
);
const errorHandlerFn = (error: Error) => {
const statusCode = (error as any)?.response?.status;
if (statusCode != null && 400 <= statusCode && statusCode < 500) {
throw error;
}
};
return RetryUtility.exponentialRetryAsync(requestFn, `HttpRequestHandler.get`, retries, retryDelayInMs, errorHandlerFn);
}
Example #20
Source File: hoverProvider.ts From vscode-stripe with MIT License | 6 votes |
async function provideHoverCommand(
languageClient: LanguageClient,
params: TextDocumentPositionParams,
token: CancellationToken,
): Promise<Command[] | undefined> {
const response = await languageClient.sendRequest(
FindLinks.type,
{
type: 'superImplementation',
position: params,
},
token,
);
if (response && response.length) {
const location = response[0];
let tooltip;
if (location.kind === 'method') {
tooltip = `Go to super method '${location.displayName}'`;
} else {
tooltip = `Go to super implementation '${location.displayName}'`;
}
return [
{
title: 'Go to Super Implementation',
command: javaCommands.NAVIGATE_TO_SUPER_IMPLEMENTATION_COMMAND,
tooltip,
arguments: [
{
uri: encodeBase64(location.uri),
range: location.range,
},
],
},
];
}
}
Example #21
Source File: cfgFormat.ts From sourcepawn-vscode with MIT License | 6 votes |
public provideDocumentFormattingEdits(
document: TextDocument,
options: FormattingOptions,
token: CancellationToken
): ProviderResult<TextEdit[]> {
let workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
// Get the user's settings.
let insertSpaces: boolean =
Workspace.getConfiguration("editor", workspaceFolder).get(
"insertSpaces"
) || false;
let tabSize: number =
Workspace.getConfiguration("editor", workspaceFolder).get("tabSize") || 2;
// Apply user settings
const start = new Position(0, 0);
const end = new Position(
document.lineCount - 1,
document.lineAt(document.lineCount - 1).text.length
);
let range = new Range(start, end);
let text = formatCFGText(document.getText(), insertSpaces, tabSize);
// If process failed,
if (text === "") {
window.showErrorMessage(
"The formatter failed to run, check the console for more details."
);
return undefined;
}
return [new TextEdit(range, text)];
}
Example #22
Source File: hoverProvider.ts From vscode-stripe with MIT License | 6 votes |
function createClientHoverProvider(languageClient: LanguageClient): JavaHoverProvider {
const hoverProvider: JavaHoverProvider = new JavaHoverProvider(languageClient);
registerHoverCommand(async (params: TextDocumentPositionParams, token: CancellationToken) => {
const command = await provideHoverCommand(languageClient, params, token);
return command;
});
return hoverProvider;
}
Example #23
Source File: spProviders.ts From sourcepawn-vscode with MIT License | 6 votes |
public async provideRenameEdits(
document: TextDocument,
position: Position,
newName: string,
token: CancellationToken
): Promise<WorkspaceEdit> {
return renameProvider(
this.itemsRepository,
position,
document,
newName,
token
);
}
Example #24
Source File: ahkHoverProvider.ts From vscode-autohotkey with MIT License | 6 votes |
public async provideHover(document: TextDocument, position: Position, token: CancellationToken) {
const context = this.buildContext(document, position)
const snippetHover = this.tryGetSnippetHover(context)
if (snippetHover) {
return snippetHover;
}
const method = await Parser.getMethodByName(document, context.word)
if (method) {
const markdonw = new MarkdownString("", true).appendCodeblock(method.full)
if (method.comment) {
markdonw.appendText(method.comment)
}
return new Hover(markdonw)
}
return null
}
Example #25
Source File: element-completion-item-povider.ts From element-ui-helper with MIT License | 6 votes |
/**
* 提供自动完成提示
*
* @param document 文档
* @param position 位置
* @param token token
* @param context 上下文
*/
provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
this._document = document
this._position = position
this.token = token
let tag: TagObject | undefined = this.getPreTag()
let attr = this.getPreAttr()
if (!tag || !/^[E|e]l/.test(tag.text || '')) {
// 如果不是element的标签(E|el开头) 则返回 null 表示没有hover
return null
} else if (this.isAttrValueStart(tag, attr)) {
// 如果是属性值的开始
return this.getAttrValueCompletionItems(tag.text, attr)
} else if (this.isEventStart(tag)) {
// 优先判定事件
return this.getEventCompletionItems(tag.text)
} else if (this.isAttrStart(tag)) {
// 判断属性
return this.getAttrCompletionItems(tag.text)
} else if (this.isTagStart()) {
// 判断标签
return this.getTagCompletionItems(tag.text)
}
return null
}
Example #26
Source File: extension.ts From vscode-crestron-splus with GNU General Public License v3.0 | 6 votes |
public async provideDocumentRangeFormattingEdits(
document: TextDocument,
range: Range,
_options: FormattingOptions,
_token: CancellationToken
): Promise<TextEdit[]> {
return this.provideEdits(document, {
rangeEnd: document.offsetAt(range.end),
rangeStart: document.offsetAt(range.start),
});
}
Example #27
Source File: hoverProvider.ts From vscode-stripe with MIT License | 6 votes |
async getContributedHoverCommands(
params: TextDocumentPositionParams,
token: CancellationToken,
): Promise<Command[]> {
const contributedCommands: Command[] = [];
for (const provideFn of hoverCommandRegistry) {
try {
if (token.isCancellationRequested) {
break;
}
// eslint-disable-next-line no-await-in-loop
const commands = (await provideFn(params, token)) || [];
commands.forEach((command: Command) => {
contributedCommands.push(command);
});
} catch (error) {
return [];
}
}
return contributedCommands;
}
Example #28
Source File: element-hover-provider.ts From element-ui-helper with MIT License | 6 votes |
provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover> {
this._document = document
this._position = position
this._token = token
const tag: TagObject | undefined = this.getTag()
if (!/^[E|e]l/.test(tag?.text || '')) {
// 如果不是element的标签(E|el开头) 则返回 null 表示没有hover
return null
}
const attr = this.getAttr()
const range = this.getHoverRange(attr)
return this.getHoverInstance(tag, attr, range)
}
Example #29
Source File: NextObjectIdCompletionProvider.ts From al-objid with MIT License | 5 votes |
async provideCompletionItems(
document: TextDocument,
position: Position,
token: CancellationToken,
context: CompletionContext
) {
const nextIdContext: NextIdContext = { injectSemicolon: false };
const type = await getTypeAtPosition(document, position, nextIdContext);
if (!type) {
return;
}
const app = WorkspaceManager.instance.getALAppFromUri(document.uri);
if (!app) {
return;
}
const objectId = await Backend.getNextNo(app, type, app.manifest.idRanges, false);
Telemetry.instance.log("getNextNo-fetch", app.hash);
if (showNotificationsIfNecessary(app, objectId) || !objectId) return [];
output.log(`Suggesting object ID auto-complete for ${type} ${objectId.id}`);
if (Array.isArray(objectId.id)) {
if (!objectId.id.length) {
objectId.id.push(0);
}
const items: NextObjectIdCompletionItem[] = [];
const logicalNames: string[] = [];
for (let i = 0; i < objectId.id.length; i++) {
const id = objectId.id[i];
const range = getRangeForId(id as number, app.config.getObjectTypeRanges(type));
if (range && range.description) {
if (logicalNames.includes(range.description)) {
continue;
}
logicalNames.push(range.description);
}
const objectIdCopy = { ...objectId, id };
const deeperContext = {
...nextIdContext,
requireId: id,
additional: { ordinal: i },
} as NextIdContext;
items.push(
new NextObjectIdCompletionItem(
type,
objectIdCopy,
app,
position,
document.uri,
deeperContext,
range
)
);
}
return items;
} else {
return [new NextObjectIdCompletionItem(type, objectId, app, position, document.uri, nextIdContext)];
}
}