Example #1
0
/**
 * 
 */
function showNodeMCUToolbox() {
	vscode.commands.executeCommand('vscode.previewHtml', DeviceInfoContentProvider.uri, vscode.ViewColumn.One, 'NodeMCU Toolbox').then((success) => {}, (reason) => {
		vscode.window.showErrorMessage(reason);
	});
}
Example #2
0
 }).then(editor => {
     assert(vscode.window.activeTextEditor, 'No active editor');
     textEditor = editor;
     return vscode.commands.executeCommand('python.sortImports');
 }).then(() => {
export function activate(context: vscode.ExtensionContext) {


    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated


    var openurl = require('open');
    var fs = require('fs');
    var GitHubApi = require("github4");

    var github = new GitHubApi({
        version: "3.0.0"
    });




    var disposable = vscode.commands.registerCommand('extension.updateSettings', async () => {
        var en: envir.Environment = new envir.Environment(context);
        var common: commons.Commons = new commons.Commons(en);
        var myGi: myGit.GithubService = null;

        async function Init() {

            vscode.window.setStatusBarMessage("Checking for Github Token and GIST.", 2000);
            var syncSetting: Setting = await common.InitSettings();
            if (syncSetting.Token == null || syncSetting.Token == "") {
                openurl("https://github.com/settings/tokens");
                await common.GetTokenAndSave(syncSetting).then(function (saved: boolean) {
                    if (saved) {
                        Init();
                        return;
                    }
                    else {
                        vscode.window.showErrorMessage("TOKEN NOT SAVED");
                        return;
                    }
                }, function (err: any) {
                    console.error(err);
                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                    return;
                });
            }
            else {
                myGi = new myGit.GithubService(syncSetting.Token);
                vscode.window.setStatusBarMessage("Uploading / Updating Your Settings In Github.", 3000);
                await startGitProcess(syncSetting);
                return;
            }
        }


        async function startGitProcess(sett: Setting) {

            if (sett.Token != null) {
                var allSettingFiles = new Array<File>();
                vscode.window.setStatusBarMessage("Reading Settings and Extensions.", 1000);
                await fileManager.FileManager.FileExists(en.FILE_SETTING).then(async function (fileExists: boolean) {
                    if (fileExists) {
                        await fileManager.FileManager.ReadFile(en.FILE_SETTING).then(function (settings: string) {
                            if (settings) {
                                var fileName = en.FILE_SETTING_NAME;
                                var filePath = en.FILE_SETTING;
                                var fileContent = settings;
                                var file: File = new File(fileName, fileContent, filePath);
                                allSettingFiles.push(file);
                            }
                        });
                    }
                });

                await fileManager.FileManager.FileExists(en.FILE_LAUNCH).then(async function (fileExists: boolean) {
                    if (fileExists) {
                        await fileManager.FileManager.ReadFile(en.FILE_LAUNCH).then(function (launch: string) {
                            if (launch) {
                                var fileName = en.FILE_LAUNCH_NAME;
                                var filePath = en.FILE_LAUNCH;
                                var fileContent = launch;
                                var file: File = new File(fileName, fileContent, filePath);
                                allSettingFiles.push(file);
                            }
                        });
                    }
                });

                var destinationKeyBinding : string = "";
                if (en.OsType == OsType.Mac) {
                    destinationKeyBinding = en.FILE_KEYBINDING_MAC;
                }
                else{
                    destinationKeyBinding = en.FILE_KEYBINDING_DEFAULT;
                }

                await fileManager.FileManager.FileExists(en.FILE_KEYBINDING).then(async function (fileExists: boolean) {
                    if (fileExists) {
                        await fileManager.FileManager.ReadFile(en.FILE_KEYBINDING).then(function (keybinding: string) {
                            if (keybinding) {
                                var fileName = destinationKeyBinding;
                                var filePath = en.FILE_KEYBINDING;
                                var fileContent = keybinding;
                                var file: File = new File(fileName, fileContent, filePath);
                                allSettingFiles.push(file);
                            }
                        });
                    }
                });


                await fileManager.FileManager.FileExists(en.FILE_LOCALE).then(async function (fileExists: boolean) {
                    if (fileExists) {
                        await fileManager.FileManager.ReadFile(en.FILE_LOCALE).then(function (locale: string) {
                            if (locale) {
                                var fileName = en.FILE_LOCALE_NAME;
                                var filePath = en.FILE_LOCALE;
                                var fileContent = locale;
                                var file: File = new File(fileName, fileContent, filePath);
                                allSettingFiles.push(file);
                            }
                        });
                    }
                });


                var extensionlist = pluginService.PluginService.CreateExtensionList();
                extensionlist.sort(function (a, b) {
                    return a.name.localeCompare(b.name);
                });

                var fileName = en.FILE_EXTENSION_NAME;
                var filePath = en.FILE_EXTENSION;
                var fileContent = JSON.stringify(extensionlist, undefined, 2);;
                var file: File = new File(fileName, fileContent, filePath);
                allSettingFiles.push(file);


                var snippetFiles = await fileManager.FileManager.ListFiles(en.FOLDER_SNIPPETS);
                snippetFiles.forEach(snippetFile => {
                    allSettingFiles.push(snippetFile);
                });


                if (sett.Gist == null || sett.Gist === "") {
                    await myGi.CreateNewGist(allSettingFiles).then(async function (gistID: string) {
                        if (gistID) {
                            sett.Gist = gistID;
                            await common.SaveSettings(sett).then(function (added: boolean) {
                                if (added) {
                                    vscode.window.showInformationMessage("Uploaded Successfully." + " GIST ID :  " + gistID + " . Please copy and use this ID in other machines to sync all settings.");
                                    vscode.window.setStatusBarMessage("Gist Saved.", 1000);
                                }
                            }, function (err: any) {
                                console.error(err);
                                vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                return;
                            });
                        }
                        else {
                            vscode.window.showErrorMessage("GIST ID: undefined" + common.ERROR_MESSAGE);
                            return;
                        }
                    }, function (error: any) {
                        vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                        return;
                    });
                }
                else {
                    await myGi.ExistingGist(sett.Gist, allSettingFiles).then(function (added: boolean) {
                        vscode.window.showInformationMessage("Settings Updated Successfully");

                    }, function (error: any) {
                        vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                        return;
                    });
                }
            }
            else {
                vscode.window.showErrorMessage("ERROR ! Github Account Token Not Set");
            }
        }

        await Init();

    });


    var disposable = vscode.commands.registerCommand('extension.downloadSettings', async () => {

        var en: envir.Environment = new envir.Environment(context);
        var common: commons.Commons = new commons.Commons(en);
        var myGi: myGit.GithubService = null;

        async function Init() {

            vscode.window.setStatusBarMessage("Checking for Github Token and GIST.", 2000);
            var syncSetting: Setting = await common.InitSettings();
            if (syncSetting.Token == null || syncSetting.Token == "") {
                openurl("https://github.com/settings/tokens");
                await common.GetTokenAndSave(syncSetting).then(function (saved: boolean) {
                    if (saved) {
                        Init();
                        return;
                    }
                    else {
                        vscode.window.showErrorMessage("TOKEN NOT SAVED");
                        return;
                    }
                }, function (err: any) {
                    console.error(err);
                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                    return;
                });
            }
            myGi = new myGit.GithubService(syncSetting.Token);
            if (syncSetting.Gist == null || syncSetting.Gist == "") {
                await common.GetGistAndSave(syncSetting).then(function (saved: boolean) {
                    if (saved) {
                        Init();
                        return;
                    }
                    else {
                        vscode.window.showErrorMessage("GIST NOT SAVED");
                        return;
                    }
                }, function (err: any) {
                    console.error(err);
                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                    return;
                });
            }
            await StartDownload(syncSetting.Gist);

        }

        async function StartDownload(gist: string) {

            myGi.DownloadGist(gist).then(async function (res: any) {
                var keys = Object.keys(res.files);

                for (var i: number = 0; i < keys.length; i++) {
                    switch (keys[i]) {
                        case "launch.json": {
                            await fileManager.FileManager.WriteFile(en.FILE_LAUNCH, res.files[en.FILE_LAUNCH_NAME].content).then(
                                function (added: boolean) {
                                    vscode.window.showInformationMessage("Launch Settings downloaded Successfully");
                                }, function (error: any) {
                                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                    return;
                                }
                            );
                            break;
                        }
                        case "settings.json": {
                            await fileManager.FileManager.WriteFile(en.FILE_SETTING, res.files[en.FILE_SETTING_NAME].content).then(
                                function (added: boolean) {
                                    vscode.window.showInformationMessage("Editor Settings downloaded Successfully");
                                }, function (error: any) {
                                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                    return;
                                });
                            break;
                        }
                        case en.FILE_KEYBINDING_DEFAULT || en.FILE_KEYBINDING_MAC: {
                            
                            var sourceKeyBinding : string = "";
                            var os : string = null;
                            if (en.OsType == OsType.Mac) {
                                sourceKeyBinding = en.FILE_KEYBINDING_MAC;
                                os = "Mac";
                            }
                            else{
                                sourceKeyBinding = en.FILE_KEYBINDING_DEFAULT;
                            }

                            await fileManager.FileManager.WriteFile(en.FILE_KEYBINDING, res.files[sourceKeyBinding].content).then(
                                function (added: boolean) {
                                    if (os) {
                                    vscode.window.showInformationMessage("Keybinding Settings for Mac downloaded Successfully");    
                                    }
                                    vscode.window.showInformationMessage("Keybinding Settings downloaded Successfully");
                                }, function (error: any) {
                                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                    return;
                                });
                            break;
                        }
                        case "locale.json": {

                            await fileManager.FileManager.WriteFile(en.FILE_LOCALE, res.files[en.FILE_LOCALE_NAME].content).then(
                                function (added: boolean) {
                                    vscode.window.showInformationMessage("Locale Settings downloaded Successfully");
                                }, function (error: any) {
                                    vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                    return;
                                });
                            break;
                        }
                        case "extensions.json": {

                            var extensionlist = pluginService.PluginService.CreateExtensionList();
                            extensionlist.sort(function (a, b) {
                                return a.name.localeCompare(b.name);
                            });


                            var remoteList = pluginService.ExtensionInformation.fromJSONList(res.files[en.FILE_EXTENSION_NAME].content);
                            var deletedList = pluginService.PluginService.GetDeletedExtensions(remoteList);

                            for (var deletedItemIndex = 0; deletedItemIndex < deletedList.length; deletedItemIndex++) {
                                var deletedExtension = deletedList[deletedItemIndex];
                                await pluginService.PluginService.DeleteExtension(deletedExtension, en.ExtensionFolder)
                                    .then((res) => {
                                        vscode.window.showInformationMessage(deletedExtension.name + '-' + deletedExtension.version + " is removed.");
                                    }, (rej) => {
                                        vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                     });
                            }

                            var missingList = pluginService.PluginService.GetMissingExtensions(remoteList);
                            if (missingList.length == 0) {
                                vscode.window.showInformationMessage("No extension need to be installed");
                            }
                            else {
                                var actionList = new Array<Promise<void>>();
                                vscode.window.setStatusBarMessage("Installing Extensions in background.");
                                missingList.forEach(element => {
                                    actionList.push(pluginService.PluginService.InstallExtension(element, en.ExtensionFolder)
                                        .then(function () {
                                            var name = element.publisher + '.' + element.name + '-' + element.version;
                                            vscode.window.showInformationMessage("Extension " + name + " installed Successfully");
                                        }));
                                });
                                Promise.all(actionList)
                                    .then(function () {
                                        vscode.window.setStatusBarMessage("Restart Required to use installed extensions.");
                                        vscode.window.showInformationMessage("Extension installed Successfully, please restart");
                                    })
                                    .catch(function (e) {
                                        console.log(e);
                                        vscode.window.setStatusBarMessage("");
                                        vscode.window.showErrorMessage("Extension download failed." + common.ERROR_MESSAGE)
                                    });
                            }
                            break;
                        }
                        default: {
                            if (i < keys.length) {
                                await fileManager.FileManager.CreateDirectory(en.FOLDER_SNIPPETS);

                                var file = en.FOLDER_SNIPPETS.concat(keys[i]);//.concat(".json");
                                var fileName = keys[i]//.concat(".json");
                                await fileManager.FileManager.WriteFile(file, res.files[keys[i]].content).then(
                                    function (added: boolean) {
                                        vscode.window.showInformationMessage(fileName + " snippet added successfully.");
                                    }, function (error: any) {
                                        vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                                        return;
                                    }
                                );
                            }
                            break;
                        }
                    }
                }
            }, function (err: any) {
                vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                return;
            });
        }
        await Init();
    });

    var disposable = vscode.commands.registerCommand('extension.resetSettings', async () => {
        var en: envir.Environment = new envir.Environment(context);
        var fManager: fileManager.FileManager;
        var common: commons.Commons = new commons.Commons(en);
        var syncSetting: Setting = await common.InitSettings();

        vscode.window.setStatusBarMessage("Resetting Your Settings.", 2000);
        try {
            syncSetting.Token = null;
            syncSetting.Gist = null;
            await common.SaveSettings(syncSetting).then(function (added: boolean) {
                if (added) {
                    vscode.window.showInformationMessage("GIST ID and Github Token Cleared.");
                }
            }, function (err: any) {
                console.error(err);
                vscode.window.showErrorMessage(common.ERROR_MESSAGE);
                return;
            });

        }
        catch (err) {
            console.log(err);
            vscode.window.showErrorMessage("Unable to clear settings. Error Logged on console. Please open an issue.");
        }
    });
    var disposable = vscode.commands.registerCommand('extension.releaseNotes', async () => {
        openurl("http://shanalikhan.github.io/2016/05/14/Visual-studio-code-sync-settings-release-notes.html");
    });

    context.subscriptions.push(disposable);
}
Example #4
0
	constructor(context: vs.ExtensionContext, analyzer: Analyzer) {
		context.subscriptions.push(vs.commands.registerCommand("dart.openAnalyzerDiagnostics", async () => {
			const res = await analyzer.diagnosticGetServerPort();
			openInBrowser(`http://localhost:${res.port}/`);
		}));
	}
Example #5
0
	test('showQuickPick, accept first', async function () {
		const pick = window.showQuickPick(['eins', 'zwei', 'drei']);
		await new Promise(resolve => setTimeout(resolve, 10)); // Allow UI to update.
		await commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem');
		assert.equal(await pick, 'eins');
	});
Example #6
0
export function create(client: ITypescriptServiceClient, isOpen: (path: string) => Promise<boolean>, memento: vscode.Memento) {

	const toDispose: vscode.Disposable[] = [];
	const projectHinted: { [k: string]: boolean } = Object.create(null);

	const projectHintIgnoreList = memento.get<string[]>('projectHintIgnoreList', []);
	for (let path of projectHintIgnoreList) {
		if (path === null) {
			path = undefined;
		}
		projectHinted[path] = true;
	}

	let currentHint: Hint;
	let item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, Number.MIN_VALUE);
	item.command = 'js.projectStatus.command';
	toDispose.push(vscode.commands.registerCommand('js.projectStatus.command', () => {
		let {message, options} = currentHint;
		return vscode.window.showInformationMessage(message, ...options).then(selection => {
			if (selection) {
				return selection.execute();
			}
		});
	}));

	toDispose.push(vscode.workspace.onDidChangeTextDocument(e => {
		delete projectHinted[e.document.fileName];
	}));

	function onEditor(editor: vscode.TextEditor): void {
		if (!editor
			|| !vscode.languages.match(selector, editor.document)
			|| !client.asAbsolutePath(editor.document.uri)) {

			item.hide();
			return;
		}

		const file = client.asAbsolutePath(editor.document.uri);
		isOpen(file).then(value => {
			if (!value) {
				return;
			}

			return client.execute('projectInfo', { file, needFileNameList: true }).then(res => {

				let {configFileName, fileNames} = res.body;

				if (projectHinted[configFileName] === true) {
					return;
				}

				if (!configFileName && vscode.workspace.rootPath) {
					exists(join(vscode.workspace.rootPath, 'jsconfig.json'), exists => {
						// don't hint if there is a global jsconfig-file. We can get here due
						// to TypeScript bugs or jsconfig configurations
						if (exists) {
							return;
						}
						currentHint = {
							message: localize('hintCreate', "Create a jsconfig.json to enable richer IntelliSense and code navigation across the entire workspace."),
							options: [{
								title: localize('ignore.cmdCreate', 'Ignore'),
								execute: () => {
									client.logTelemetry('js.hintProjectCreation.ignored');
									projectHinted[configFileName] = true;
									projectHintIgnoreList.push(configFileName);
									memento.update('projectHintIgnoreList', projectHintIgnoreList);
									item.hide();
								}
							}, {
								title: localize('cmdCreate', "Create jsconfig.json"),
								execute: () => {
									client.logTelemetry('js.hintProjectCreation.accepted');
									projectHinted[configFileName] = true;
									item.hide();

									return vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + encodeURIComponent(join(vscode.workspace.rootPath, 'jsconfig.json'))))
										.then(doc => vscode.window.showTextDocument(doc, vscode.ViewColumn.Three))
										.then(editor => editor.edit(builder => builder.insert(new vscode.Position(0, 0), defaultConfig)));
								}
							}]
						};
						item.text = '$(light-bulb)';
						item.tooltip = localize('hintCreate.tooltip', "Create a jsconfig.json to enable richer IntelliSense and code navigation across the entire workspace.");
						item.color = '#A5DF3B';
						item.show();
						client.logTelemetry('js.hintProjectCreation');
					});

				} else if (fileNames.length > fileLimit) {

					let largeRoots = computeLargeRoots(configFileName, fileNames).map(f => `'/${f}/'`).join(', ');

					currentHint = {
						message: largeRoots.length > 0
							? localize('hintExclude', "For better performance exclude folders with many files, like: {0}", largeRoots)
							: localize('hintExclude.generic', "For better performance exclude folders with many files."),
						options: [{
							title: localize('open', "Configure Excludes"),
							execute: () => {
								client.logTelemetry('js.hintProjectExcludes.accepted');
								projectHinted[configFileName] = true;
								item.hide();

								return vscode.workspace.openTextDocument(configFileName)
									.then(vscode.window.showTextDocument);
							}
						}]
					};
					item.tooltip = currentHint.message;
					item.text = localize('large.label', "Configure Excludes");
					item.tooltip = localize('hintExclude.tooltip', "For better performance exclude folders with many files.");
					item.color = '#A5DF3B';
					item.show();
					client.logTelemetry('js.hintProjectExcludes');

				} else {
					item.hide();
				}
			});
		}).catch(err => {
			client.warn(err);
		});
	}

	toDispose.push(vscode.window.onDidChangeActiveTextEditor(onEditor));
	onEditor(vscode.window.activeTextEditor);

	return vscode.Disposable.from(...toDispose);
}
Example #7
0
File: tab.ts Project: iivvoo/Vim
 private executeCommandWithCount(count: number, command: string) {
   for (let i = 0; i < count; i++) {
     vscode.commands.executeCommand(command);
   }
 }
Example #8
0
	before("run 'flutter clean'", () => vs.commands.executeCommand("_flutter.clean", fsPath(flutterHelloWorldFolder)));
export function activate(context: vscode.ExtensionContext): void {
	const outputChannel: vscode.OutputChannel = null;

	// Supported languages
	const supportedDocuments: vscode.DocumentSelector = [
		{ language: 'css', scheme: 'file' },
		{ language: 'postcss', scheme: 'file' },
		{ language: 'scss', scheme: 'file' },
		{ language: 'less', scheme: 'file' }
	];

	// For plugin command: "postcssSorting.execute"
	const command = vscode.commands.registerTextEditorCommand('postcssSorting.execute', (textEditor) => {
		// Prevent run command without active TextEditor
		if (!vscode.window.activeTextEditor) {
			return null;
		}

		const document = textEditor.document;

		const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
		const workspaceUri = workspaceFolder ? workspaceFolder.uri : null;
		const settings = settingsManager.getSettings(workspaceUri);

		use(settings, document, null)
			.then((result) => {
				if (!result) {
					return;
				}

				textEditor.edit((editBuilder) => {
					editBuilder.replace(result.range, result.css);
				});
			})
			.catch((err) => utils.output(outputChannel, err, settings.showErrorMessages));
	});

	// For commands: "Format Document" and "Format Selection"
	const format = vscode.languages.registerDocumentRangeFormattingEditProvider(supportedDocuments, {
		provideDocumentRangeFormattingEdits(document: vscode.TextDocument, range: vscode.Range): vscode.ProviderResult<vscode.TextEdit[]> {
			// Prevent run command without active TextEditor
			if (!vscode.window.activeTextEditor) {
				return null;
			}

			const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
			const workspaceUri = workspaceFolder ? workspaceFolder.uri : null;
			const settings = settingsManager.getSettings(workspaceUri);

			return use(settings, document, range)
				.catch((err) => utils.output(outputChannel, err, settings.showErrorMessages))
				.then((result) => {
					if (!result) {
						return;
					}

					return [vscode.TextEdit.replace(result.range, result.css)];
				});
		}
	});

	// Subscriptions
	context.subscriptions.push(command);
	context.subscriptions.push(format);
}
export function activate(context: vscode.ExtensionContext) {
    ExtensionServer.getInstance().start();
    performVersionsCheck(context);

    let runCommand = (project: ns.NSProject, options: string[]) => {
        if (vscode.workspace.rootPath === undefined) {
            vscode.window.showErrorMessage('No workspace opened.');
            return;
        }

        vscode.window.showQuickPick(options)
        .then(target => {
            if(target == undefined) {
                return; // e.g. if the user presses escape button
            }

            // Move the selected option to be the first element in order to keep the last selected option at the top of the list
            options.splice(options.indexOf(target), 1);
            options.unshift(target);

            // Show output channel
            let runChannel: vscode.OutputChannel = vscode.window.createOutputChannel(`Run on ${project.platform()}`);
            runChannel.clear();
            runChannel.show(vscode.ViewColumn.Two);

            // Execute run command
            let emulator: boolean = (target === 'emulator');
            AnalyticsService.getInstance().runRunCommand(project.platform(), emulator);
            return project.run(emulator)
            .then(tnsProcess => {
                tnsProcess.on('error', err => {
                    vscode.window.showErrorMessage('Unexpected error executing NativeScript Run command.');
                });
                tnsProcess.stderr.on('data', data => {
                    runChannel.append(data);
                });
                tnsProcess.stdout.on('data', data => {
                    runChannel.append(data);
                });
                tnsProcess.on('exit', exitCode => {
                    tnsProcess.stdout.removeAllListeners('data');
                    tnsProcess.stderr.removeAllListeners('data');
                });
                tnsProcess.on('close', exitCode => {
                    runChannel.hide();
                });
            });
        });
    };

    let iosRunOptions = ['device', 'emulator'];
    let runIosCommand = vscode.commands.registerCommand('nativescript.runIos', () => {
        return runCommand(new ns.IosProject(vscode.workspace.rootPath), iosRunOptions);
    });

    let androidRunOptions = ['device', 'emulator'];
    let runAndroidCommand = vscode.commands.registerCommand('nativescript.runAndroid', () => {
        return runCommand(new ns.AndroidProject(vscode.workspace.rootPath), androidRunOptions);
    });

    context.subscriptions.push(runIosCommand);
    context.subscriptions.push(runAndroidCommand);
}
Example #11
0
	before("run 'flutter create' for example", () => vs.commands.executeCommand("_flutter.create", fsPath(flutterHelloWorldExampleSubFolder)));
Example #12
0
export function activate() {
	console.log('Congratulations, your extension "TextTools" is now active!');
	vscode.commands.registerCommand('extension.textFunctions', textFunctions);
}
Example #13
0
export function setCommandContext(key: CommandContext | string, value: any) {
    return commands.executeCommand(BuiltInCommands.SetContext, key, value);
}
Example #14
0
	mcuCommands.onFSChanged(() => { if (fsListVisible) { vscode.commands.executeCommand('nodemcu.listFiles'); }});
Example #15
0
export async function activate(context: vscode.ExtensionContext) {

    var openurl = require('open');
    var fs = require('fs');

    var en: Environment = new Environment(context);
    var common: Commons = new Commons(en, context);

    await common.StartMigrationProcess();
    let startUpSetting: ExtensionConfig = await common.GetSettings();

    if (startUpSetting) {
        let tokenAvailable: boolean = (startUpSetting.token != null) && (startUpSetting.token != "");
        let gistAvailable: boolean = (startUpSetting.gist != null) && (startUpSetting.gist != "");

        if (startUpSetting.autoUpload && tokenAvailable && gistAvailable) {
            common.StartWatch();
        }

        if (gistAvailable == true && startUpSetting.autoDownload == true) {
            vscode.commands.executeCommand('extension.downloadSettings');
        }
        else {

        }
    }

    var updateSettings = vscode.commands.registerCommand('extension.updateSettings', async function () {

        let args = arguments;

        let en: Environment = new Environment(context);
        let common: Commons = new Commons(en, context);
        common.CloseWatch();

        let myGi: GithubService = null;
        let dateNow: Date = new Date();
        let localConfig: LocalConfig = new LocalConfig();
        let syncSetting: ExtensionConfig = await common.GetSettings();
        let allSettingFiles = new Array<File>();
        let uploadedExtensions = new Array<ExtensionInformation>();

        let customSettings: CustomSettings = new CustomSettings();

        let askToken: boolean = !syncSetting.anonymousGist;

        await common.InitializeSettings(syncSetting, askToken, false).then(async (resolve) => {

            localConfig.config = resolve;
            syncSetting = localConfig.config;

            if (args.length > 0) {
                if (args[0] == "publicGIST") {
                    localConfig.publicGist = true;
                }
                else {
                    localConfig.publicGist = false;
                }
            }
            myGi = new GithubService(syncSetting.token);

            await startGitProcess();

        }, (reject) => {
            common.LogException(reject, common.ERROR_MESSAGE, true);
            return;
        });

        async function startGitProcess() {

            vscode.window.setStatusBarMessage("Sync : Uploading / Updating Your Settings In Github.");

            if (!syncSetting.anonymousGist) {
                if (syncSetting.token == null && syncSetting.token == "") {
                    vscode.window.showInformationMessage("Sync : Set Github Token or set anonymousGist to true from settings.");
                    return;
                }
            }

            syncSetting.lastUpload = dateNow;
            vscode.window.setStatusBarMessage("Sync : Reading Settings and Extensions.");

            uploadedExtensions = PluginService.CreateExtensionList();

            uploadedExtensions.sort(function (a, b) {
                return a.name.localeCompare(b.name);
            });

            // var remoteList = ExtensionInformation.fromJSONList(file.content);
            // var deletedList = PluginService.GetDeletedExtensions(uploadedExtensions);

            let fileName = en.FILE_EXTENSION_NAME;
            let filePath = en.FILE_EXTENSION;
            let fileContent = JSON.stringify(uploadedExtensions, undefined, 2);;
            let file: File = new File(fileName, fileContent, filePath, fileName);
            allSettingFiles.push(file);

            let contentFiles: Array<File> = new Array();

            // if (syncSetting.workspaceSync) {
            contentFiles = await FileManager.ListFiles(en.USER_FOLDER, 0, 2);
            // }
            // else {
            //     contentFiles = await FileManager.ListFiles(en.USER_FOLDER, 0, 1);
            // }

            let customExist: boolean = await FileManager.FileExists(en.FILE_CUSTOMIZEDSETTINGS);
            if (customExist) {
                customSettings = await common.GetCustomSettings();

                contentFiles = contentFiles.filter((file: File, index: number) => {
                    let a: boolean = file.fileName != en.FILE_CUSTOMIZEDSETTINGS_NAME;
                    return a;
                });

                if (customSettings.ignoreUploadFiles.length > 0) {
                    contentFiles = contentFiles.filter((file: File, index: number) => {
                        let a: boolean = customSettings.ignoreUploadFiles.indexOf(file.fileName) == -1 && file.fileName != en.FILE_CUSTOMIZEDSETTINGS_NAME;
                        return a;
                    });
                }
                if (customSettings.ignoreUploadFolders.length > 0) {
                    contentFiles = contentFiles.filter((file: File, index: number) => {
                        let matchedFolders = customSettings.ignoreUploadFolders.filter((folder) => {
                            return file.filePath.indexOf(folder) == -1;
                        });
                        return matchedFolders.length > 0;
                    });
                }
            }
            else {

                common.LogException(null, common.ERROR_MESSAGE, true);
                return;
            }



            contentFiles.forEach(snippetFile => {

                if (snippetFile.fileName != en.APP_SUMMARY_NAME && snippetFile.fileName != en.FILE_KEYBINDING_MAC) {
                    if (snippetFile.content != "") {
                        if (snippetFile.fileName == en.FILE_KEYBINDING_NAME) {
                            var destinationKeyBinding: string = "";
                            if (en.OsType == OsType.Mac) {
                                destinationKeyBinding = en.FILE_KEYBINDING_MAC;
                            }
                            else {
                                destinationKeyBinding = en.FILE_KEYBINDING_DEFAULT;
                            }
                            snippetFile.gistName = destinationKeyBinding;
                        }
                        allSettingFiles.push(snippetFile);
                    }
                }
            });

            var extProp: CloudSetting = new CloudSetting();
            extProp.lastUpload = dateNow;
            fileName = en.FILE_CLOUDSETTINGS_NAME;
            fileContent = JSON.stringify(extProp);
            file = new File(fileName, fileContent, "", fileName);
            allSettingFiles.push(file);

            let completed: boolean = false;
            let newGIST: boolean = false;

            if (syncSetting.anonymousGist) {
                await myGi.CreateAnonymousGist(localConfig.publicGist, allSettingFiles).then(async function (gistID: string) {
                    if (gistID) {
                        newGIST = true;
                        syncSetting.gist = gistID;
                        completed = true;
                        vscode.window.setStatusBarMessage("Sync : GIST ID: " + syncSetting.gist + " created.");
                    }
                    else {
                        vscode.window.showInformationMessage("Sync : Unable to create Gist.");
                        return;
                    }
                }, function (error: any) {
                    common.LogException(error, common.ERROR_MESSAGE, true);
                    return;
                });
            }
            else {

                if (syncSetting.gist == null || syncSetting.gist === "") {
                    newGIST = true;
                    await myGi.CreateEmptyGIST(localConfig.publicGist).then(async function (gistID: string) {
                        if (gistID) {
                            syncSetting.gist = gistID;
                            vscode.window.setStatusBarMessage("Sync : GIST ID: " + syncSetting.gist + " created.");
                        }
                        else {
                            vscode.window.showInformationMessage("Sync : Unable to create Gist.");
                            return;
                        }
                    }, function (error: any) {
                        common.LogException(error, common.ERROR_MESSAGE, true);
                        return;
                    });
                }

                await myGi.ReadGist(syncSetting.gist).then(async function (gistObj: any) {

                    if (gistObj) {
                        if (gistObj.owner != null) {
                            if (gistObj.owner.login != myGi.userName) {
                                common.LogException(null, "Sync : You cant edit GIST for user : " + gistObj.owner.login, true);
                                return;
                            }
                        }
                        if (gistObj.public == true) {
                            localConfig.publicGist = true;
                        }

                        vscode.window.setStatusBarMessage("Sync : Uploading Files Data.");
                        gistObj = myGi.UpdateGIST(gistObj, allSettingFiles);

                        await myGi.SaveGIST(gistObj).then(async function (saved: boolean) {
                            if (saved) {
                                completed = true;

                            }
                            else {
                                vscode.window.showErrorMessage("GIST NOT SAVED");
                                return;
                            }
                        }, function (error: any) {
                            common.LogException(error, common.ERROR_MESSAGE, true);
                            return;
                        });
                    }
                    else {
                        vscode.window.showErrorMessage("GIST ID: " + syncSetting.gist + " UNABLE TO READ.");
                        return;
                    }
                }, function (gistReadError: any) {
                    common.LogException(gistReadError, common.ERROR_MESSAGE, true);
                    return;
                });
            }

            if (completed) {
                await common.SaveSettings(syncSetting).then(function (added: boolean) {
                    if (added) {
                        if (newGIST) {
                            vscode.window.showInformationMessage("Uploaded Successfully." + " GIST ID :  " + syncSetting.gist + " . Please copy and use this ID in other machines to sync all settings.");
                        }
                        else {
                            vscode.window.setStatusBarMessage("");
                            vscode.window.setStatusBarMessage("Uploaded Successfully.", 5000);
                        }

                        if (localConfig.publicGist) {
                            vscode.window.showInformationMessage("Sync : You can share the GIST ID to other users to download your settings.");
                        }

                        if (syncSetting.showSummary) {
                            common.GenerateSummmaryFile(true, allSettingFiles, null, uploadedExtensions, localConfig);

                        }
                        if (syncSetting.autoUpload) {
                            common.StartWatch();
                        }
                        vscode.window.setStatusBarMessage("");
                    }
                }, function (err: any) {
                    common.LogException(err, common.ERROR_MESSAGE, true);
                    return;
                });
            }
        }
    });

    var downloadSettings = vscode.commands.registerCommand('extension.downloadSettings', async function () {

        var en: Environment = new Environment(context);
        var common: Commons = new Commons(en, context);
        common.CloseWatch();

        var myGi: GithubService = null;
        var localSettings: LocalConfig = new LocalConfig();
        var syncSetting: ExtensionConfig = await common.GetSettings();
        let customSettings: CustomSettings = new CustomSettings();
        let askToken: boolean = !syncSetting.anonymousGist;

        await common.InitializeSettings(syncSetting, false, true).then(async (resolve) => {

            localSettings.config = resolve;
            syncSetting = localSettings.config;
            customSettings = await common.GetCustomSettings();
            await StartDownload();
        });

        async function StartDownload() {

            myGi = new GithubService(syncSetting.token);
            vscode.window.setStatusBarMessage("");
            vscode.window.setStatusBarMessage("Sync : Reading Settings Online.", 2000);

            myGi.ReadGist(syncSetting.gist).then(async function (res: any) {

                var addedExtensions: Array<ExtensionInformation> = new Array<ExtensionInformation>();
                var deletedExtensions: Array<ExtensionInformation> = new Array<ExtensionInformation>();
                var updatedFiles: Array<File> = new Array<File>();
                var actionList = new Array<Promise<void | boolean>>();

                if (res) {
                    if (res.public == true) {
                        localSettings.publicGist = true;
                    }
                    var keys = Object.keys(res.files);
                    if (keys.indexOf(en.FILE_CLOUDSETTINGS_NAME) > -1) {
                        var cloudSettGist: Object = JSON.parse(res.files[en.FILE_CLOUDSETTINGS_NAME].content);
                        var cloudSett: CloudSetting = Object.assign(new CloudSetting(), cloudSettGist);;

                        let lastUploadStr: string = (syncSetting.lastUpload) ? syncSetting.lastUpload.toString() : "";
                        let lastDownloadStr: string = (syncSetting.lastDownload) ? syncSetting.lastDownload.toString() : "";

                        var upToDate: boolean = false;
                        if (lastDownloadStr != "") {
                            upToDate = new Date(lastDownloadStr).getTime() === new Date(cloudSett.lastUpload).getTime();
                        }

                        if (lastUploadStr != "") {
                            upToDate = upToDate || new Date(lastUploadStr).getTime() === new Date(cloudSett.lastUpload).getTime();
                        }

                        if (!syncSetting.forceDownload) {
                            if (upToDate) {
                                vscode.window.setStatusBarMessage("");
                                vscode.window.setStatusBarMessage("Sync : You already have latest version of saved settings.", 5000);
                                return;
                            }
                        }
                        syncSetting.lastDownload = cloudSett.lastUpload;
                    }

                    keys.forEach(gistName => {
                        if (res.files[gistName]) {
                            if (res.files[gistName].content) {
                                if (gistName.indexOf(".") > -1) {
                                    if (en.OsType == OsType.Mac && gistName == en.FILE_KEYBINDING_DEFAULT) {
                                        return;
                                    }
                                    if (en.OsType != OsType.Mac && gistName == en.FILE_KEYBINDING_MAC) {
                                        return;
                                    }
                                    var f: File = new File(gistName, res.files[gistName].content, null, gistName);
                                    updatedFiles.push(f);
                                }
                            }
                        }
                        else {
                            console.log(gistName + " key in response is empty.");
                        }
                    });

                    for (var index = 0; index < updatedFiles.length; index++) {

                        var file: File = updatedFiles[index];
                        var path: string = null;
                        var writeFile: boolean = false;
                        var content: string = file.content;

                        if (content != "") {

                            if (file.gistName == en.FILE_EXTENSION_NAME) {

                                var extensionlist = PluginService.CreateExtensionList();

                                extensionlist.sort(function (a, b) {
                                    return a.name.localeCompare(b.name);
                                });

                                var remoteList = ExtensionInformation.fromJSONList(file.content);
                                var deletedList = PluginService.GetDeletedExtensions(remoteList);

                                for (var deletedItemIndex = 0; deletedItemIndex < deletedList.length; deletedItemIndex++) {
                                    var deletedExtension = deletedList[deletedItemIndex];
                                    (async function (deletedExtension: ExtensionInformation, ExtensionFolder: string) {
                                        await actionList.push(PluginService.DeleteExtension(deletedExtension, en.ExtensionFolder)
                                            .then((res) => {
                                                //vscode.window.showInformationMessage(deletedExtension.name + '-' + deletedExtension.version + " is removed.");
                                                deletedExtensions.push(deletedExtension);
                                            }, (rej) => {
                                                common.LogException(rej, common.ERROR_MESSAGE, true);
                                            }));
                                    }(deletedExtension, en.ExtensionFolder));

                                }

                                var missingList = PluginService.GetMissingExtensions(remoteList);
                                if (missingList.length == 0) {
                                    vscode.window.setStatusBarMessage("");
                                    vscode.window.setStatusBarMessage("Sync : No Extension needs to be installed.", 2000);
                                }
                                else {

                                    vscode.window.setStatusBarMessage("Sync : Installing Extensions in background.");
                                    missingList.forEach(async (element) => {

                                        await actionList.push(PluginService.InstallExtension(element, en.ExtensionFolder)
                                            .then(function () {
                                                addedExtensions.push(element);
                                                //var name = element.publisher + '.' + element.name + '-' + element.version;
                                                //vscode.window.showInformationMessage("Extension " + name + " installed Successfully");
                                            }));
                                    });
                                }
                            }
                            else {

                                writeFile = true;
                                if (file.gistName == en.FILE_KEYBINDING_DEFAULT || file.gistName == en.FILE_KEYBINDING_MAC) {
                                    let test: string = "";
                                    en.OsType == OsType.Mac ? test = en.FILE_KEYBINDING_MAC : test = en.FILE_KEYBINDING_DEFAULT;
                                    if (file.gistName != test) {
                                        writeFile = false;
                                    }
                                }
                                if (writeFile) {
                                    if (file.gistName == en.FILE_KEYBINDING_MAC) {
                                        file.fileName = en.FILE_KEYBINDING_DEFAULT;
                                    }
                                    let filePath: string = await FileManager.CreateDirTree(en.USER_FOLDER, file.fileName);
                                    await actionList.push(FileManager.WriteFile(filePath, content).then(
                                        function (added: boolean) {
                                            //TODO : add Name attribute in File and show information message here with name , when required.
                                        }, function (error: any) {
                                            common.LogException(error, common.ERROR_MESSAGE, true);
                                            return;
                                        }
                                    ));
                                }
                            }
                        }
                    }
                }
                else {
                    common.LogException(res, "Sync : Unable to Read Gist.", true);
                }

                Promise.all(actionList)
                    .then(async function () {

                        // if (!syncSetting.showSummary) {
                        //     if (missingList.length == 0) {
                        //         //vscode.window.showInformationMessage("No extension need to be installed");
                        //     }
                        //     else {
                        //         //extension message when summary is turned off
                        //         vscode.window.showInformationMessage("Sync : " + missingList.length + " extensions installed Successfully, Restart Required.");
                        //     }
                        //     if (deletedExtensions.length > 0) {
                        //         vscode.window.showInformationMessage("Sync : " + deletedExtensions.length + " extensions deleted Successfully, Restart Required.");
                        //     }
                        // }

                        await common.SaveSettings(syncSetting).then(async function (added: boolean) {
                            if (added) {

                                if (syncSetting.showSummary) {
                                    common.GenerateSummmaryFile(false, updatedFiles, deletedExtensions, addedExtensions, localSettings);
                                }

                                vscode.window.setStatusBarMessage("");
                                vscode.window.setStatusBarMessage("Sync : Download Complete.", 5000);
                                if (Object.keys(customSettings.replaceCodeSettings).length > 0) {
                                    let config = vscode.workspace.getConfiguration();
                                    
                                    let keysDefined : Array<string> = Object.keys(customSettings.replaceCodeSettings);

                                    keysDefined.forEach((key: string, index: number) => {
                                        let c: string = undefined;
                                        let value : string = customSettings.replaceCodeSettings[key];
                                        value == "" ? c == undefined : c = value;
                                        config.update(key, c, true);
                                    });
                                }


                                if (syncSetting.autoUpload) {
                                    common.StartWatch();
                                }
                            }
                            else {
                                vscode.window.showErrorMessage("Sync : Unable to save extension settings file.")
                            }
                        }, function (errSave: any) {
                            common.LogException(errSave, common.ERROR_MESSAGE, true);
                            return;
                        });
                    })
                    .catch(function (e) {
                        common.LogException(e, common.ERROR_MESSAGE, true);
                    });
            }, function (err: any) {
                common.LogException(err, common.ERROR_MESSAGE, true);
                return;
            });
        }
    });

    var resetSettings = vscode.commands.registerCommand('extension.resetSettings', async () => {
        var en: Environment = new Environment(context);
        var fManager: FileManager;
        var common: Commons = new Commons(en, context);
        var syncSetting: ExtensionConfig = await common.GetSettings();
        await Init();

        async function Init() {
            vscode.window.setStatusBarMessage("Sync : Resetting Your Settings.", 2000);
            try {
                syncSetting = new ExtensionConfig();

                await common.SaveSettings(syncSetting).then(function (added: boolean) {
                    if (added) {
                        vscode.window.showInformationMessage("Sync : Settings Cleared.");
                    }
                }, function (err: any) {
                    common.LogException(err, common.ERROR_MESSAGE, true);
                    return;
                });

            }
            catch (err) {
                common.LogException(err, "Sync : Unable to clear settings. Error Logged on console. Please open an issue.", true);
            }
        }

    });

    var howSettings = vscode.commands.registerCommand('extension.HowSettings', async () => {
        openurl("http://shanalikhan.github.io/2015/12/15/Visual-Studio-Code-Sync-Settings.html");
    });

    var otherOptions = vscode.commands.registerCommand('extension.otherOptions', async () => {
        var en: Environment = new Environment(context);
        var common: Commons = new Commons(en, context);
        var setting: ExtensionConfig = await common.GetSettings();
        var localSetting: LocalConfig = new LocalConfig();
        var tokenAvailable: boolean = setting.token != null && setting.token != "";
        var gistAvailable: boolean = setting.gist != null && setting.gist != "";
        let customSettings: CustomSettings = await common.GetCustomSettings();

        let items: Array<string> = new Array<string>();
        items.push("Sync : Edit Extension Local Settings");
        items.push("Sync : Share Settings with Public GIST");
        items.push("Sync : Toggle Force Download");
        items.push("Sync : Toggle Auto-Upload On Settings Change");
        items.push("Sync : Toggle Auto-Download On Startup");
        items.push("Sync : Toggle Show Summary Page On Upload / Download");
        items.push("Sync : Preserve Setting to stop overide during Download");
        items.push("Sync : Open Issue");
        items.push("Sync : Release Notes");

        var selectedItem: Number = 0;
        var settingChanged: boolean = false;

        var teims = vscode.window.showQuickPick(items).then(async (resolve: string) => {

            switch (resolve) {
                case items[0]: {
                    //extension local settings
                    var file: vscode.Uri = vscode.Uri.file(en.FILE_CUSTOMIZEDSETTINGS);
                    fs.openSync(file.fsPath, 'r');

                    await vscode.workspace.openTextDocument(file).then((a: vscode.TextDocument) => {
                        vscode.window.showTextDocument(a, vscode.ViewColumn.One, true);
                    });
                    break;
                }
                case items[1]: {
                    //share public gist
                    await vscode.window.showInformationMessage("Sync : This will remove current GIST and upload settings on new public GIST. Do you want to continue ?", "Yes").then((resolve) => {
                        if (resolve == "Yes") {
                            localSetting.publicGist = true;
                            settingChanged = true;
                            setting.gist = "";
                            selectedItem = 1;
                        }
                    }, (reject) => {
                        return;
                    });
                    break;
                }
                case items[2]: {
                    //toggle force download
                    selectedItem = 2;
                    settingChanged = true;
                    if (setting.forceDownload) {
                        setting.forceDownload = false;
                    }
                    else {
                        setting.forceDownload = true;
                    }
                    break;
                }
                case items[3]: {
                    //toggle auto upload
                    selectedItem = 3;
                    settingChanged = true;
                    if (setting.autoUpload) {
                        setting.autoUpload = false;
                    }
                    else {
                        setting.autoUpload = true;
                    }
                    break;
                }
                case items[4]: {
                    //auto downlaod on startup
                    selectedItem = 4;
                    settingChanged = true;

                    if (!setting) {
                        vscode.commands.executeCommand('extension.HowSettings');
                        return;
                    }

                    if (!tokenAvailable || !gistAvailable) {
                        vscode.commands.executeCommand('extension.HowSettings');
                        return;
                    }
                    if (setting.autoDownload) {
                        setting.autoDownload = false;
                    }
                    else {
                        setting.autoDownload = true;
                    }
                    break;
                }
                case items[5]: {
                    //page summary toggle
                    selectedItem = 5;
                    settingChanged = true;

                    if (!tokenAvailable || !gistAvailable) {
                        vscode.commands.executeCommand('extension.HowSettings');
                        return;
                    }
                    if (setting.showSummary) {
                        setting.showSummary = false;
                    }
                    else {
                        setting.showSummary = true;
                    }
                    break;
                }

                case items[6]: {
                    //preserve
                    let options: vscode.InputBoxOptions = {
                        ignoreFocusOut: true,
                        placeHolder: "Enter any Key from settings.json to preserve.",
                        prompt: "Example : Write 'http.proxy' => store this computer proxy and overwrite it , if set empty it will remove proxy."

                    };
                    vscode.window.showInputBox(options).then(async (res) => {
                        //customSettings
                        //debugger;
                        if (res) {
                            let settingKey: string = res;
                            let a = vscode.workspace.getConfiguration();
                            let val: string = a.get<string>(settingKey);
                            customSettings.replaceCodeSettings[res] = val;
                            let done: boolean = await common.SetCustomSettings(customSettings);
                            if (done) {
                                if (val == "") {
                                    vscode.window.showInformationMessage("Sync : Done. " + res + " value will be removed from settings.json after downloading.");
                                }
                                else {
                                    vscode.window.showInformationMessage("Sync : Done. Extension will keep " + res + " : " + val + " in setting.json after downloading.");
                                }
                            }
                        }
                    });
                    break;
                }
                case items[7]: {
                    openurl("https://github.com/shanalikhan/code-settings-sync/issues/new");
                    break;
                }
                case items[8]: {
                    openurl("http://shanalikhan.github.io/2016/05/14/Visual-studio-code-sync-settings-release-notes.html");
                    break;
                }

                default: {
                    break;
                }


            }
        }, (reject) => {
            common.LogException(reject, "Error", true);
            return;
        }).then(async (resolve: any) => {
            if (settingChanged) {
                if (selectedItem == 1) {
                    common.CloseWatch();
                }
                await common.SaveSettings(setting).then(async function (added: boolean) {
                    if (added) {
                        switch (selectedItem) {
                            case 4: {
                                if (setting.autoDownload) {
                                    vscode.window.showInformationMessage("Sync : Auto Download turned ON upon VSCode Startup.");
                                }
                                else {
                                    vscode.window.showInformationMessage("Sync : Auto Download turned OFF upon VSCode Startup.");
                                }
                                break;
                            }
                            case 5: {
                                if (setting.showSummary) {
                                    vscode.window.showInformationMessage("Sync : Summary Will be shown upon download / upload.");
                                }
                                else {
                                    vscode.window.showInformationMessage("Sync : Summary Will be hidden upon download / upload.");
                                }
                                break;
                            }
                            case 2: {
                                if (setting.forceDownload) {
                                    vscode.window.showInformationMessage("Sync : Force Download Turned On.");
                                }
                                else {
                                    vscode.window.showInformationMessage("Sync : Force Download Turned Off.");
                                }
                                break;
                            }
                            case 3: {
                                if (setting.autoUpload) {
                                    vscode.window.showInformationMessage("Sync : Auto upload on Setting Change Turned On. Will be affected after restart.");
                                }
                                else {
                                    vscode.window.showInformationMessage("Sync : Auto upload on Setting Change Turned Off.");
                                }
                                break;
                            }
                            case 1: {
                                await vscode.commands.executeCommand('extension.updateSettings', "publicGIST");
                                break;
                            }
                        }
                    }
                    else {
                        vscode.window.showErrorMessage("Unable to Toggle.");
                    }
                }, function (err: any) {
                    common.LogException(err, "Sync : Unable to toggle. Please open an issue.", true);
                    return;
                });
            }

        }, (reject: any) => {
            common.LogException(reject, "Error", true);
            return;
        });
    });

    context.subscriptions.push(updateSettings);
    context.subscriptions.push(downloadSettings);
    context.subscriptions.push(resetSettings);
    context.subscriptions.push(howSettings);
    context.subscriptions.push(otherOptions);

}
Example #16
0
	const onRepository = () => commands.executeCommand('setContext', 'gitOpenRepositoryCount', `${model.repositories.length}`);
Example #17
0
        var teims = vscode.window.showQuickPick(items).then(async (resolve: string) => {

            switch (resolve) {
                case items[0]: {
                    //extension local settings
                    var file: vscode.Uri = vscode.Uri.file(en.FILE_CUSTOMIZEDSETTINGS);
                    fs.openSync(file.fsPath, 'r');

                    await vscode.workspace.openTextDocument(file).then((a: vscode.TextDocument) => {
                        vscode.window.showTextDocument(a, vscode.ViewColumn.One, true);
                    });
                    break;
                }
                case items[1]: {
                    //share public gist
                    await vscode.window.showInformationMessage("Sync : This will remove current GIST and upload settings on new public GIST. Do you want to continue ?", "Yes").then((resolve) => {
                        if (resolve == "Yes") {
                            localSetting.publicGist = true;
                            settingChanged = true;
                            setting.gist = "";
                            selectedItem = 1;
                        }
                    }, (reject) => {
                        return;
                    });
                    break;
                }
                case items[2]: {
                    //toggle force download
                    selectedItem = 2;
                    settingChanged = true;
                    if (setting.forceDownload) {
                        setting.forceDownload = false;
                    }
                    else {
                        setting.forceDownload = true;
                    }
                    break;
                }
                case items[3]: {
                    //toggle auto upload
                    selectedItem = 3;
                    settingChanged = true;
                    if (setting.autoUpload) {
                        setting.autoUpload = false;
                    }
                    else {
                        setting.autoUpload = true;
                    }
                    break;
                }
                case items[4]: {
                    //auto downlaod on startup
                    selectedItem = 4;
                    settingChanged = true;

                    if (!setting) {
                        vscode.commands.executeCommand('extension.HowSettings');
                        return;
                    }

                    if (!tokenAvailable || !gistAvailable) {
                        vscode.commands.executeCommand('extension.HowSettings');
                        return;
                    }
                    if (setting.autoDownload) {
                        setting.autoDownload = false;
                    }
                    else {
                        setting.autoDownload = true;
                    }
                    break;
                }
                case items[5]: {
                    //page summary toggle
                    selectedItem = 5;
                    settingChanged = true;

                    if (!tokenAvailable || !gistAvailable) {
                        vscode.commands.executeCommand('extension.HowSettings');
                        return;
                    }
                    if (setting.showSummary) {
                        setting.showSummary = false;
                    }
                    else {
                        setting.showSummary = true;
                    }
                    break;
                }

                case items[6]: {
                    //preserve
                    let options: vscode.InputBoxOptions = {
                        ignoreFocusOut: true,
                        placeHolder: "Enter any Key from settings.json to preserve.",
                        prompt: "Example : Write 'http.proxy' => store this computer proxy and overwrite it , if set empty it will remove proxy."

                    };
                    vscode.window.showInputBox(options).then(async (res) => {
                        //customSettings
                        //debugger;
                        if (res) {
                            let settingKey: string = res;
                            let a = vscode.workspace.getConfiguration();
                            let val: string = a.get<string>(settingKey);
                            customSettings.replaceCodeSettings[res] = val;
                            let done: boolean = await common.SetCustomSettings(customSettings);
                            if (done) {
                                if (val == "") {
                                    vscode.window.showInformationMessage("Sync : Done. " + res + " value will be removed from settings.json after downloading.");
                                }
                                else {
                                    vscode.window.showInformationMessage("Sync : Done. Extension will keep " + res + " : " + val + " in setting.json after downloading.");
                                }
                            }
                        }
                    });
                    break;
                }
                case items[7]: {
                    openurl("https://github.com/shanalikhan/code-settings-sync/issues/new");
                    break;
                }
                case items[8]: {
                    openurl("http://shanalikhan.github.io/2016/05/14/Visual-studio-code-sync-settings-release-notes.html");
                    break;
                }

                default: {
                    break;
                }


            }
        }, (reject) => {
Example #18
0
export function activate(context: ExtensionContext) {

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=6004'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		documentSelector: ['css', 'scss', 'less'],
		synchronize: {
			configurationSection: ['css', 'scss', 'less']
		},
		initializationOptions: {
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions);
	client.registerFeature(new ConfigurationFeature(client));

	let disposable = client.start();
	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);

	client.onReady().then(_ => {
		let colorRequestor = (uri: string) => {
			return client.sendRequest(ColorSymbolRequest.type, uri).then(ranges => ranges.map(client.protocol2CodeConverter.asRange));
		};
		let isDecoratorEnabled = (languageId: string) => {
			return workspace.getConfiguration().get<boolean>(languageId + '.colorDecorators.enable');
		};

		context.subscriptions.push(languages.registerColorProvider(['css', 'scss', 'less'], new ColorProvider(colorRequestor)));
		context.subscriptions.push(activateColorDecorations(colorRequestor, { css: true, scss: true, less: true }, isDecoratorEnabled));
	});

	let indentationRules = {
		increaseIndentPattern: /(^.*\{[^}]*$)/,
		decreaseIndentPattern: /^\s*\}/
	};

	languages.setLanguageConfiguration('css', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	languages.setLanguageConfiguration('less', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	languages.setLanguageConfiguration('scss', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g,
		indentationRules: indentationRules
	});

	commands.registerCommand('_css.applyCodeAction', applyCodeAction);

	function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) {
		let textEditor = window.activeTextEditor;
		if (textEditor && textEditor.document.uri.toString() === uri) {
			if (textEditor.document.version !== documentVersion) {
				window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`);
			}
			textEditor.edit(mutator => {
				for (let edit of edits) {
					mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText);
				}
			}).then(success => {
				if (!success) {
					window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.');
				}
			});
		}
	}
}
Example #19
0
'use strict';

import * as vscode from 'vscode';
import { runNgCommand } from './run'

export var ngtest = vscode.commands.registerCommand('extension.ngTest', () => {
    runNgCommand(['test'], false);
});
Example #20
0
'use strict';

import * as vscode from 'vscode';
import * as cp from 'child_process';

export var ngget = vscode.commands.registerCommand('extension.ngGet', () => {
    vscode.window.showInputBox({ placeHolder: 'name of the Parameter' }).then(
        (name) => {
            let child = cp.exec('ng get ' + name);
            child.stdout.on('data', (data) => {
                console.log('data', data);
                vscode.window.showInformationMessage(data);
            });
        }
    );
});
Example #21
0
 let registerCommand = (command, callback) => 
     context.subscriptions.push(vscode.commands.registerTextEditorCommand(command, (editor, edit) => 
         callback(client, editor)));
 next = applyEditPromise.then(_ => 
     {
         return vscode.commands.executeCommand("workbench.action.closeActiveEditor");
     });
Example #23
0
export function activate(context: vscode.ExtensionContext) {
	registerCompletionProviders(context, true);

	context.subscriptions.push(vscode.commands.registerCommand('emmet.wrapWithAbbreviation', (args) => {
		wrapWithAbbreviation(args);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.expandAbbreviation', (args) => {
		expandAbbreviation(args);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.removeTag', () => {
		return removeTag();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.updateTag', (inputTag) => {
		if (inputTag && typeof inputTag === 'string') {
			return updateTag(inputTag);
		}
		return vscode.window.showInputBox({ prompt: 'Enter Tag' }).then(tagName => {
			return updateTag(tagName);
		});
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.matchTag', () => {
		matchTag();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.balanceOut', () => {
		balanceOut();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.balanceIn', () => {
		balanceIn();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.splitJoinTag', () => {
		return splitJoinTag();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.mergeLines', () => {
		mergeLines();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.toggleComment', () => {
		toggleComment();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.nextEditPoint', () => {
		fetchEditPoint('next');
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.prevEditPoint', () => {
		fetchEditPoint('prev');
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.selectNextItem', () => {
		fetchSelectItem('next');
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.selectPrevItem', () => {
		fetchSelectItem('prev');
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.evaluateMathExpression', () => {
		evaluateMathExpression();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.incrementNumberByOneTenth', () => {
		return incrementDecrement(.1);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.incrementNumberByOne', () => {
		return incrementDecrement(1);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.incrementNumberByTen', () => {
		return incrementDecrement(10);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.decrementNumberByOneTenth', () => {
		return incrementDecrement(-0.1);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.decrementNumberByOne', () => {
		return incrementDecrement(-1);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.decrementNumberByTen', () => {
		return incrementDecrement(-10);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.updateImageSize', () => {
		return updateImageSize();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('emmet.reflectCSSValue', () => {
		return reflectCssValue();
	}));

	let currentExtensionsPath = undefined;
	let resolveUpdateExtensionsPath = () => {
		let extensionsPath = vscode.workspace.getConfiguration('emmet')['extensionsPath'];
		if (extensionsPath && !path.isAbsolute(extensionsPath)) {
			extensionsPath = path.join(vscode.workspace.rootPath, extensionsPath);
		}
		if (currentExtensionsPath !== extensionsPath) {
			currentExtensionsPath = extensionsPath;
			updateExtensionsPath(currentExtensionsPath);
		}
	};

	resolveUpdateExtensionsPath();

	context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(() => {
		registerCompletionProviders(context, false);
		resolveUpdateExtensionsPath();
	}));
}
 ? next.then(_ => 
        {
            return vscode.commands.executeCommand("vscode.open", fileToOpen);
        })
Example #25
0
 }).then(() => {
     originalContent = textDocument.getText();
     return vscode.commands.executeCommand('python.sortImports');
 }).then(edits => {
Example #26
0
export function activate(context: ExtensionContext) {

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=6044'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	let documentSelector = ['css', 'scss', 'less'];

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		documentSelector,
		synchronize: {
			configurationSection: ['css', 'scss', 'less', 'emmet']
		},
		initializationOptions: {
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions);
	client.registerProposedFeatures();

	let disposable = client.start();
	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);

	let indentationRules = {
		increaseIndentPattern: /(^.*\{[^}]*$)/,
		decreaseIndentPattern: /^\s*\}/
	};

	languages.setLanguageConfiguration('css', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	languages.setLanguageConfiguration('less', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	languages.setLanguageConfiguration('scss', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g,
		indentationRules: indentationRules
	});

	client.onReady().then(() => {
		context.subscriptions.push(initCompletionProvider());
		context.subscriptions.push(initFoldingProvider());
	});

	function initCompletionProvider(): Disposable {
		const regionCompletionRegExpr = /^(\s*)(\/(\*\s*(#\w*)?)?)?$/;

		return languages.registerCompletionItemProvider(documentSelector, {
			provideCompletionItems(doc, pos) {
				let lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos));
				let match = lineUntilPos.match(regionCompletionRegExpr);
				if (match) {
					let range = new Range(new Position(pos.line, match[1].length), pos);
					let beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet);
					beginProposal.range = range; TextEdit.replace(range, '/* #region */');
					beginProposal.insertText = new SnippetString('/* #region $1*/');
					beginProposal.documentation = localize('folding.start', 'Folding Region Start');
					beginProposal.filterText = match[2];
					beginProposal.sortText = 'za';
					let endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet);
					endProposal.range = range;
					endProposal.insertText = '/* #endregion */';
					endProposal.documentation = localize('folding.end', 'Folding Region End');
					endProposal.sortText = 'zb';
					endProposal.filterText = match[2];
					return [beginProposal, endProposal];
				}
				return null;
			}
		});
	}

	function initFoldingProvider(): Disposable {
		return languages.registerFoldingProvider(documentSelector, {
			provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken) {
				const param: FoldingRangeRequestParam = {
					textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
					maxRanges: context.maxRanges
				};
				return client.sendRequest(FoldingRangesRequest.type, param, token).then(res => {
					if (res && Array.isArray(res.ranges)) {
						return new FoldingRangeList(res.ranges.map(r => new FoldingRange(r.startLine, r.endLine, r.type)));
					}
					return null;
				}, error => {
					client.logFailedRequest(FoldingRangesRequest.type, error);
					return null;
				});
			}
		});
	}

	commands.registerCommand('_css.applyCodeAction', applyCodeAction);

	function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) {
		let textEditor = window.activeTextEditor;
		if (textEditor && textEditor.document.uri.toString() === uri) {
			if (textEditor.document.version !== documentVersion) {
				window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`);
			}
			textEditor.edit(mutator => {
				for (let edit of edits) {
					mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText);
				}
			}).then(success => {
				if (!success) {
					window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.');
				}
			});
		}
	}
}
Example #27
0
 .then(() => vscode.commands.executeCommand('workbench.files.action.closeAllFiles'))
Example #28
0
    public launchSimHost(): Q.Promise<void> {
        let provider = new SimHostContentProvider(this.simulateInfo.simHostUrl);
        this.registration = vscode.workspace.registerTextDocumentContentProvider(this.simulateProtocol, provider);

        return Q(vscode.commands.executeCommand("vscode.previewHtml", this.simulateUri, vscode.ViewColumn.Two).then(() => void 0));
    }
Example #29
0
function registerCommand(context: vscode.ExtensionContext, command: string, callback: (...args: any[]) => any) {
    let disposable = vscode.commands.registerCommand(command, callback);
    context.subscriptions.push(disposable);
}
 const closeAllEditors = () => {
     return commands.executeCommand('workbench.action.closeAllEditors');
 };