vscode#commands TypeScript Examples

The following examples show how to use vscode#commands. 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 everforest-vscode with MIT License 7 votes vote down vote up
// }}}
  private promptToReload() {
    // {{{
    const action = "Reload";
    window
      .showInformationMessage("Reload required.", action)
      .then((selectedAction) => {
        if (selectedAction === action) {
          commands.executeCommand("workbench.action.reloadWindow");
        }
      });
  }
Example #2
Source File: DoExport.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
constructor() {
        commands.registerCommand('al-xml-doc.exportPdf', () => {
            this.ExportPdf(window.activeTextEditor);
        });

        commands.registerCommand('al-xml-doc.exportMarkdown', () => {
            this.ExportMarkdown(window.activeTextEditor, true);
        });
    
        commands.registerCommand('al-xml-doc.exportProjectToMarkdown', () => {
            this.ExportMarkdown(window.activeTextEditor, false);
        });

        commands.registerCommand('al-xml-doc.deleteExportedMarkdown', () => {
            this.DeleteExistingDocumentationFiles();
        });
        
    }
Example #3
Source File: debugSession.ts    From vscode-autohotkey with MIT License 6 votes vote down vote up
public constructor() {
		super("ahk-debug.txt");

		// this debugger uses zero-based lines and columns
		this.setDebuggerLinesStartAt1(false);
		this.setDebuggerColumnsStartAt1(false);

		this.dispather = new DebugDispather();
		this.dispather.on('break', (reason: string) => {
			this.sendEvent(new StoppedEvent(reason, DebugSession.THREAD_ID));
		}).on('breakpointValidated', (bp: DebugProtocol.Breakpoint) => {
			this.sendEvent(new BreakpointEvent('changed', { verified: bp.verified, id: bp.id } as DebugProtocol.Breakpoint));
		}).on('output', (text) => {
			this.sendEvent(new OutputEvent(`${text}\n`));
			commands.executeCommand('workbench.debug.action.focusRepl')
		}).on('end', () => {
			this.sendEvent(new TerminatedEvent());
		});

	}
Example #4
Source File: driveAuthenticator.ts    From google-drive-vscode with MIT License 6 votes vote down vote up
private showMissingCredentialsMessage(): void {
    const configureButton = 'Configure credentials';
    window.showWarningMessage(`The operation cannot proceed since Google Drive API credentials haven't been configured. Please configure the credentials and try again.`, configureButton)
      .then(selectedButton => {
        if (selectedButton === configureButton) {
          commands.executeCommand(CONFIGURE_CREDENTIALS_COMMAND);
        }
      });
  }
Example #5
Source File: coverage.ts    From gnucobol-debug with GNU General Public License v3.0 6 votes vote down vote up
constructor() {
        workspace.onDidOpenTextDocument(() => {
            this.updateStatus();
        });
        workspace.onDidCloseTextDocument(() => {
            this.updateStatus();
        });
        window.onDidChangeActiveTextEditor(() => {
            this.updateStatus();
        });
        commands.registerCommand(this.COMMAND, () => {
            this.highlight = !this.highlight;
            this.updateStatus();
        });
        this.statusBar.command = this.COMMAND;
    }
Example #6
Source File: changeSMApi.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export async function run(args: any) {
  const optionalSMHomes: OptionalSMAPI[] = Workspace.getConfiguration(
    "sourcepawn"
  ).get("availableAPIs");
  let newSMHomeChoices: QuickPickItem[] = optionalSMHomes.map(
    (optionalHome) => {
      return {
        label: optionalHome.name,
        detail: optionalHome.SMHomePath,
      };
    }
  );

  const QuickPickOptions: QuickPickOptions = {
    canPickMany: false,
  };
  window
    .showQuickPick(newSMHomeChoices, QuickPickOptions)
    .then(async (newSMHome) => {
      if (newSMHome.detail == undefined) {
        return;
      }
      await Workspace.getConfiguration("sourcepawn").update(
        "SourcemodHome",
        newSMHome.detail
      );
      let spCompPath = optionalSMHomes.find((e) => e.name === newSMHome.label)
        .compilerPath;
      await Workspace.getConfiguration("sourcepawn").update(
        "SpcompPath",
        spCompPath
      );
      commands.executeCommand("workbench.action.reloadWindow");
    });
  return 0;
}
Example #7
Source File: account.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
export async function initAccount(context: ExtensionContext): Promise<void> {
  context.subscriptions.push(
    commands.registerCommand("cloudmusic.addAccount", () =>
      AccountManager.loginQuickPick()
    ),

    commands.registerCommand(
      "cloudmusic.account",
      () =>
        void MultiStepInput.run(async (input) => {
          const pick = await input.showQuickPick({
            title: i18n.word.account,
            step: 1,
            items: [...AccountManager.accounts].map(([uid, { nickname }]) => ({
              label: `$(account) ${nickname}`,
              uid,
            })),
          });
          AccountManager.accountQuickPick(pick.uid);
        })
    ),

    commands.registerCommand(
      "cloudmusic.dailyCheck",
      async () =>
        void window.showInformationMessage(
          (await AccountManager.dailyCheck())
            ? i18n.sentence.success.dailyCheck
            : i18n.sentence.error.needSignIn
        )
    )
  );

  await AccountManager.init();
}
Example #8
Source File: activator.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
export function activate(ballerinaExtInstance: BallerinaExtension) {
    const context = <ExtensionContext>ballerinaExtInstance.context;
    const langClient = <ExtendedLangClient>ballerinaExtInstance.langClient;
    const examplesListRenderer = commands.registerCommand('ballerina.showExamples', () => {
        sendTelemetryEvent(ballerinaExtInstance, TM_EVENT_OPEN_EXAMPLES, CMP_EXAMPLES_VIEW);
        ballerinaExtInstance.onReady()
            .then(() => {
                const { experimental } = langClient.initializeResult!.capabilities;
                const serverProvidesExamples = experimental && experimental.examplesProvider;

                if (!serverProvidesExamples) {
                    ballerinaExtInstance.showMessageServerMissingCapability();
                    return;
                }

                showExamples(context, langClient);
            })
            .catch((e) => {
                ballerinaExtInstance.showPluginActivationError();
                sendTelemetryException(ballerinaExtInstance, e, CMP_EXAMPLES_VIEW);
            });
    });

    context.subscriptions.push(examplesListRenderer);
}
Example #9
Source File: extension.ts    From flatpak-vscode with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
    private registerCommand(name: string, callback: (...args: any) => any | Promise<void>) {
        this.extCtx.subscriptions.push(
            commands.registerCommand(`${EXTENSION_ID}.${name}`, async (args) => {
                try {
                    await callback(args)
                } catch (err) {
                    if (err instanceof RunnerError) {
                        return
                    }

                    throw err
                }
            })
        )
    }
Example #10
Source File: export-factory.ts    From vscode-code-review with MIT License 6 votes vote down vote up
/**
   * Enable/Disable filtering comments by commit
   * @param state The state of the filter
   * @returns The new state of the filter
   */
  public setFilterByCommit(state: boolean): boolean {
    this.filterByCommit = state;
    if (this.filterByCommit) {
      try {
        const gitDirectory = workspace.getConfiguration().get('code-review.gitDirectory') as string;
        const gitRepositoryPath = path.resolve(this.workspaceRoot, gitDirectory);

        this.currentCommitId = gitCommitId({ cwd: gitRepositoryPath });
      } catch (error) {
        this.filterByCommit = false;
        this.currentCommitId = null;

        console.log('Not in a git repository. Disabling filter by commit', error);
      }
    } else {
      this.currentCommitId = null;
    }

    commands.executeCommand('setContext', 'isFilteredByCommit', this.filterByCommit);

    return this.filterByCommit;
  }
Example #11
Source File: startupCheck.ts    From ide-vscode with MIT License 6 votes vote down vote up
async function checkDotnetInstallation(): Promise<boolean> {
  const answer = await checkSupportedDotnetVersion();
  if(answer !== undefined) {
    const selection = await window.showErrorMessage(
      answer,
      Messages.Dotnet.ChangeConfiguration,
      Messages.Dotnet.VisitDownload
    );
    switch(selection) {
    case Messages.Dotnet.ChangeConfiguration:
      commands.executeCommand(VSCodeCommands.ConfigureLanguageSettings);
      break;
    case Messages.Dotnet.VisitDownload:
      commands.executeCommand(VSCodeCommands.Open, Uri.parse(Messages.Dotnet.DownloadUri));
      break;
    }
    return false;
  }
  return true;
}
Example #12
Source File: extension.ts    From format-imports-vscode with MIT License 6 votes vote down vote up
// 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 #13
Source File: ConvertCandidateLink.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
async execute(_opts: CommandOpts) {
    const { location, text } = _opts;
    await commands.executeCommand("vscode.open", location.uri);
    const editor = VSCodeUtils.getActiveTextEditor()!;
    const selection = editor.document.getText(location.range);
    const preConversionOffset = selection.indexOf(text);
    const convertedSelection = selection.replace(text, `[[${text}]]`);
    await editor.edit((editBuilder) => {
      editBuilder.replace(location.range, convertedSelection);
    });
    const postConversionSelectionRange = new Selection(
      new Position(
        location.range.start.line,
        location.range.start.character + preConversionOffset
      ),
      new Position(
        location.range.end.line,
        location.range.start.character + preConversionOffset + text.length + 4
      )
    );
    editor.selection = postConversionSelectionRange;
    return;
  }
Example #14
Source File: colorization.test.ts    From myst-vs-code with MIT License 6 votes vote down vote up
suite("colorization", () => {
  before(() => {
    // ensure the extension is activated, so the grammar is injected
    commands.executeCommand("myst.Activate").then(
      (_data: any) => {},
      () => {}
    )
  })

  // We place the test files in this lower level FoldingRange, so that when this file is compiled to out/test/,
  // it still finds them
  const extensionColorizeFixturePath = join(
    __dirname,
    "../../../test_static/colorize-fixtures"
  )
  if (fs.existsSync(extensionColorizeFixturePath)) {
    // pause to allow extension to load?
    const fixturesFiles = fs.readdirSync(extensionColorizeFixturePath)
    fixturesFiles.forEach(fixturesFile => {
      // define a test for each fixture
      test(fixturesFile, done => {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        assertUnchangedTokens(join(extensionColorizeFixturePath, fixturesFile), done)
      })
    })
  }
})
Example #15
Source File: extension.ts    From markmap-vscode with MIT License 6 votes vote down vote up
export function activate(context: ExtensionContext) {
  context.subscriptions.push(commands.registerCommand(`${PREFIX}.open`, (uri?: Uri) => {
    uri ??= vscodeWindow.activeTextEditor?.document.uri;
    commands.executeCommand(
      'vscode.openWith',
      uri,
      VIEW_TYPE,
      ViewColumn.Beside,
    );
  }));
  const markmapEditor = new MarkmapEditor(context);
  context.subscriptions.push(vscodeWindow.registerCustomEditorProvider(
    VIEW_TYPE,
    markmapEditor,
    { webviewOptions: { retainContextWhenHidden: true } },
  ));
}
Example #16
Source File: DrawioEditorProviderBinary.ts    From vscode-drawio with GNU General Public License v3.0 6 votes vote down vote up
public async openCustomDocument(
		uri: Uri,
		openContext: CustomDocumentOpenContext,
		token: CancellationToken
	): Promise<DrawioBinaryDocument> {
		const document = new DrawioBinaryDocument(uri, openContext.backupId);
		document.onChange(() => {
			this.onDidChangeCustomDocumentEmitter.fire({
				document,
			});
		});
		document.onInstanceSave(() => {
			commands.executeCommand("workbench.action.files.save");
		});

		return document;
	}
Example #17
Source File: index.ts    From Json-to-Dart-Model with MIT License 6 votes vote down vote up
export function activate(context: ExtensionContext) {
  context.subscriptions.push(
    commands.registerCommand(
      'jsonToDart.fromFile',
      transformFromFile
    ),
    commands.registerCommand(
      'jsonToDart.fromSelection',
      transformFromSelection
    ),
    commands.registerCommand(
      'jsonToDart.fromClipboard',
      transformFromClipboard
    ),
    commands.registerCommand(
      'jsonToDart.addCodeGenerationLibraries',
      addCodeGenerationLibraries
    ),
    commands.registerCommand(
      'jsonToDart.fromClipboardToCodeGen',
      transformFromClipboardToCodeGen
    ),
    commands.registerCommand(
      'jsonToDart.fromSelectionToCodeGen',
      transformFromSelectionToCodeGen
    ),
  );

  const disposableOnDidSave = workspace.onDidSaveTextDocument((doc) => jsonReader.onChange(doc));
  context.subscriptions.push(disposableOnDidSave);
}
Example #18
Source File: index.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
constructor(
    private installDBT: InstallDBT,
    private updateDBT: UpdateDBT,
    private runModel: RunModel,
  ) {
    this.disposables.push(
      commands.registerCommand("dbtPowerUser.runCurrentModel", () =>
        this.runModel.runModelOnActiveWindow()
      ),
      commands.registerCommand("dbtPowerUser.compileCurrentModel", () =>
        this.runModel.compileModelOnActiveWindow()
      ),
      commands.registerCommand("dbtPowerUser.runChildrenModels", (model) =>
        this.runModel.runModelOnNodeTreeItem(RunModelType.CHILDREN)(model)
      ),
      commands.registerCommand("dbtPowerUser.runParentModels", (model) =>
        this.runModel.runModelOnNodeTreeItem(RunModelType.PARENTS)(model)
      ),
      commands.registerCommand("dbtPowerUser.showRunSQL", () =>
        this.runModel.showRunSQLOnActiveWindow()
      ),
      commands.registerCommand("dbtPowerUser.showCompiledSQL", () =>
        this.runModel.showCompiledSQLOnActiveWindow()
      ),
      commands.registerCommand("dbtPowerUser.installDBT", () =>
        this.installDBT.installDBTCommand()
      ),
      commands.registerCommand("dbtPowerUser.updateDBT", () =>
        this.updateDBT.updateDBTCommand()
      )
    );
  }
Example #19
Source File: q-conn-manager.ts    From vscode-q with MIT License 6 votes vote down vote up
removeConn(uniqLabel: string): void {
        const qConn = this.getConn(uniqLabel);
        qConn?.setConn(undefined);
        if (this.activeConn?.uniqLabel === uniqLabel) {
            this.activeConn = undefined;
            QStatusBarManager.updateConnStatus(undefined);
        }
        commands.executeCommand('q-client.refreshEntry');
        window.showWarningMessage(`Lost connection to ${uniqLabel} `);
    }
Example #20
Source File: holes.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
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 #21
Source File: extension.ts    From typescript-explicit-types with GNU General Public License v3.0 6 votes vote down vote up
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 #22
Source File: config.ts    From vscode-cadence with Apache License 2.0 6 votes vote down vote up
// Adds an event handler that prompts the user to reload whenever the config
// changes.
export function handleConfigChanges (): void {
  workspace.onDidChangeConfiguration((e) => {
    // TODO: do something smarter for account/emulator config (re-send to server)
    const promptRestartKeys = [
      'languageServerPath',
      'accountKey',
      'accountAddress',
      'emulatorAddress'
    ]
    const shouldPromptRestart = promptRestartKeys.some((key) =>
      e.affectsConfiguration(`cadence.${key}`)
    )
    if (shouldPromptRestart) {
      window
        .showInformationMessage(
          'Server launch configuration change detected. Reload the window for changes to take effect',
          'Reload Window',
          'Not now'
        )
        .then((choice) => {
          if (choice === 'Reload Window') {
            commands.executeCommand('workbench.action.reloadWindow')
              .then(() => {}, () => {})
          }
        }, () => {})
    }
  })
}
Example #23
Source File: lsp-commands.ts    From vscode-microprofile with Apache License 2.0 6 votes vote down vote up
/**
 * Registers the `microprofile.command.open.uri` command.
 * This command gives the capability to open the given uri of the command.
 */
export function registerOpenURICommand(): Disposable {
  return commands.registerCommand(CommandKind.COMMAND_OPEN_URI, (uri) => {
    commands.executeCommand('vscode.open', Uri.parse(uri));
  });
}
Example #24
Source File: extension.ts    From vscode-discord with MIT License 6 votes vote down vote up
export function activate(ctx: ExtensionContext): void {
	if (config.get<string[]>("ignoreWorkspaces").includes(workspace.name))
		return;

	_activate();

	ctx.subscriptions.push(
		client.statusBar,
		commands.registerCommand("RPC.reconnect", reconnect),
		commands.registerCommand("RPC.disconnect", deactivate)
	);
}
Example #25
Source File: index.ts    From vscode-gcode with MIT License 6 votes vote down vote up
export function register(context: ExtensionContext){
    
  // Create an array where each item  is a function that returns 'void'.
  // Since these functions will be registered as commands, the names of the
  // functions must match what is defined in the project's package.json.
  const gcodeCommands = [
    addLineNumbers,
    removeLineNumbers,
    toggleComment,
    tailorTextMateGrammar
  ];

  gcodeCommands.forEach(cmd => {
    context.subscriptions.push(
      commands.registerCommand(`gcode.${cmd.name}`, cmd)
    );
  });

}
Example #26
Source File: stripeSamples.ts    From vscode-stripe with MIT License 6 votes vote down vote up
/**
   * Ask if the user wants to open the sample in the same or new window
   */
  private promptOpenFolder = async (postInstallMessage: string, clonePath: string, sampleName: string): Promise<void> => {
    const openFolderOptions = {
      sameWindow: 'Open in same window',
      newWindow: 'Open in new window',
    };

    const selectedOption = await window.showInformationMessage(
      postInstallMessage,
      {modal: true},
      ...Object.values(openFolderOptions),
    );

    // open the readme file in a new browser window
    // cant open in the editor because cannot update user setting 'workbench.startupEditor​' from stripe extension
    // preview markdown also does not work because opening new workspace will terminate the stripe extension process
    env.openExternal(Uri.parse(`https://github.com/stripe-samples/${sampleName}#readme`));

    switch (selectedOption) {
      case openFolderOptions.sameWindow:
        await commands.executeCommand('vscode.openFolder', Uri.file(clonePath), {
          forceNewWindow: false,
        });
        break;
      case openFolderOptions.newWindow:
        await commands.executeCommand('vscode.openFolder', Uri.file(clonePath), {
          forceNewWindow: true,
        });
        break;
      default:
        break;
    }
  };
Example #27
Source File: extension.ts    From language-tools with MIT License 6 votes vote down vote up
function addCompilePreviewCommand(getLS: () => LanguageClient, context: ExtensionContext) {
    const compiledCodeContentProvider = new CompiledCodeContentProvider(getLS);

    context.subscriptions.push(
        workspace.registerTextDocumentContentProvider(
            CompiledCodeContentProvider.scheme,
            compiledCodeContentProvider
        ),
        compiledCodeContentProvider
    );

    context.subscriptions.push(
        commands.registerTextEditorCommand('svelte.showCompiledCodeToSide', async (editor) => {
            if (editor?.document?.languageId !== 'svelte') {
                return;
            }

            const uri = editor.document.uri;
            const svelteUri = CompiledCodeContentProvider.toSvelteSchemeUri(uri);
            window.withProgress(
                { location: ProgressLocation.Window, title: 'Compiling..' },
                async () => {
                    return await window.showTextDocument(svelteUri, {
                        preview: true,
                        viewColumn: ViewColumn.Beside
                    });
                }
            );
        })
    );
}
Example #28
Source File: openDailyNote.ts    From memo with MIT License 6 votes vote down vote up
openDailyNote = () => {
  const dailyQuickPick = createDailyQuickPick();

  dailyQuickPick.onDidChangeSelection((selection) =>
    commands.executeCommand('_memo.openDocumentByReference', {
      reference: selection[0].detail,
    }),
  );

  dailyQuickPick.onDidHide(() => dailyQuickPick.dispose());

  dailyQuickPick.show();
}
Example #29
Source File: client.ts    From vala-vscode with MIT License 6 votes vote down vote up
peekSymbol(_editor: TextEditor, _edit: TextEditorEdit, lspCurrentLocation: lsp.Location, lspTargetLocation: lsp.Location): void {
        let currentLocation = new Location(
            Uri.parse(lspCurrentLocation.uri),
            new Range(
                new Position(lspCurrentLocation.range.start.line, lspCurrentLocation.range.start.character),
                new Position(lspCurrentLocation.range.end.line, lspCurrentLocation.range.end.character)
            )
        );
        let targetLocation = new Location(
            Uri.parse(lspTargetLocation.uri),
            new Range(
                new Position(lspTargetLocation.range.start.line, lspTargetLocation.range.start.character),
                new Position(lspTargetLocation.range.end.line, lspTargetLocation.range.end.character)
            )
        );

        commands.executeCommand(
            'editor.action.peekLocations',
            currentLocation.uri, // anchor uri and position
            currentLocation.range.end,
            [targetLocation], // results (vscode.Location[])
            'peek', // mode ('peek' | 'gotoAndPeek' | 'goto')
            'Nothing found' // <- message
        );
    }