vscode#Command TypeScript Examples

The following examples show how to use vscode#Command. 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: comment-lens-provider.ts    From vscode-code-review with MIT License 6 votes vote down vote up
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 #2
Source File: holes.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
provideCodeActions(document: TextDocument, range: Range): Command[] {
        const cmds: Command[] = [];
        for (const hole of this.holes) {
            if (!range.intersection(mkRange(hole))) { continue; }
            for (const action of hole.results) {
                cmds.push({
                    title: action.description,
                    command: this.executeHoleCommand,
                    arguments: [hole.file, hole.start.line, hole.start.column, action.name],
                });
            }
        }
        return cmds;
    }
Example #3
Source File: hoverProvider.ts    From vscode-stripe with MIT License 6 votes vote down vote up
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 #4
Source File: hoverProvider.ts    From vscode-stripe with MIT License 6 votes vote down vote up
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 #5
Source File: taskProvider.ts    From vscode-todo-md with MIT License 6 votes vote down vote up
constructor(
		readonly label: string,
		readonly task: TheTask,
		readonly command: Command,
	) {
		super(label);
		if (task.links.length) {
			this.contextValue = 'link';
		}
		if (task.subtasks.length) {
			if (task.isCollapsed) {
				this.collapsibleState = TreeItemCollapsibleState.Collapsed;
			} else {
				this.collapsibleState = TreeItemCollapsibleState.Expanded;
			}
		}

		if (task.done) {
			this.iconPath = new ThemeIcon('pass', new ThemeColor('todomd.treeViewCompletedTaskIcon'));
		} else {
			// this.iconPath = new ThemeIcon('circle-large-outline');// TODO: maybe
		}
	}
Example #6
Source File: ALDocumentationQuickFix.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
public provideCodeActions(document: TextDocument, range: Range | Selection, context: CodeActionContext, token: CancellationToken): ProviderResult<(CodeAction | Command)[]> {
        this.QuickFixActions = [];

        return new Promise(resolve => {
            resolve(this.ProvideCodeActionsAsync(document, range, context, token));
         });
    }
Example #7
Source File: ALDocumentationQuickFix.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
private async ProvideCodeActionsAsync(document: TextDocument, range: Range | Selection, context: CodeActionContext, token: CancellationToken): Promise<(CodeAction | Command)[] | null | undefined> {
        let alObject: ALObject | null = await ALSyntaxUtil.GetALObject(document);
        if (alObject === null) {
            return;
        }

        context.diagnostics.filter(diagnostics => diagnostics.source === ALXmlDocDiagnosticPrefix).forEach(diagnostic => {
            if (diagnostic === undefined) {
                return;
            }

            let diagCodes: Array<string> = [];
            if (diagnostic.code!.toString().indexOf(',') !== -1) { // multiple diagnostic codes
                diagnostic.code!.toString().split(', ').forEach(diagnosticCode => {
                    diagCodes.push(diagnosticCode);
                });
            } else { // just one diagnostic code
                diagCodes.push(diagnostic.code!.toString());
            }
            diagCodes.forEach(diagnosticCode => {
                let alProcedure: ALProcedure | undefined;
                if ((diagnosticCode !== ALXmlDocDiagnosticCode.ObjectDocumentationMissing) && (diagnosticCode !== ALXmlDocDiagnosticCode.ParameterUnnecessary)) {
                    alProcedure = alObject?.Procedures?.find(alProcedure => (alProcedure.LineNo === range.start.line));
                    if (alProcedure === undefined) {
                        console.error(`[ProvideCodeActionsAsync] - Unable to locate ALProcedure object for diagnostics entry. Please report this error at https://github.com/365businessdev/vscode-alxmldocumentation/issues`);
                        return;
                    }
                }

                switch (diagnosticCode) {
                    case ALXmlDocDiagnosticCode.DocumentationMissing:
                        this.AddDocumentationMissingCodeAction(alProcedure, diagnostic);
                        break;
                    case ALXmlDocDiagnosticCode.SummaryMissing:
                        this.AddSummaryDocumentationMissingCodeAction(alProcedure, diagnostic);
                        break;
                    case ALXmlDocDiagnosticCode.ParameterMissing:
                        this.AddParameterDocumentationMissingCodeAction(alProcedure, diagnostic);
                        break;
                    case ALXmlDocDiagnosticCode.ReturnTypeMissing:
                        this.AddReturnDocumentationMissingCodeAction(alProcedure, diagnostic);
                        break;
                    case ALXmlDocDiagnosticCode.ParameterUnnecessary:
                        this.AddUnnecessaryParameterDocumentationMissingCodeAction(alProcedure, diagnostic);
                        break;
                    case ALXmlDocDiagnosticCode.ObjectDocumentationMissing:
                        this.AddObjectDocumentationMissingCodeAction(alObject, diagnostic);
                        break;
                }
            });

        });
        
        return this.QuickFixActions;
    }
Example #8
Source File: actions.ts    From format-imports-vscode with MIT License 5 votes vote down vote up
provideCodeActions(): ProviderResult<(CodeAction | Command)[]> {
    return SortActionProvider.ACTION_COMMANDS;
  }
Example #9
Source File: versionStatusBar.ts    From vscode-dbt-power-user with MIT License 5 votes vote down vote up
private showTextInStatusBar(text: string, command?: Command) {
    this.statusBar.text = text;
    this.statusBar.command = command;
    this.statusBar.show();
  }
Example #10
Source File: q-conn.ts    From vscode-q with MIT License 5 votes vote down vote up
command?: Command;
Example #11
Source File: hoverProvider.ts    From vscode-stripe with MIT License 5 votes vote down vote up
async provideHover(
    document: TextDocument,
    position: Position,
    token: CancellationToken,
  ): Promise<Hover | undefined> {
    let contents: any[] = [];
    let range;

    const params = {
      textDocument: this.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document),
      position: this.languageClient.code2ProtocolConverter.asPosition(position),
    };

    // get javs doc convent from server
    const hoverResponse = await this.languageClient.sendRequest(HoverRequest.type, params, token);

    // parse for stripe api hover content
    let stripeApiHoverContent;
    if (hoverResponse && hoverResponse.contents && Array.isArray(hoverResponse.contents)) {
      const stripeFullClassPath = Object.entries(hoverResponse.contents[0])
        .filter((item) => item[0] === 'value')
        .filter((item) => item[1].includes('com.stripe.model'));
      if (stripeFullClassPath.length > 0) {
        const stripeMethod = stripeFullClassPath[0][1].split(' ')[1].split('(')[0];
        const url = getJavaApiDocLink(stripeMethod);
        if (url) {
          stripeApiHoverContent = new MarkdownString(
            'See this method in the [Stripe API Reference](' + url + ')',
          );
          stripeApiHoverContent.isTrusted = true;
        }
      }
    }

    if (!!stripeApiHoverContent) {
      contents = contents.concat([stripeApiHoverContent]);
    }

    // get contributed hover commands from third party extensions.
    const contributedCommands: Command[] = await this.getContributedHoverCommands(params, token);

    if (contributedCommands.length > 0) {
      const contributedContent = new MarkdownString(
        contributedCommands.map((command) => this.convertCommandToMarkdown(command)).join(' | '),
      );
      contributedContent.isTrusted = true;
      contents = contents.concat([contributedContent]);
    }

    // combine all hover contents with java docs from server
    const serverHover = this.languageClient.protocol2CodeConverter.asHover(hoverResponse);
    if (serverHover && serverHover.contents) {
      contents = contents.concat(serverHover.contents);
      range = serverHover.range;
    }

    return new Hover(contents, range);
  }
Example #12
Source File: hoverProvider.ts    From vscode-stripe with MIT License 5 votes vote down vote up
private convertCommandToMarkdown(command: Command): string {
    return `[${command.title}](command:${command.command}?${encodeURIComponent(
      JSON.stringify(command.arguments || []),
    )} "${command.tooltip || command.command}")`;
  }
Example #13
Source File: NextObjectIdCompletionItem.ts    From al-objid with MIT License 5 votes vote down vote up
getCompletionCommand(position: Position, uri: Uri, type: string, app: ALApp, objectId: NextObjectIdInfo): Command {
        return {
            command: NinjaCommand.CommitSuggestion,
            title: "",
            arguments: [
                async () => {
                    //TODO Assigning from public range (1..50000) for enum values results in "No more objects..." error
                    output.log(`Committing object ID auto-complete for ${type} ${objectId.id}`, LogLevel.Info);
                    const realId = await Backend.getNextNo(
                        app,
                        type,
                        app.manifest.idRanges,
                        true,
                        objectId.id as number
                    );
                    const notChanged = !realId || this.isIdEqual(realId.id, objectId.id as number);
                    Telemetry.instance.log("getNextNo-commit", app.hash, notChanged ? undefined : "different");
                    if (notChanged) {
                        return;
                    }
                    output.log(
                        `Another user has consumed ${type} ${objectId.id} in the meantime. Retrieved new: ${type} ${realId.id}`,
                        LogLevel.Info
                    );

                    let replacement = `${realId.id}`;
                    if (!realId.available) {
                        if (this._range) {
                            UI.nextId.showNoMoreInLogicalRangeWarning(this._range.description).then(result => {
                                if (result === LABELS.BUTTON_LEARN_MORE) {
                                    showDocument(DOCUMENTS.LOGICAL_RANGES);
                                }
                            });
                        } else {
                            syncIfChosen(app, UI.nextId.showNoMoreNumbersWarning());
                        }
                        replacement = "";
                    }

                    let replace = new WorkspaceEdit();
                    replace.set(uri, [
                        TextEdit.replace(
                            new Range(position, position.translate(0, objectId.id.toString().length)),
                            replacement
                        ),
                    ]);
                    workspace.applyEdit(replace);
                },
            ],
        };
    }