vscode#ExtensionContext TypeScript Examples

The following examples show how to use vscode#ExtensionContext. 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: webview-utils.ts    From plugin-vscode with Apache License 2.0 7 votes vote down vote up
export function getCommonWebViewOptions(): Partial<WebviewOptions & WebviewPanelOptions> {
    return {
        enableScripts: true,
        retainContextWhenHidden: true,
        localResourceRoots: [
            Uri.file(join((ballerinaExtInstance.context as ExtensionContext).extensionPath, 'resources', 'jslibs')),
            Uri.file(getWebViewResourceRoot()),
            Uri.file(getNodeModulesRoot())
        ],
    };
}
Example #2
Source File: utils.ts    From vscode-stripe with MIT License 7 votes vote down vote up
export async function hasNoBuildToolConflict(
  context: ExtensionContext,
): Promise<boolean> {
  const isMavenEnabled: boolean = workspace.getConfiguration().get<boolean>(IMPORT_MAVEN) || false;
  const isGradleEnabled: boolean = workspace.getConfiguration().get<boolean>(IMPORT_GRADLE) || false;
  if (isMavenEnabled && isGradleEnabled) {
    // user has both build tools enabled. check project build files
    if (!(await hasBuildToolConflicts())) {
      return true;
    }
    return false;
  }

  return true;
}
Example #3
Source File: Controller.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Constructor of Controller.
     * @param context ExtensionContext
     */
    constructor(context: ExtensionContext) {
        // initialize classes.
        const doUpdateCache = new DoUpdateCache();
        const doComment = new DoComment();
        const doHover = new RegisterProvider();
        const doExport = new DoExport();

        // add to subscriptions.
        context.subscriptions.push(doUpdateCache);
        context.subscriptions.push(doComment);
        context.subscriptions.push(doHover);
        context.subscriptions.push(doExport);
    }
Example #4
Source File: ahkHoverProvider.ts    From vscode-autohotkey with MIT License 6 votes vote down vote up
private initSnippetCache(context: ExtensionContext) {
        const ahk = JSON.parse(readFileSync(join(context.extensionPath, "snippets", "ahk.json"), "UTF8"));
        this.snippetCache = new Map<string, Snippet>();
        // tslint:disable-next-line: forin
        for (const key in ahk) {
            const snip = ahk[key] as Snippet;
            if (typeof snip.body === 'string') {
                snip.body = snip.body?.replace(/\d{1}:/g, "");
            }
            this.snippetCache.set(key.toLowerCase(), snip);
        }
    }
Example #5
Source File: extension.ts    From element-ui-helper with MIT License 6 votes vote down vote up
export function activate(context: ExtensionContext): void {
  console.log('extension "element-ui-helper" is now active!')

  // 注册 completion 提示
  context.subscriptions.push(
    vscode.languages.registerCompletionItemProvider(
      [
        {
          language: 'vue',
          scheme: 'file'
        }
      ],
      new ElementCompletionItemProvider(),
      '',
      ' ',
      ':',
      '<',
      '"',
      "'",
      '/',
      '@',
      '(',
      '-'
    )
  )

  // 注册 hover 提示
  context.subscriptions.push(
    vscode.languages.registerHoverProvider(
      [
        {
          language: 'vue',
          scheme: 'file'
        }
      ],
      new ElementHoverProvier()
    )
  )
}
Example #6
Source File: registerCFGLinter.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
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 #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
constructor(extCtx: vscode.ExtensionContext) {
        this.extCtx = extCtx
        this.workspaceState = new WorkspaceState(extCtx)

        this.manifestManager = new ManifestManager(this.workspaceState)
        this.extCtx.subscriptions.push(this.manifestManager)
        this.manifestManager.onDidActiveManifestChanged(async ([manifest, isLastActive]) => {
            await this.handleActiveManifestChanged(manifest, isLastActive)
        })

        this.buildPipeline = new BuildPipeline(this.workspaceState)
        this.extCtx.subscriptions.push(this.buildPipeline)

        this.manifestManager.onDidRequestRebuild(async (manifest) => {
            if (this.manifestManager.isActiveManifest(manifest)) {
                console.log(`Manifest at ${manifest.uri.fsPath} requested a rebuild`)
                await manifest.deleteRepoDir()
                await this.buildPipeline.resetState()
            }
        })
    }
Example #10
Source File: export-factory.ts    From vscode-code-review with MIT License 6 votes vote down vote up
/**
   * for trying out: https://stackblitz.com/edit/code-review-template
   */
  constructor(private context: ExtensionContext, private workspaceRoot: string, private generator: FileGenerator) {
    let groupByConfig = workspace.getConfiguration().get('code-review.groupBy') as string;
    if (!groupByConfig || groupByConfig === '-') {
      groupByConfig = Group.filename;
    }
    this.groupBy = groupByConfig as GroupBy;
    this.includeCodeSelection = workspace.getConfiguration().get('code-review.reportWithCodeSelection') as boolean;
    this.includePrivateComments = workspace.getConfiguration().get('code-review.reportWithPrivateComments') as boolean;
    this.privateCommentIcon = workspace.getConfiguration().get('code-review.privateCommentIcon') as string;

    this.filterByCommit = workspace.getConfiguration().get('code-review.filterCommentsByCommit') as boolean;
    this.setFilterByCommit(this.filterByCommit);

    this.filterByFilename = workspace.getConfiguration().get('code-review.filterCommentsByFilename') as boolean;
    this.setFilterByFilename(this.filterByFilename, true);
  }
Example #11
Source File: extension.ts    From ide-vscode with MIT License 6 votes vote down vote up
export async function activate(context: ExtensionContext): Promise<void> {
  if(!await checkAndInformAboutInstallation()) {
    return;
  }
  const statusOutput = window.createOutputChannel(ExtensionConstants.ChannelName);
  context.subscriptions.push(statusOutput);
  extensionRuntime = new ExtensionRuntime(context, statusOutput);
  await extensionRuntime.initialize();
}
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: codeActionProvider.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
function activate(context: ExtensionContext) {
  context.subscriptions.push(
    languages.registerCodeActionsProvider(
      "markdown",
      doctorFrontmatterProvider
    ),
    languages.registerCodeActionsProvider("markdown", refactorProvider)
  );
}
Example #14
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 #15
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 #16
Source File: extension.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
export async function activate(context: ExtensionContext) {
  const dbtPowerUserExtension = container.get(DBTPowerUserExtension);
  
  context.subscriptions.push(
    dbtPowerUserExtension,
  );

  await dbtPowerUserExtension.activate();
}
Example #17
Source File: q-status-bar-manager.ts    From vscode-q with MIT License 6 votes vote down vote up
private constructor(context: ExtensionContext) {

        this.queryModeStatusBar = window.createStatusBarItem(StatusBarAlignment.Left, 99);
        context.subscriptions.push(this.queryModeStatusBar);
        this.queryModeStatusBar.color = this.isLightTheme ? '#512DA8' : '#B39DDB';
        this.queryModeStatusBar.command = 'q-client.switchMode';
        this.queryModeStatusBar.text = '$(triangle-left)q ' + QConnManager.queryMode.toLowerCase();
        this.queryModeStatusBar.show();

        this.connStatusBar = window.createStatusBarItem(StatusBarAlignment.Left, 98);
        context.subscriptions.push(this.connStatusBar);
        this.connStatusBar.color = this.isLightTheme ? '#512DA8' : '#B39DDB';
        this.connStatusBar.command = 'q-client.connectEntry';
        this.connStatusBar.show();

        this.queryStatusBar = window.createStatusBarItem(StatusBarAlignment.Left, 97);
        this.queryStatusBar.text = '$(play-circle)';
        this.queryStatusBar.color = '#4CAF50';
        this.queryStatusBar.tooltip = 'Querying';
        context.subscriptions.push(this.queryStatusBar);
        this.unlimitedQueryStatusBar = window.createStatusBarItem(StatusBarAlignment.Left, 96);
        this.unlimitedQueryStatusBar.text = '$(flame)';
        this.unlimitedQueryStatusBar.color = '#F44336';
        this.unlimitedQueryStatusBar.tooltip = 'Unlimited Query';
        context.subscriptions.push(this.unlimitedQueryStatusBar);

    }
Example #18
Source File: taskgutter.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
constructor(client: LeanClientProvider, context: ExtensionContext) {
        this.decorations.set(LeanFileProgressKind.Processing, [
            window.createTextEditorDecorationType({
                overviewRulerLane: OverviewRulerLane.Left,
                overviewRulerColor: 'rgba(255, 165, 0, 0.5)',
                dark: {
                    gutterIconPath: context.asAbsolutePath('media/progress-dark.svg'),
                },
                light: {
                    gutterIconPath: context.asAbsolutePath('media/progress-light.svg'),
                },
                gutterIconSize: 'contain',
            }),
            'busily processing...'
        ])
        this.decorations.set(LeanFileProgressKind.FatalError, [
            window.createTextEditorDecorationType({
                overviewRulerLane: OverviewRulerLane.Left,
                overviewRulerColor: 'rgba(255, 0, 0, 0.5)',
                dark: {
                    gutterIconPath: context.asAbsolutePath('media/progress-error-dark.svg'),
                },
                light: {
                    gutterIconPath: context.asAbsolutePath('media/progress-error-light.svg'),
                },
                gutterIconSize: 'contain',
            }),
            'processing stopped'
        ])

        this.subscriptions.push(
            window.onDidChangeVisibleTextEditors(() => this.updateDecos()),
            client.progressChanged(([uri, processing]) => {
                this.status[uri.toString()] = processing
                this.updateDecos()
            }));
    }
Example #19
Source File: Extension.ts    From vscode-file-downloader with MIT License 6 votes vote down vote up
// Called when the extension is activated
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
export function activate(context: ExtensionContext): IFileDownloader {
    const logger = new OutputLogger(`File Downloader`, context);
    logger.log(`File Downloader extension now active.`);

    const requestHandler = new HttpRequestHandler(logger);

    return new FileDownloader(requestHandler, logger);
}
Example #20
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 #21
Source File: extension.ts    From vscode-cadence with Apache License 2.0 6 votes vote down vote up
constructor (
    config: Config,
    ctx: ExtensionContext,
    api: LanguageServerAPI,
    terminal: Terminal,
    emulatorStatusBarItem: StatusBarItem,
    activeAccountStatusBarItem: StatusBarItem
  ) {
    this.config = config
    this.ctx = ctx
    this.api = api
    this.terminal = terminal
    this.emulatorStatusBarItem = emulatorStatusBarItem
    this.activeAccountStatusBarItem = activeAccountStatusBarItem
  }
Example #22
Source File: extension.ts    From reach-ide with Eclipse Public License 2.0 6 votes vote down vote up
function registerCommands(context: ExtensionContext, reachPath: string) {
	const cmdHelper = commandHelper(context, reachPath);

	cmdHelper('compile');
	cmdHelper('run');
	cmdHelper('clean');
	cmdHelper('upgrade');
	cmdHelper('update');
	cmdHelper('hashes');
	cmdHelper('version');
	cmdHelper('docker-reset');
	cmdHelper('devnet');
	cmdHelper('rpc-server');
	cmdHelper('rpc-run');
	cmdHelper('react');
	cmdHelper('scaffold');
	cmdHelper('down');
	cmdHelper('init');

	urlHelper(context, 'docs', 'https://docs.reach.sh/doc-index.html');
	urlHelper(context, 'issue', 'https://github.com/reach-sh/reach-lang/issues/new');
	urlHelper(context, 'discord', 'https://discord.gg/2XzY6MVpFH');
	urlHelper(context, 'gist', 'https://gist.github.com/');

}
Example #23
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 #24
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 #25
Source File: extension.ts    From vscode-blade-formatter with MIT License 6 votes vote down vote up
function showWelcomeMessage(context: vscode.ExtensionContext) {
    let message: string | null = null;

    const previousVersion = context.globalState.get<string>(ExtensionConstants.globalVersionKey);
    const currentVersion = vscode.extensions.getExtension(ExtensionConstants.extensionId)?.packageJSON?.version;
    const previousVersionArray = previousVersion ? previousVersion.split('.').map((s: string) => Number(s)) : [0, 0, 0];
    const currentVersionArray = currentVersion.split('.').map((s: string) => Number(s));

    if (previousVersion === undefined || previousVersion.length === 0) {
        message = `Thanks for using ${ExtensionConstants.displayName}.`;
    } else if (currentVersion !== previousVersion && (
        // patch update
        (previousVersionArray[0] === currentVersionArray[0] && previousVersionArray[1] === currentVersionArray[1] && previousVersionArray[2] < currentVersionArray[2]) ||
        // minor update
        (previousVersionArray[0] === currentVersionArray[0] && previousVersionArray[1] < currentVersionArray[1]) ||
        // major update
        (previousVersionArray[0] < currentVersionArray[0])
    )
    ) {
        message = `${ExtensionConstants.displayName} updated to ${currentVersion}.`;
    }

    if (message) {
        vscode.window.showInformationMessage(message, '⭐️ Star on Github', '? Report Bug')
            .then(function (val: string | undefined) {
                if (val === '? Report Bug') {
                    vscode.env.openExternal(vscode.Uri.parse('https://github.com/shufo/vscode-blade-formatter/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc'));
                } else if (val === '⭐️ Star on Github') {
                    vscode.env.openExternal(vscode.Uri.parse('https://github.com/shufo/vscode-blade-formatter'));
                }
            });
        context.globalState.update(ExtensionConstants.globalVersionKey, currentVersion);
    }
}
Example #26
Source File: extension.ts    From vscode-stripe with MIT License 6 votes vote down vote up
/**
 * Checks for the explicit setting of the EXTENSION_MODE and
 * Implcitly checks by using the magic session string. This session value is used whenever an extension
 * is running on a development host. https://github.com/microsoft/vscode/issues/10272
 */
function getTelemetry(extensionContext: ExtensionContext) {
  if (process.env.EXTENSION_MODE === 'development' || env.sessionId === 'someValue.sessionId') {
    console.log('Extension is running in development mode. Not emitting Telemetry');
    return new NoOpTelemetry();
  } else {
    return new StripeAnalyticsServiceTelemetry(extensionContext);
  }
}
Example #27
Source File: extension.ts    From language-tools with MIT License 6 votes vote down vote up
export function activate(context: ExtensionContext) {
    // The extension is activated on TS/JS/Svelte files because else it might be too late to configure the TS plugin:
    // If we only activate on Svelte file and the user opens a TS file first, the configuration command is issued too late.
    // We wait until there's a Svelte file open and only then start the actual language client.
    const tsPlugin = new TsPlugin(context);
    let lsApi: { getLS(): LanguageClient } | undefined;

    if (workspace.textDocuments.some((doc) => doc.languageId === 'svelte')) {
        lsApi = activateSvelteLanguageServer(context);
        tsPlugin.askToEnable();
    } else {
        const onTextDocumentListener = workspace.onDidOpenTextDocument((doc) => {
            if (doc.languageId === 'svelte') {
                lsApi = activateSvelteLanguageServer(context);
                tsPlugin.askToEnable();
                onTextDocumentListener.dispose();
            }
        });

        context.subscriptions.push(onTextDocumentListener);
    }

    // This API is considered private and only exposed for experimenting.
    // Interface may change at any time. Use at your own risk!
    return {
        /**
         * As a function, because restarting the server
         * will result in another instance.
         */
        getLanguageServer() {
            if (!lsApi) {
                lsApi = activateSvelteLanguageServer(context);
            }

            return lsApi.getLS();
        }
    };
}
Example #28
Source File: completionProvider.ts    From memo with MIT License 6 votes vote down vote up
activate = (context: ExtensionContext) =>
  context.subscriptions.push(
    languages.registerCompletionItemProvider(
      'markdown',
      {
        provideCompletionItems,
        resolveCompletionItem,
      },
      '[',
    ),
  )
Example #29
Source File: initCommands.ts    From vscode-sftp-revived with MIT License 6 votes vote down vote up
export default function init(context: ExtensionContext) {
  loadCommands(
    require.context(
      // Look for files in the commands directory
      './commands',
      // Do not look in subdirectories
      false,
      // Only include "_base-" prefixed .vue files
      /command.*.ts$/
    ),
    /command(.*)/,
    createCommand,
    context
  );
  loadCommands(
    require.context(
      // Look for files in the current directory
      './commands',
      // Do not look in subdirectories
      false,
      // Only include "_base-" prefixed .vue files
      /fileCommand.*.ts$/
    ),
    /fileCommand(.*)/,
    createFileCommand,
    context
  );
}