VS-Code command inputs using an (example) extension - visual-studio-code

In the VSCode documentation for variable substitution, it says there is now a way of using an extension to generate a list of options. Specifically, it gives an example and then says "It is assumed that some extension provides an extension.mochaSupport.testPicker command...".
I accept there is help provided in how to get started with extensions of various kinds, but I was wondering if anyone had indeed already written something equivalent to extension.mochaSupport.testPicker?
I appreciate it's probably trivial for someone not starting from scratch, but the graphic simulation on the first page implies someone has indeed already written such an extension (to generate the graphic), so my question is "does anyone know of an extension that is documented anywhere that complements this example to select an input from a list?"

I was faced with the same issue, so I wrote a small example extension. You can find the sample code on https://github.com/GianUlli/vscode-custom-command-input-example.
The basic idea is to register a command that returns a string. Following the official VS Code guide, you start by registering the command when the extension is activated in extension.ts in the activate function:
let disposable = vscode.commands.registerCommand(
'vscode-custom-command-input-example.pickTestCase',
async () => {
return pickTestCase().catch(console.error);
}
);
context.subscriptions.push(disposable);
pickTestCase is the custom function that extracts all test cases from the workspace using a glob search.
export async function pickTestCase() {
let workingFolder = getWorkspaceFolder();
return new Promise<string[]>((resolve, reject) => {
glob('*.json', { cwd: workingFolder }, (err, files) => {
if (err) {
return reject(err);
}
resolve(files);
});
})
.then((files) => {
if (files.length > 0) {
return window.showQuickPick(files);
} else {
window.showErrorMessage('Could not find any test cases.');
return undefined;
}
})
.then((testCase) => {
return testCase;
});
}
Do not forget to register the command in package.json:
"contributes": {
"commands": [
{
"command": "vscode-custom-command-input-example.pickTestCase",
"title": "Pick a test case"
}
]
}
With those pieces, the user is now able to put ${command:vscode-custom-command-input-example.pickTestCase} in his task definitions (.vscode/tasks.json) and launch configurations (.vscode/launch.json), for example in a build task:
{
"label": "Echo example",
"command": "echo",
"type": "shell",
"args": ["${command:vscode-custom-command-input-example.pickTestCase}"],
"presentation": {
"reveal": "always"
},
"group": "build"
}

Related

VSCode extension for quick semantic info

I am used to point the mouse and get information about certain references in Visual studio code.
Here one example, using Javascript, I point the mouse to a function reference and I get information about the function signature.
I would like to have something similar to other files.
e.g.
Take the following example, in a less popular language
module top #(
parameter NB=4
);
logic [NB /*I would like info here */ -1:0] b;
endmodule
How can I write an extension that when I point the mouse to the parameter it shows me the the declaration in a box, preferably with the same syntax highlight as it is shown in the editor.
Now there is a pull request with a sample to vscode-extension-samples.
Basically you have to write something like this
import * as vscode from 'vscode';
class SimpleHoverProvider implements vscode.HoverProvider {
public provideHover(
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken
): vscode.Hover | null {
return new vscode.Hover(`${location.line}: ${location.character}`);
// return null; if there is no information to show
}
}
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
console.log('Congratulations, hover-provider-sample extension is active!');
const hoverProvider = new SimpleHoverProvider();
vscode.languages.registerHoverProvider('text', hoverProvider);
}
And define languages and activation events on package.json
{
"activationEvents": [
"onLanguage:text",
"onLanguage:report"
],
"contributes": {
"languages": [
{
"id": "text",
"extensions": [
".txt"
]
},
{
"id": "report",
"extensions": [
".rpt"
]
}
]
},
}

Adding jar to vscode debug extension

We are having a runnable jar for the DAP(Debugger Adapater Protocol) of ABL language and we are planning to add a vscode extension for that ABL DAP.
Could you provide us some documentation or give us an idea about how to do it?
There are basically two approaches for making VS Code run your *.jar:
Declarative:
In the package.json of your extension, you can register your executable as part of the debuggers extension point. Here is the doc: https://code.visualstudio.com/api/extension-guides/debugger-extension#anatomy-of-the-package.json-of-a-debugger-extension.
And here is an example from the node.js debugger.
Basically the following attributes are available:
"runtime": "node",
"runtimeArgs": [ "--arguments_passed_to_runtime" ],
"program": "./dist/dap.js",
"args": [ "--arguments_passed_to_program" ],
The resulting command that VS Code will call is this:
node --arguments_passed_to_runtime ./dist/dap.js --arguments_passed_to_program
You do not have to make a distinction between runtime and program. You can use either "runtime" or "program" and leave out the other.
Non-declarative:
Alternatively you can use extension code to "calculate" the command that VS Code should execute when launching your Debug Adapter. See this API: https://github.com/microsoft/vscode/blob/4c3769071459718f89bd48fa3b6e806c83cf3336/src/vs/vscode.d.ts#L8797-L8816
Based on this API the following snippet shows how you could create a DebugAdapterDescriptor for your abl debugger:
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: ExtensionContext) {
vscode.debug.registerDebugAdapterDescriptorFactory('abl', {
createDebugAdapterDescriptor(session: DebugSession, executable: DebugAdapterExecutable | undefined): ProviderResult<DebugAdapterDescriptor> {
return new vscode.DebugAdapterExecutable(
"/usr/bin/java",
[
join(context.extensionPath, "bin", "abl.jar")
],
{
"cwd": "some current working directory path",
"env": {
"key": "value"
}
}
);
}
});
}

Asking while using SSML in Dialogflow webhook

I am trying to build an Actions on Google Agent via DialogFlow and keep getting errors when trying to ask the user a question while including ssml.
I have built the agent on DialogFlow, have logic implemented using the fulfillment webhook (implemented via the node module dialogflow-fulfillment) and have been able to test on DialogFlow successfully using the test console on the right side DialogFlow.
I therefore hooked up the DialogFlow Integrations to Google Assistant.
I first tried unsuccessfully:
const client = new WebhookClient({ req, res });
let qToSnd = 'Hi <break time=\"500ms\"/> Can I help you?';
let conv = client.conv();
conv.ask(qToSnd);
client.add(conv);
The above would work (not give errors) but would result in the question being asked while speaking out the <break> tag.
I have also tried:
conv.ask(
new Text({
text: _stripTags(qToSnd),
ssml: qToSnd
}));
However, when I test this using the Actions on Google simulator I get the error message:
[Agent] isn't responding right now. Try again soon.
Digging into the logs viewer shows the following error message:
MalformedResponse: ErrorId: ... Failed to parse Dialogflow response into AppResponse because of invalid platform response. : Could not find a RichResponse or SystemIntent in the platform response for agentId: ... and intentId: ...
My fulfillment API is returning:
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"text": "Hi - Can I help you?",
"ssml": "Hi <break time=\"500ms\"/> Can I help you?"
}
]
}
}
}
}
I will appreciate any pointers in the right direction.
Looking at the JSON snippet for a simple response in the documentation, you should wrap your item in a simpleResponse element. Additionally, the keys you are using for text and audio responses are incorrect, and should be textToSpeech and displayText.
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "Howdy, this is GeekNum. I can tell you fun facts about almost any number, my favorite is 42. What number do you have in mind?",
"displayText": "Howdy! I can tell you fun facts about almost any number. What do you have in mind?"
}
}
]
}
}
}
}
Inspired by #NickFelker's answer below and researching more into this topic, I was able to get the SSML working by making sure to add the <speak> tags. So this works:
const client = new WebhookClient({ req, res });
let qToSnd = 'Hi <break time=\"500ms\"/> Can I help you?';
let conv = client.conv();
conv.ask('<speak>' + qToSnd + '</speak>');
client.add(conv);
The fulfillment API returns:
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "<speak>Hi <break time=\"500ms\"/> Can I help you</speak>"
}
}
]
}
}
}
}

Extension API - Task Provider - Build Task example

I've built an extension for a programming language that I use and I've created hotkey shortcuts for calling the compiler executable with the currently open document's URI. I want to convert that to a build task in my extension. I have made a tasks.json file with a build task that works and catches errors and such, but it only works if I put it in the current workspace.
There are absolutely no examples of adding a build task anywhere and the API documentation for task providers is specifically for Ruby Rakefiles or something. I'm just wanting to make a shell executable build task with a problem matcher. Can anyone give me an example of that?
Here's a minimal TaskProvider implementation that simply runs echo "Hello World" in the shell:
'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
var type = "exampleProvider";
vscode.tasks.registerTaskProvider(type, {
provideTasks(token?: vscode.CancellationToken) {
var execution = new vscode.ShellExecution("echo \"Hello World\"");
var problemMatchers = ["$myProblemMatcher"];
return [
new vscode.Task({type: type}, vscode.TaskScope.Workspace,
"Build", "myExtension", execution, problemMatchers)
];
},
resolveTask(task: vscode.Task, token?: vscode.CancellationToken) {
return task;
}
});
}
The task definition (first argument for new Task()) needs to be contributed via package.json and can have additional properties if needed:
"contributes": {
"taskDefinitions": [
{
"type": "exampleProvider"
}
]
}
Extensions with a task provider should activate when the Tasks: Run Task command is executed:
"activationEvents": [
"onCommand:workbench.action.tasks.runTask"
]
And finally, the problem matcher(s) you want to reference need to be contributed in the package.json's contributes.problemMatchers section.

Is it possible to call commands between extensions in VSCode?

For example, there are two VSCode extensions:
extension1 has registered command exCommand1
extension2 has registered command exCommand2
According to documentation, a VSCode extension can call commands
(ref: https://code.visualstudio.com/docs/extensionAPI/vscode-api)
executeCommand<T>(command: string, ...rest: any[]): Thenable<T | undefined>
If API Doc is correct then
extension1 can call exCommand2 provided by extension2
extension2 can call exCommand1 provided by extension1
But, VSCode's extensions are lazily loaded, so how does one call a command from another extension that may not already be loaded?
I know this is an old post, if you still have the same requirement or for others googling, this is how I have done it.
var xmlExtension = vscode.extensions.getExtension( 'DotJoshJohnson.xml' );
// is the ext loaded and ready?
if( xmlExtension.isActive == false ){
xmlExtension.activate().then(
function(){
console.log( "Extension activated");
// comment next line out for release
findCommand();
vscode.commands.executeCommand("xmlTools.formatAsXml");
},
function(){
console.log( "Extension activation failed");
}
);
} else {
vscode.commands.executeCommand("xmlTools.formatAsXml");
}
// dev helper function to dump all the command identifiers to the console
// helps if you cannot find the command id on github.
var findCommand = function(){
vscode.commands.getCommands(true).then(
function(cmds){
console.log("fulfilled");
console.log(cmd);
},
function() {
console.log("failed");
console.log(arguments);
}
)
};