Giter Site home page Giter Site logo

vs-script-commands's Introduction

[DEPRECATED] vs-script-commands

Adds additional commands to Visual Studio Code (VS Code) that uses scripts (JavaScript) for execution.


The extension is now marked as DEPRECATED ... it is RECOMMENDED to use vscode-powertools by e.GO Digital.

If you have suggestions and other kind of issues for that new extension, feel free to open an issue here.


Table of contents

  1. Install
  2. How to use
  3. Documentation

Install []

Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter:

ext install vs-script-commands

Or search for things like vs-script-commands in your editor:

Screenshot VSCode Extension search

How to use []

Changes []

  • if you come from version 1.x, you should take a look at the wiki first ... if you have problems, you can open an issue and/or download a version 1.x branch from here

Settings []

Open (or create) your settings.json in your .vscode subfolder of your workspace.

Add a script.commands section:

{
    "script.commands": {
    }
}
Name Description
autoSelectWorkspace Select the workspace by active text editor automatically or not. Default (false)
commands One or more commands to register.
disableNewVersionPopups Disables the display of popups that reports for a new version of that extension. Default (false)
globals Global data available for ALL commands defined by that extension.
quick Settings for quick execution feature.
showOutput Open output on startup or not. Default (true)
showInternalVSCommands Show internal Visual Studio Code commands in GUI or not. Default (false)

Commands []

Define one or more command, by defining its id and the script file, which should be executed:

{
    "script.commands": {
        "commands": [
            {
                "id": "mkloubert.mycommand",
                "script": "./my-command.js"
            }
        ]
    }
}

The ./my-command.js must have a public / exported execute() function:

exports.execute = function (args) {
    // access VSCode API (s. https://code.visualstudio.com/Docs/extensionAPI/vscode-api)
    var vscode = require('vscode');

    // access any NodeJS API provided by VSCode (s. https://nodejs.org/api/)
    var path = require('path');

    // import an own module
    var myModule = require('./myModule');

    // use the functions and classes provided by this extension
    // s. https://mkloubert.github.io/vs-script-commands/modules/_helpers_.html
    var helpers = args.require('./helpers');

    // access a module that is part of the extentsion
    // s. https://github.com/mkloubert/vs-script-commands/blob/master/package.json
    var moment = args.require('moment');

    // access the global data from the settings
    var globals = args.globals;

    // access the data of the entry from the settings
    var opts = args.options;

    // share / store data (while current session)...
    // ... for this script
    args.commandState = new Date();
    // ... with other scripts
    args.globalState['myCommand'] = new Date();

    // access permanent data storages
    // s. https://github.com/Microsoft/vscode/blob/master/src/vs/workbench/common/memento.ts
    var myAppWideValue = args.extension.globalState.get('myAppValue');  // app wide
    args.extension.workspaceState.update('myWorkspaceValue', 'New workspace wide value');  // workspace wide

    // share data between two executions
    var prevVal = args.previousValue;  // data from the previous execution
    args.nextValue = 'This is a value only for the next execution';  // data for the next execution

    // registers for a one-time event
    args.events.once('myCommandEvent', function(v) {
        // 'v' should be 'William Henry Gates'
        // if upcoming 'args.events.emit()' is called
        args.log("From 'myCommandEvent': " + v);
    });

    // emit 'myCommandEvent' event (s. above)
    args.events.emit('myCommandEvent', 'William Henry Gates');

    // logs a message to output window / channel
    args.log('A log message');

    // write to output channel of that extension
    // s. https://code.visualstudio.com/Docs/extensionAPI/vscode-api#OutputChannel
    args.outputChannel.appendLine('A message for the output channel.');


    var scriptFile = path.basename(__filename);

    // open HTML document in new tab (for reports e.g.)
    args.openHtml('<html>Hello from my extension: ' + scriptFile + '</html>', 'My HTML document').then(function() {
        // HTML opened
    }, function(err) {
        // opening HTML document failed
    });

    // deploys 'index.html' to 'My SFTP server'
    // s. https://github.com/mkloubert/vs-deploy
    args.deploy(['./index.html'], ['My SFTP server']).then(function() {
        // file deployed
    }, function(err) {
        // deployment failed
    });

    vscode.window.showInformationMessage('Hello from my extension: ' + scriptFile);

    // you also can return a Promise
    // if your command is executed async
    return 666;
}

The args parameter uses the ScriptCommandExecutorArguments interface.

You can now execute the command by anything that uses the Visual Studio Code API:

var vscode = require('vscode');

vscode.commands.executeCommand('mkloubert.mycommand').then(function(result) {
    // if we look at the upper example:
    // this should be: 666
}, function(err) {
    // handle an error
});

A command entry provides the following properties:

Name Description
arguments One or more arguments for the callbacks.
askForArgument Defines if the GUI asks for an argument when invoke manually or not. Default (false)
async Invokes command async or not. Default (true)
button Settings for optional button in the status bar.
cached Cache script or not. Default (false)
commandState The initial value for commandState property. Default {}
continueOnError Continue on error or cancel. Default (true)
description The description for the command.
displayName The custom display name.
id The ID of the command.
onActiveEditorChanged Is invoked when the active text editor has been changed. Default (false)
onClose Executes the command on VSCode closes or not. Default (false)
onConfigChanged Is invoked after settings.json has been changed. Default (false)
onEditorChanged Is invoked after a text editor changed. Default (false)
onFileChanged Is invoked when a file has been changed. Default (false)
onFileClosed Is invoked when a file has been closed. Default (false)
onFileDeleted Is invoked when a file has been deleted. Default (false)
onFileOpened Is invoked when a file has been opened. Default (false)
onNewFile Is invoked when a file has been created. Default (false)
onSaved Is invoked when a file has been saved. Default (false)
onStartup Executes the command on startup or not. Default (false)
onWillSave Is invoked when a file is going to be saved. Default (false)
options Additional data for the execution.
script The path to the script to execute. IF YOU USE A RELATIVE PATH: The path is relative to your workspace.
sortOrder The sort order (for the GUI). Default 0
suppressArguments Supress own arguments of the extension or not. Default (false)

Key bindinds []

After defining one or more commands, you can open your keybindings.json file and set shortcuts for them, by selecting File > Preferences > Keyboard Shortcuts (Code > Preferences > Keyboard Shortcuts on Mac) in your editor:

Demo Key bindinds

Invoke manually []

Press F1 to open the list of commands and enter one of the following commands:

Demo Invoke manually

Name Description Command
Script commands: Execute command Executes a command defined by that extension. extension.scriptCommands.execute
Script commands: Execute VSCode command Executes another command that is available in VSCode. extension.scriptCommands.executeVSCode
Script commands: Quick execution Executes a JavaScript expression quickly. extension.scriptCommands.quickExecution
Script commands: Select workspace Changes the current workspace, s. Multi-root Workspaces. extension.scriptCommands.selectWorkspace

Status bar buttons []

You can activate buttons for your commands in the status bar, by defining the button property:

{
    "script.commands": {
        "commands": [
            {
                "id": "mkloubert.mycommand",
                "script": "./my-command.js",
                
                "button": {
                    "text": "My command",
                    "tooltip": "This is a tooltip for my command"
                }
            }
        ]
    }
}

Demo Status bar buttons

Name Description
color The custom (text) color for the button.
isRight Set button on the right side or not. Default (false)
priority The custom priority.
show Show button on startup or not. Default (true)
text The caption for the button.
tooltip The tooltip for the button.

Quick execution []

Press F1 to open the list of commands and select Script commands: Quick execution to execute any JavaScript expression (execute $help to open a help tab which lists all available features, like functions and variables):

Demo Quick execution

You can define custom settings for the feature:

{
    "script.commands": {
        "quick": {
            "noResultInfo": false,
            "showResultInTab": true,
            
            "state": {
                "MK": 23979,
                "TM": "1979-09-05 23:09:19.079"
            }
        }
    }
}
Name Description
cwd The initial current directory for the executions.
disableHexView Do not show binary data in 'hex view'. Default: (false)
noResultInfo Do not show results of executions. Default: (false)
saveResultsToState Save all results to $state variable or not. Default: (false)
showResultInTab Show results in tab instead of a popup or not. Default: (false)
saveToGlobalHistory Save entries, that are stored automatically, to global history instead to workspace history. Default: (false)
saveToHistory Automatically save entries to history or not. Default: (false)
state The initial state value.

Documentation []

The full API documentation can be found here.

vs-script-commands's People

Contributors

mkloubert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vs-script-commands's Issues

How to install global commands

The extension docs state that you should define script commands in the workspace settings.json. But I have some commands I want to be available always (i.e., in every workspace, and even when I open a standalone file with no workspace. How do I do that? Also script files seem to be located relative to the workspace - so where would I put script files for global commands (I'd rather not hard code paths, as I'd prefer my settings to be portable).

Improvement: script autoloading

This is a great extension just for making VSCode more extensible and customizable. Would it be possible to auto-load scripts on startup? In addition to getting a list of scripts, also auto-load any scripts in a given directory.

An example of what that might look like in settings.json:

{
    "script.commands.autoloadPaths": [
         "/home/me/.vscode/scripts"
    ]
}

A sane default set of paths would be in $HOME/.vscode/scripts and ${workspaceFolder}/.vscode/scripts. Those paths would satisfy me, and it would not even have to be customizable to start.

Basically you would list all files in each directory configured to be autoloaded and look for *.js files. Then you would load the file with require() a little earlier so that you could access a command export that mirrors the one in the settings.

Short example:

// Inside ${workspaceFolder}/.vscode/scripts/example.js
exports.command = {
    id: "my.command.id",
    displayName: "Example script command"
};

exports.execute = function (args) {
    args.log("Hello world!");
};

Organizing scripts in this way would be much easier to manage, and could be supported simultaneously with the existing method.

How to get focused file when calling a custom command

Hi, everything is in the title.

I want to make a custom script that will call php-cs-fixer via Node API child-process, but I can't find how to get the current file focused in VSCode.

Do you have any examples about this use case ?

Thanks a lot

Script Commands stop working when there is no workspace

This seems to have caused #5 .
When vscode is opened without a workspace the follow error message appears in the output channel of Script Commands:

[ERROR] ScriptCommandController.reloadConfiguration(1): TypeError: Path must be a string. Received undefined

And this should be caused by the following code in the extension:
in reloadConfiguration() of src/controller.ts:

const SETTINGS_FILE = Path.join(
    sc_workspace.getRootPath(),
    './.vscode/settings.json',
);

and in getRootPath() of src/workspace.ts:

if ('undefined' !== typeof workspace_root) {
    return Path.resolve(workspace_root);
} //doesn't return anything when workspace_root is undefined

Thus the TypeError occurs and Script Commands stop working.

Get selected folders/files in Explorer?

Is it possible to get the currently selected files/folders in Explorer, from a command?

I saw this, but it seems to require a menu contribution, which I don't think this extension uses.

I know you can get the open editor with vscode.window.activeTextEditor, but that doesn't help if you want to run an action on a folder.

Stopped working

Not sure if this has something to do with latest VC Code releases, but the commands don't get registered. A short-cut I defined previously to call a custom command results now in:

command my_command not found

Using vs-script-commands to fold all code in all editors

Hello Marcel,

I love the work you do, vscode-remote-workspace and vs-scripts-commands. I use vscode-remote-workspace, all the time very helpful!!!!

I was wondering if I could ask a question. I realize this issue tracker is not the most correct way to ask you a question. Let me know if there is a better way for asking questions that are not issues.

I have written a stack overflow post on my question.

Any thoughts would be great!

Have a nice day,
Kyle Swanson

Thanks again for vscode-remote-workspace!!!!!

Can't import an own module

    // import an own module
    var myModule = require('./myModule');

I have replace.js & import replace-davinci.

It should output replace davinci in replace-davinci.js but can't find anything.
If i want to use replaceDavinci.replace(text, fileName);, it occur replace is undefined.

I love this extension and Google it for a long time. Hope you can help me to fixed it. Thanks a lot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.