How to define additional default tasks in VS Code? - visual-studio-code

I'm often using VS Code for Html/Css/Js development. I'm often using the following task (from other SO post) to open HTML page in browser:
{
"version": "0.1.0",
"command": "explorer",
"windows": {
"command": "explorer.exe"
},
"args": ["${file}"]
}
Is there a way to add this task as default one for all folders?

The short answer is "no".
The slightly longer answer is, "no, but they are thinking about ways this can be done" as demonstrated in this issue.
A workaround is to add a snippet that you can easily add to tasks.json in new projects. Go to File > Preferences > User Snippets > json and add something like this:
"Explorer Task": {
"prefix": "expTask",
"body": [
'{',
'\t"version": "0.1.0",',
'\t"command": "explorer",',
'\t"windows": {',
'\t\t"command": "explorer.exe"',
'\t},',
'\t"args": ["${file}"]',
'}'
],
"description": "Explorer task that I use so often"
},
Now when you go to tasks.json in any new project, you type expTask (or whatever you name it) and you can easily drop this in.

Related

How to add a new match/mapping for an existing language?

Thanks to an extension (Caddyfile Syntax, Caddyfile Support) I have highlighting for Caddyfile. Installing the extensions also mapped Caddyfile files with the relevant syntax highlighting rules.
I now would like to also have the same mapping for caddy.conf files.
According to the documentation, I should add an alias for caddy.conf so that it is handled the same way as Caddyfile.
The problem is that I do not know where to add this information in settings.json.
I had a look for anything "caddy" in defaultSettings.json but I do not see any structure that would match th eone in the documentation. Namely, I only see
// Configure settings to be overridden for the caddyfile language.
"[caddyfile]": {
"editor.insertSpaces": false,
"editor.formatOnSave": true
},
What I am looking for should more look like (according to the documentation above)
"languages": [{
"id": "java",
"extensions": [ ".java", ".jav" ],
"aliases": [ "Java", "java" ]
}]
So in practical terms - where in setting.json should I add the alias (or possibly a new mapping)?
Try adding this to your settings.json:
"files.associations": {
"*.conf": "caddyfile"
}
Alternatively, you can invoke the workbench.action.editor.changeLanguageMode command (Ctrl+K M by default, also works by clicking the language label in the status bar) and select the language you want. This is probably preferable if you might have files with the same extension, but different syntax.

VS Code keybinding: Accept quickfix codeAction

I'm trying to implement a small function by adding a shortcut for auto-correcting the last misspelled word, and this is what I get currently:
{
"key": "cmd+l",
"command": "extension.multiCommand.execute",
"args": {
"sequence": [
"cSpell.goToPreviousSpellingIssue",
"editor.action.quickFix",
"workbench.action.navigateToLastEditLocation",
"acceptSelectedSuggestionOnEnter",
"acceptSelectedSuggestion"
]
}
},
The idea is simple: jump back to the first misspelled word, and just select the first suggestion my spelling checker gives me, finally jump back to the previous edited position.
The code above is using multiCommand plug-in. Question is that I can't find any keystroke events to let me actually select the first suggestion my spelling checker gives me.
As in the config, I'm using cSpell for checking my spelling. To be specific, after I hit cmd+l, this is what I get:
snap shot
Clearly, I manage to move to the previous spelling issue, and evoke quickFix to let the suggestion widget pop up, and then move my cursor back to where I was initially. Hence, the only problem is what is the event to select that suggestion?
Really appreciate every helps, or if there is a better method to do the same thing please tell me! (I have tried every keyword I can think of, and there are not many references out there both in the official document from VS Code and google)
Because the quickfix menu is a different beast than a suggestions menu, the nextSuggestion or acceptSuggestion type of commands will not work in it. There is an open issue for navigation commands in the quickfix menu, see Missing keybinding for navigation in Quick Fix contextual menu
.
But you can get what you want another way. I found Keybinding for applying a specific code action and in it is a method for applying a quickfix with a command:
{
"key": "ctrl+shift+r ctrl+e",
"command": "editor.action.codeAction",
"args": {
"kind": "refactor.extract.function",
"apply": "first"
}
}
Valid values for "apply":
"first" — Always automatically the first available code action.
"ifSingle" — Default. Automatically the code action if only one is available. Otherwise, show the context menu.
"never" — Always show the code action context menu, even if only a single code action is available.
Adapting that for your use case, try this:
{
"key": "cmd+l", // "ctrl+l" for Windows
"command": "extension.multiCommand.execute",
"args": {
"sequence": [
"cSpell.goToPreviousSpellingIssue",
{
"command": "editor.action.codeAction",
"args": {
"kind": "quickfix",
"apply": "first" // you indicated you want the first choice
}
},
// "workbench.action.navigateToLastEditLocation"
"cursorUndo" // better than the above I believe
]
}
}

VSCode - Unable to write into user settings

when I try to change my vscode theme, I get a message saying "Unable to write into user settings" and to correct any errors. I checked my setting but didn't know what was wrong with it. Does anyone see any mistakes? I've pasted my settings code below.
"launch": {
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Local Node File",
"console": "integratedTerminal",
"program": "${file}"
},
{
"name": "Launch index.html",
"type": "chrome",
"request": "launch",
"file": "${workspaceFolder}/index.html"
},
{
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000,
"emmet.includeLanguages": { "erb": "html" }
},
"liveSassCompile.settings.formats": [
{
"format": "expanded",
"extensionName": ".css",
"savePath": "/css"
}
],
"liveSassCompile.settings.generateMap": false
]
}
IMO, the real problem is not how to fix the JSON, the real problem is the error msg "Unable to write into user settings". This tells me nothing useful; it makes the issue sound like a permissions problem, not a faulty comma or something in JSON.
I came here because I got the "Unable..." error in VSC, and had no idea how to fix it. The error msg unhelpfully suggests logging into the shared settings, which I unsuccessfully (apparently) attempted to do several times in different ways. That was not the problem at all. Once I fixed a stray comma in my JSON, as implied here, the error went away.
BTW, I'm not looking for upvotes, since this page already explains what the issue is. I'm venting my frustration with VSC...
open your settings.json, find the way line and annotation it
There's 2 problems going on.
1. How to identify JSON syntax errors
I get a message saying ... to correct any errors
...
Does anyone see any mistakes?
Any kind of json linter will tell you if your json is valid.
You could use VSCode itself, but since we're on the web, paste your json into https://jsonlint.com/ and right away it shows you there's an error:
Error: Parse error on line 1:
"launch": { "version": "0.2
--------^
Expecting 'EOF', '}', ',', ']', got ':'
It even has a little ascii art "arrow" pointing to the character that's the problem.
It's complaining because your json has a key ("launch") that's not inside an object ({...}). Compare your json to the launch configuration examples in VSCode Debugging docs, you'll notice that your "launch": is not in those examples. Just remove that so it starts from the first {, i.e.
When you fix that first problem, you hit your second problem:
2. "liveSassCompile.settings.formats" in wrong place
It's the same error as above: a json key not in an object.
Error: Parse error on line 23:
...le.settings.formats": [{ "format": "e
-----------------------^
Expecting 'EOF', '}', ',', ']', got ':'
In this case, it's because you pasted styling settings ("liveSassCompile.settings.formats": { ... }) into the launch configurations array.
You'll need to find the right place to paste those settings, but it's not inside that array — or anywhere in the launch config.
Check if running vs code as administrator solves your problem, the problem is from permissions that you have. ( only check for troubleshooting ).
Also, your JSON format must be valid for save.

contributes.menus: what are the possible variables for "when" action [duplicate]

VSCode 1.3 has added support for adding commands to context menus. Is there a way to identify whether a file or folder is clicked to open the explorer context menu?
"menus": {
"explorer/context": [
{
"when": "????",
"command": "extension.myCommand",
"group": "myGroup"
}
]
}
Also, is there a comprehensive(ish) list of expressions that might be checked in the when clause here?
You can use "when": "explorerResourceIsFolder".
I had to dig through the code to find it (I was actually writing up a response to say it didn't exist and enumerating the possible clause values when I saw it).
As of v1.10.1:
config.<any_config_path_here>
editorIsOpen
explorerResourceIsFolder
explorerViewletFocus
explorerViewletVisible
filesExplorerFocus
globalMessageVisible
inDebugMode
inQuickOpen
inZenMode
listFocus
openEditorsFocus
resource (Uri information: path, query, scheme, etc)
resourceFilename
resourceLangId
resourceScheme
scmProvider
textCompareEditorVisible
I've submitted an issue to improve the documentation for this.
Regarding obtaining a comprehensive list of context keys: in recent VSCode versions, there's a Developer: Inspect Context Keys command. After executing the command, it lets you pick a UI element:
After that, the dev console opens, and you can expand the logged object that contains a full list of context keys and their current values in this "scope":
https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts
is file: "when": "!explorerResourceIsFolder"
is dir: "when": "explorerResourceIsFolder"
You can get the list of language ids like this...
vscode.languages.getLanguages().then(l => console.log('languages', l));
I still haven't figured out how to determine if the item that was right clicked is a directory. If someone figures it out please let me know.
A write up about the feature is here. But basically:
the when is the same as the keybindings-when and can use the same keys
the when can use two new keys resourceScheme and resourceLangId which are available without an editor - think of the explorer context
menu
the when can be a boolean configuration value, e.g config.editor.lineNumbers
My menu:
"menus":{
"explorer/context": [
{
"when": "resourceLangId == sql",
"command": "extension.myCmd"
}
]

How do I add a snippet programmatically?

We have some custom snippets we provide as part of our VS Code extension via key bindings and a snippets json file:
{
"key": "ctrl+shift+i",
"mac": "cmd+shift+i",
"command": "editor.action.insertSnippet"
},
...
"snippets": [
{
"language": "xml",
"path": "./snippets/xml.json"
}
]
We would like a button to add one particular snippet to the editor at the current cursor position.
How do I programmatically I invoke the part of "editor.action.insertSnippet" after the user has selected the snippet?
I posted this issue on the vscode repo.
jrieken responded with the following reply:
The insertSnippet-command accepts an argument which is either the name of a snippet or a snippet itself. So, either { snippet: "console.log($1)$0"} for an inline snippet or { langId: "csharp", name: "myFavSnippet" } referencing an existing snippet.
You can run any registered command via vscode.commands.executeCommand. See also the vscode namespace API.