当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript workspace.onDidChangeWorkspaceFolders方法代码示例

本文整理汇总了TypeScript中vscode.workspace.onDidChangeWorkspaceFolders方法的典型用法代码示例。如果您正苦于以下问题:TypeScript workspace.onDidChangeWorkspaceFolders方法的具体用法?TypeScript workspace.onDidChangeWorkspaceFolders怎么用?TypeScript workspace.onDidChangeWorkspaceFolders使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在vscode.workspace的用法示例。


在下文中一共展示了workspace.onDidChangeWorkspaceFolders方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: activate

export function activate(context: ExtensionContext) {
    const { fileIsIgnored } = ignoreFileHandler(context.subscriptions);
    const editProvider = new EditProvider(fileIsIgnored);
    function registerFormatter() {
        disposeHandlers();
        const { languageSelector, rangeLanguageSelector } = selectors();
        rangeFormatterHandler = languages.registerDocumentRangeFormattingEditProvider(
            rangeLanguageSelector,
            editProvider
        );
        formatterHandler = languages.registerDocumentFormattingEditProvider(
            languageSelector,
            editProvider
        );
    }
    registerFormatter();
    context.subscriptions.push(
        workspace.onDidChangeWorkspaceFolders(registerFormatter),
        {
            dispose: disposeHandlers,
        },
        setupErrorHandler(),
        configFileListener(),
        ...registerDisposables()
    );
}
开发者ID:JulioC,项目名称:prettier-vscode,代码行数:26,代码来源:extension.ts

示例2: registerTaskProvider

function registerTaskProvider(context: vscode.ExtensionContext): vscode.Disposable | undefined {

	function invalidateScriptCaches() {
		invalidateHoverScriptsCache();
		invalidateTasksCache();
		if (treeDataProvider) {
			treeDataProvider.refresh();
		}
	}

	if (vscode.workspace.workspaceFolders) {
		let watcher = vscode.workspace.createFileSystemWatcher('**/package.json');
		watcher.onDidChange((_e) => invalidateScriptCaches());
		watcher.onDidDelete((_e) => invalidateScriptCaches());
		watcher.onDidCreate((_e) => invalidateScriptCaches());
		context.subscriptions.push(watcher);

		let workspaceWatcher = vscode.workspace.onDidChangeWorkspaceFolders((_e) => invalidateScriptCaches());
		context.subscriptions.push(workspaceWatcher);

		let provider: vscode.TaskProvider = new NpmTaskProvider();
		let disposable = vscode.workspace.registerTaskProvider('npm', provider);
		context.subscriptions.push(disposable);
		return disposable;
	}
	return undefined;
}
开发者ID:sadguruy,项目名称:vscode,代码行数:27,代码来源:main.ts

示例3: createWatcher

function createWatcher( func: (e: Uri)=>void, extension: string ): void {
    var dict: any[] = [];
    
        function addWatcher(wf: WorkspaceFolder) {
            var watcher = workspace.createFileSystemWatcher( new RelativePattern(wf, `**/*.${extension}` ) );  
            dict.push({key: wf.uri.fsPath, value: watcher});
            watcher.onDidCreate( (e) => {
                func( e );
                // cmUtils.addCopyright( e );
            } );
        }
    
        workspace.workspaceFolders.forEach( wf => {
           addWatcher( wf );
        });
    
        workspace.onDidChangeWorkspaceFolders( e => {
            e.added.forEach( a => {
                addWatcher(a);
            });
            e.removed.forEach( a => {
                let watcher: FileSystemWatcher = dict.find( o => o.key == a.uri.fsPath );
                watcher = null;
            })
        } );
}
开发者ID:docura-io,项目名称:vscode-cm,代码行数:26,代码来源:extension.ts

示例4: activate

export function activate(context: ExtensionContext) {

    // Create a status bar item
    const status = window.createStatusBarItem(StatusBarAlignment.Left, 1000000);
    context.subscriptions.push(status);

    // Update status bar item based on events for multi root folder changes
    context.subscriptions.push(workspace.onDidChangeWorkspaceFolders(e => updateStatus(status)));

    // Update status bar item based on events for configuration
    context.subscriptions.push(workspace.onDidChangeConfiguration(e => this.updateStatus(status)));

    // Update status bar item based on events around the active editor
    context.subscriptions.push(window.onDidChangeActiveTextEditor(e => updateStatus(status)));
    context.subscriptions.push(window.onDidChangeTextEditorViewColumn(e => updateStatus(status)));
    context.subscriptions.push(workspace.onDidOpenTextDocument(e => updateStatus(status)));
    context.subscriptions.push(workspace.onDidCloseTextDocument(e => updateStatus(status)));

    updateStatus(status);
}
开发者ID:voodoos,项目名称:vscode-extension-samples,代码行数:20,代码来源:extension.ts

示例5: activate

export function activate(ctx: vscode.ExtensionContext) {
  const elixirSetting = vscode.workspace.getConfiguration('elixir');
  useElixirSense = elixirSetting.useElixirSense;
  autoSpawnElixirSenseServers = elixirSetting.autoSpawnElixirSenseServers;
  const projectPath = elixirSetting.projectPath;
  // TODO: detect environment automatically.
  const env = elixirSetting.elixirEnv;

  if (useElixirSense) {
    ElixirSenseServerProcess.initClass();
    if (autoSpawnElixirSenseServers) {
      (vscode.workspace.workspaceFolders || []).forEach(workspaceFolder => {
        startElixirSenseServerForWorkspaceFolder(workspaceFolder, ctx, env, projectPath);
      });
    } else if ((vscode.workspace.workspaceFolders || []).length === 1) {
      startElixirSenseServerForWorkspaceFolder(vscode.workspace.workspaceFolders[0], ctx, env);
    }
    vscode.workspace.onDidChangeWorkspaceFolders(e => {
      (e.removed || []).forEach(workspaceFolder => stopElixirSenseServerByPath(workspaceFolder.uri.fsPath));
      if (autoSpawnElixirSenseServers) {
        (e.added || []).forEach(workspaceFolder => startElixirSenseServerForWorkspaceFolder(workspaceFolder, ctx, env));
      }
    });
  } else {
    this.elixirServer = new ElixirServer(elixirSetting.command);
    this.elixirServer.start();
    ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(ELIXIR_MODE, new ElixirAutocomplete(this.elixirServer), '.'));
    ctx.subscriptions.push(vscode.languages.registerDefinitionProvider(ELIXIR_MODE, new ElixirDefinitionProvider(this.elixirServer)));
    ctx.subscriptions.push(vscode.languages.registerHoverProvider(ELIXIR_MODE, new ElixirHoverProvider(this.elixirServer)));
    ctx.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(ELIXIR_MODE, new ElixirFormatterProvider()));
    ctx.subscriptions.push(vscode.languages.setLanguageConfiguration('elixir', configuration));
  }

  ctx.subscriptions.push(vscode.languages.registerDocumentSymbolProvider({ language: 'elixir' }, new ElixirDocumentSymbolProvider()));

  const disposables = [];
  if (useElixirSense) {
    disposables.push(vscode.commands.registerCommand('extension.selectElixirSenseWorkspaceFolder', () => selectElixirSenseWorkspaceFolder(ctx, env)));
  }
  ctx.subscriptions.push(...disposables);
}
开发者ID:fr1zle,项目名称:vscode-elixir,代码行数:41,代码来源:elixirMain.ts

示例6: activate

export function activate(context: vscode.ExtensionContext) {

    let riolog = new RioLog();
    context.subscriptions.push(riolog);

    let preferences: Preferences[] = [];

    let workspaces = vscode.workspace.workspaceFolders;

    if (workspaces === undefined) {
        vscode.window.showErrorMessage('WPILib does not support single file');
        return;
    }

    for (let w of workspaces) {
        preferences.push(new Preferences(w));
    }

    context.subscriptions.push(vscode.workspace.onDidChangeWorkspaceFolders(() => {
        // Nuke and restart
        for (let p of preferences) {
            p.dispose();
        }
        let wp = vscode.workspace.workspaceFolders;

        if (wp === undefined) {
            return;
        }

        for (let w of wp) {
            preferences.push(new Preferences(w));
        }
    }));

    context.subscriptions.push(...preferences);

    let extensionResourceLocation = path.join(context.extensionPath, 'resources');

    let tools = new Array<IToolRunner>();
    let codeDeployers = new Array<ICodeDeployer>();
    let codeDebuggers = new Array<ICodeDeployer>();
    let languageChoices = new Array<string>();

    let api : IExternalAPI = {
        async startRioLog(teamNumber: number) : Promise<void> {
            riolog.connect(teamNumber, path.join(extensionResourceLocation, 'riolog'));
        },
        async startTool(): Promise<void> {
            if (tools.length <= 0) {
                vscode.window.showErrorMessage('No tools found. Please install some');
                return;
            }

            let toolNames = new Array<string>();
            for (let t of tools) {
                toolNames.push(t.getDisplayName());
            }

            let result = await vscode.window.showQuickPick(toolNames, { placeHolder: 'Pick a tool'});

            if (result === undefined) {
                vscode.window.showInformationMessage('Tool run canceled');
                return;
            }

            for (let t of tools) {
                if (t.getDisplayName() === result) {
                    await t.runTool();
                    return;
                }
            }

            vscode.window.showErrorMessage('Invalid tool entered');
            return;
        },
        addTool(tool: IToolRunner): void {
            tools.push(tool);
        },
        async deployCode(workspace: vscode.WorkspaceFolder): Promise<boolean> {
            if (codeDeployers.length <= 0) {
                vscode.window.showErrorMessage('No registered deployers');
                return false;
            }

            let prefs = await this.getPreferences(workspace);

            let availableDeployers = new Array<ICodeDeployer>();
            for (let d of codeDeployers) {
                if (await d.getIsCurrentlyValid(workspace)) {
                    availableDeployers.push(d);
                }
            }

            if (availableDeployers.length <= 0) {
                vscode.window.showErrorMessage('No registered deployers');
                return false;
            } else if (availableDeployers.length === 1) {
                if (prefs.getAutoSaveOnDeploy()) {
                    vscode.workspace.saveAll();
                }
//.........这里部分代码省略.........
开发者ID:ThadHouse,项目名称:vscode-wpilib-core,代码行数:101,代码来源:extension.ts

示例7: activate

export function activate(context: ExtensionContext) {

	let module = context.asAbsolutePath(path.join('server', 'out', 'server.js'));
	let outputChannel: OutputChannel = Window.createOutputChannel('lsp-multi-server-example');

	function didOpenTextDocument(document: TextDocument): void {
		// We are only interested in language mode text
		if (document.languageId !== 'plaintext' || (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled')) {
			return;
		}

		let uri = document.uri;
		// Untitled files go to a default client.
		if (uri.scheme === 'untitled' && !defaultClient) {
			let debugOptions = { execArgv: ["--nolazy", "--inspect=6010"] };
			let serverOptions = {
				run: { module, transport: TransportKind.ipc },
				debug: { module, transport: TransportKind.ipc, options: debugOptions}
			};
			let clientOptions: LanguageClientOptions = {
				documentSelector: [
					{ scheme: 'untitled', language: 'plaintext' }
				],
				diagnosticCollectionName: 'lsp-multi-server-example',
				outputChannel: outputChannel
			}
			defaultClient = new LanguageClient('lsp-multi-server-example', 'LSP Multi Server Example', serverOptions, clientOptions);
			defaultClient.start();
			return;
		}
		let folder = Workspace.getWorkspaceFolder(uri);
		// Files outside a folder can't be handled. This might depend on the language.
		// Single file languages like JSON might handle files outside the workspace folders.
		if (!folder) {
			return;
		}
		// If we have nested workspace folders we only start a server on the outer most workspace folder.
		folder = getOuterMostWorkspaceFolder(folder);

		if (!clients.has(folder.uri.toString())) {
			let debugOptions = { execArgv: ["--nolazy", `--inspect=${6011 + clients.size}`] };
			let serverOptions = {
				run: { module, transport: TransportKind.ipc },
				debug: { module, transport: TransportKind.ipc, options: debugOptions}
			};
			let clientOptions: LanguageClientOptions = {
				documentSelector: [
					{ scheme: 'file', language: 'plaintext', pattern: `${folder.uri.fsPath}/**/*` }
				],
				diagnosticCollectionName: 'lsp-multi-server-example',
				workspaceFolder: folder,
				outputChannel: outputChannel
			}
			let client = new LanguageClient('lsp-multi-server-example', 'LSP Multi Server Example', serverOptions, clientOptions);
			client.start();
			clients.set(folder.uri.toString(), client);
		}
	}

	Workspace.onDidOpenTextDocument(didOpenTextDocument);
	Workspace.textDocuments.forEach(didOpenTextDocument);
	Workspace.onDidChangeWorkspaceFolders((event) => {
		for (let folder  of event.removed) {
			let client = clients.get(folder.uri.toString());
			if (client) {
				clients.delete(folder.uri.toString());
				client.stop();
			}
		}
	});
}
开发者ID:voodoos,项目名称:vscode-extension-samples,代码行数:71,代码来源:extension.ts

示例8: getOuterMostWorkspaceFolder

	if (_sortedWorkspaceFolders === void 0) {
		_sortedWorkspaceFolders = Workspace.workspaceFolders.map(folder => {
			let result = folder.uri.toString();
			if (result.charAt(result.length - 1) !== '/') {
				result = result + '/';
			}
			return result;
		}).sort(
			(a, b) => {
				return a.length - b.length;
			}
		);
	}
	return _sortedWorkspaceFolders;
}
Workspace.onDidChangeWorkspaceFolders(() => _sortedWorkspaceFolders = undefined);

function getOuterMostWorkspaceFolder(folder: WorkspaceFolder): WorkspaceFolder {
	let sorted = sortedWorkspaceFolders();
	for (let element of sorted) {
		let uri = folder.uri.toString();
		if (uri.charAt(uri.length - 1) !== '/') {
			uri = uri + '/';
		}
		if (uri.startsWith(element)) {
			return Workspace.getWorkspaceFolder(Uri.parse(element));
		}
	}
	return folder;
}
开发者ID:voodoos,项目名称:vscode-extension-samples,代码行数:30,代码来源:extension.ts

示例9: promptToImportWorkspaceFolders

	promptToImportWorkspaceFolders(workspaceFolders);
}

function onDidChangeWorkspaceFolders(event: vscode.WorkspaceFoldersChangeEvent)
{
	let added = event.added.filter((folder) =>
	{
		return isFlashBuilderProject(folder) && !isVSCodeProject(folder);
	});
	if(added.length === 0)
	{
		return;
	}
	checkForFlashBuilderProjectsToImport();
}
vscode.workspace.onDidChangeWorkspaceFolders(onDidChangeWorkspaceFolders);

export function pickFlashBuilderProjectInWorkspace()
{
	let workspaceFolders = vscode.workspace.workspaceFolders
	if(!workspaceFolders)
	{
		vscode.window.showErrorMessage(ERROR_NO_PROJECTS);
		return;
	}

	workspaceFolders = workspaceFolders.filter((folder) =>
	{
		return isFlashBuilderProject(folder);
	});
	if(workspaceFolders.length === 0)
开发者ID:BowlerHatLLC,项目名称:vscode-nextgenas,代码行数:31,代码来源:importFlashBuilderProject.ts

示例10: activate


//.........这里部分代码省略.........
	// Some actions only apply to Dart.
	formattingEditProvider.registerTypingFormatter(DART_MODE, "}", ";");
	context.subscriptions.push(vs.languages.registerCodeActionsProvider(DART_MODE, sourceCodeActionProvider, sourceCodeActionProvider.metadata));

	rankingCodeActionProvider.registerProvider(new IgnoreLintCodeActionProvider(activeFileFilters));
	context.subscriptions.push(vs.languages.registerImplementationProvider(DART_MODE, implementationProvider));
	if (config.showTestCodeLens) {
		const codeLensProvider = new TestCodeLensProvider(analyzer);
		context.subscriptions.push(codeLensProvider);
		context.subscriptions.push(vs.languages.registerCodeLensProvider(DART_MODE, codeLensProvider));
	}

	// Register the ranking provider from VS Code now that it has all of its delegates.
	context.subscriptions.push(vs.languages.registerCodeActionsProvider(activeFileFilters, rankingCodeActionProvider, rankingCodeActionProvider.metadata));

	// Task handlers.
	if (config.previewBuildRunnerTasks) {
		context.subscriptions.push(vs.tasks.registerTaskProvider("pub", new PubBuildRunnerTaskProvider(sdks)));
	}

	// Snippets are language-specific
	context.subscriptions.push(vs.languages.registerCompletionItemProvider(DART_MODE, new SnippetCompletionItemProvider("snippets/dart.json", (_) => true)));
	context.subscriptions.push(vs.languages.registerCompletionItemProvider(DART_MODE, new SnippetCompletionItemProvider("snippets/flutter.json", (uri) => util.isInsideFlutterProject(uri))));

	context.subscriptions.push(vs.languages.setLanguageConfiguration(DART_MODE.language, new DartLanguageConfiguration()));
	const statusReporter = new AnalyzerStatusReporter(analyzer, workspaceContext, analytics);

	// Set up diagnostics.
	const diagnostics = vs.languages.createDiagnosticCollection("dart");
	context.subscriptions.push(diagnostics);
	const diagnosticsProvider = new DartDiagnosticProvider(analyzer, diagnostics);

	// Set the roots, handling project changes that might affect SDKs.
	context.subscriptions.push(vs.workspace.onDidChangeWorkspaceFolders((f) => recalculateAnalysisRoots()));
	// TODO: Currently calculating analysis roots requires the version to check if
	// we need the package workaround. In future if we stop supporting server < 1.20.1 we
	// can unwrap this call so that it'll start sooner.
	const serverConnected = analyzer.registerForServerConnected((sc) => {
		serverConnected.dispose();
		if (vs.workspace.workspaceFolders)
			recalculateAnalysisRoots();
	});

	// Hook editor changes to send updated contents to analyzer.
	context.subscriptions.push(new FileChangeHandler(analyzer));

	// Fire up Flutter daemon if required.
	if (workspaceContext.hasAnyFlutterMobileProjects) {
		flutterDaemon = new FlutterDaemon(path.join(sdks.flutter, flutterPath), sdks.flutter);
		context.subscriptions.push(flutterDaemon);
		setUpDaemonMessageHandler(context, flutterDaemon);
	}

	util.logTime("All other stuff before debugger..");

	const pubGlobal = new PubGlobal(extContext, sdks);

	// Set up debug stuff.
	const debugProvider = new DebugConfigProvider(sdks, analytics, pubGlobal, flutterDaemon && flutterDaemon.deviceManager, flutterCapabilities);
	context.subscriptions.push(vs.debug.registerDebugConfigurationProvider("dart", debugProvider));
	context.subscriptions.push(debugProvider);

	// Setup that requires server version/capabilities.
	const connectedSetup = analyzer.registerForServerConnected((sc) => {
		connectedSetup.dispose();
开发者ID:DanTup,项目名称:Dart-Code,代码行数:66,代码来源:extension.ts

示例11: imageDecorator


//.........这里部分代码省略.........
                        }
                    } catch (error) {
                        result = Promise.resolve(fallback(markedString(item.imagePath)));
                    }
                }
            }
            return result;
        }
    };

    const refreshAllVisibleEditors = () => {
        vscode.window.visibleTextEditors
            .map(p => p.document)
            .filter(p => p != null)
            .forEach(doc => throttledScan(doc));
    };

    const getDocumentDecorators = (document: vscode.TextDocument): ScanResult => {
        const scanResult = scanResults[document.uri.toString()] || {
            decorations: [],
            token: new vscode.CancellationTokenSource()
        };
        scanResults[document.uri.toString()] = scanResult;
        return scanResult;
    };
    const scan = (document: vscode.TextDocument) => {
        const editors = findEditorsForDocument(document);
        if (editors.length > 0) {
            const showImagePreviewOnGutter = getConfiguredProperty(document, 'showImagePreviewOnGutter', true);
            const visibleLines = [];
            for (const editor of editors) {
                for (const range of editor.visibleRanges) {
                    let lineIndex = range.start.line;
                    while (lineIndex <= range.end.line) {
                        visibleLines.push(lineIndex);
                        lineIndex++;
                    }
                }
            }
            const scanResult = getDocumentDecorators(document);
            scanResult.token.cancel();
            scanResult.token = new vscode.CancellationTokenSource();

            decoratorProvider(document, visibleLines, scanResult.token.token)
                .then(symbolResponse => {
                    const scanResult = getDocumentDecorators(document);
                    clearEditorDecorations(document, scanResult.decorations.map(p => p.textEditorDecorationType));
                    scanResult.decorations.length = 0;

                    symbolResponse.images.forEach(p => {
                        editors.forEach(editor =>
                            decorate(showImagePreviewOnGutter, editor, p, scanResult.decorations)
                        );
                    });
                })
                .catch(e => {
                    console.error(e);
                });
        }
    };

    context.subscriptions.push(vscode.languages.registerHoverProvider(['*'], hoverProvider));

    context.subscriptions.push(
        vscode.workspace.onDidChangeTextDocument(e => {
            if (e) {
                throttledScan(e.document);
            }
        })
    );
    context.subscriptions.push(
        vscode.window.onDidChangeActiveTextEditor(e => {
            if (e) {
                throttledScan(e.document);
            }
        })
    );
    context.subscriptions.push(
        vscode.workspace.onDidChangeWorkspaceFolders(() => {
            refreshAllVisibleEditors();
        })
    );
    context.subscriptions.push(
        vscode.window.onDidChangeTextEditorVisibleRanges(event => {
            if (event && event.textEditor && event.textEditor.document) {
                const document = event.textEditor.document;
                throttledScan(document, 50);
            }
        })
    );
    context.subscriptions.push(
        vscode.workspace.onDidOpenTextDocument(e => {
            if (e) {
                throttledScan(e);
            }
        })
    );

    refreshAllVisibleEditors();
}
开发者ID:kisstkondoros,项目名称:gutter-preview,代码行数:101,代码来源:decorator.ts


注:本文中的vscode.workspace.onDidChangeWorkspaceFolders方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。