How to run `go fmt` on save, in Visual Studio Code? - go

How to make Visual Studio Code (or Go Programming Language Extension) to run go fmt (or other tools/commands) on save? Even auto save?
Update:
It is working now perfectly inside VSCode, at this time; just need to add some config files inside .vscode directory (I use these).
Update 2019:
This question is old. The VSCode Go extension has all you need to develop in Go, now.
Last Update 2019
BTW It worth mentioning that right above the package declaration inside your test files appears a run package tests. If you click it, you can see your code coverage of your code. The covered and not-covered parts are highlighted in different colors.
Update 2020
And now, the Go Extension for VSCode, is under the supervision of Go Team! 🎉

Now, the feature has been implemented, you can enable format on save:
Open Settings (Ctrl + ,)
Search for editor.formatOnSave and set it to true
Your Go code will be formatted automatically on Ctrl + s

Its not possible at the moment but its being worked on https://github.com/Microsoft/vscode-go/issues/14

I'm not familiar with 'go fmt' specifically, but you can create a simple vscode extension to handle on save event and execute any arbitrary command passing the file path as an argument.
Here's a sample that just calls echo $filepath:
import * as vscode from 'vscode';
import {exec} from 'child_process';
export function activate(context: vscode.ExtensionContext) {
vscode.window.showInformationMessage('Run command on save enabled.');
var cmd = vscode.commands.registerCommand('extension.executeOnSave', () => {
var onSave = vscode.workspace.onDidSaveTextDocument((e: vscode.TextDocument) => {
// execute some child process on save
var child = exec('echo ' + e.fileName);
child.stdout.on('data', (data) => {
vscode.window.showInformationMessage(data);
});
});
context.subscriptions.push(onSave);
});
context.subscriptions.push(cmd);
}
And the package file:
{
"name": "Custom onSave",
"description": "Execute commands on save.",
"version": "0.0.1",
"publisher": "Emeraldwalk",
"engines": {
"vscode": "^0.10.1"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.executeOnSave"
],
"main": "./out/src/extension",
"contributes": {
"commands": [{
"command": "extension.executeOnSave",
"title": "Execute on Save"
}]
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./"
},
"devDependencies": {
"typescript": "^1.6.2",
"vscode": "0.10.x"
}
}
The extension is enabled via cmd+shift+p then typing "Execute on Save", but it could be reconfigured to start via another command including "*" which would cause it to load any time VSCode loads.
Once the extension is enabled, the event handler will fire whenever a file is saved (NOTE: this doesn't appear to work when file is first created or on Save as...)
This is just a minor modification of a yo code scaffolded extension as outlined here: https://code.visualstudio.com/docs/extensions/example-hello-world
Update
Here's a Visual Studio Code extension I wrote for running commands on file save. https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave.

I was using CTRL+S for saving the file manually (this is habitual for me). However, I had a different binding in VS Code that would start with CTRL+S (e.g. swagger extension has a chord where pressing CTRL+S CTRL+W would generate the swagger annotation). This resulted in VS Code waiting for me to press the second chord (CTRL+W) and as such it ignored the save part altogether. I reconfigured all the keybinding chords which had CTRL+S as the first chord to a different combination. After this, pressing CTRL+S formatted my file with gofmt properly.

Related

The Debugger in VS Code is starting but closing right after with no Terminal outputs

My Setup is the following:
I use a quite big python repository and code with VS Code with the following setup:
Version: 1.66.0 (user setup)
Commit: e18005f0f1b33c29e81d732535d8c0e47cafb0b5
Date: 2022-03-30T05:50:14.623Z
Electron: 17.2.0
Chromium: 98.0.4758.109
Node.js: 16.13.0
V8: 9.8.177.11-electron.0
OS: Windows_NT x64 10.0.19041
Since yesterday the debugger doesn't start anymore. When I start it with the buttons or with F5, the debug toolbar shows up for a second and then it vanishes again. The normal run works perfectly, as well as when I run my file from a terminal.
I didn't really change something that I can remember, only that VS Code did an automatic update on Monday evening.
There is no Terminal output that I can show, since it is not opening a Debugging Console.
I used the debugger always directly from the file that I needed to debug and didn't specify any launch.json files.
What I already tried, is as mentioned using not the Debugger, but the Run command and started the files from a terminal outside of VS Code. Then my code runs as intended. But since I need the debugger for my work, this is not a good solution.
I also went back a few commits to the last step where I know it was working, but this didn't change it at all.
I tried to debug a simple "hello World" python script but there I have the same problem.
I used the automatic add configuration from VS Code and it added the following launch.json file to the .vscode folder in the repo. Together with this file it added a configuration called "Python: Aktuelle Datei" (german for current file). This also didn't help when I'm trying to launch it with this configuration.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Aktuelle Datei",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true
}
]
}
Is there anyone who encountered a similar issue?

How to Change Visual Studio Code Terminal Default Permanently [duplicate]

When I woke up this morning and launched VSCode my default terminal on launch, and when running tasks is now powershell, instead of Git Bash. I am on windows. I have tried changing the settings.json to no avail. Is there something I'm missing?
{
"workbench.startupEditor": "newUntitledFile",
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"[javascript]": {
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
},
"aws.samcli.location": "C:\\Users\\king\\AppData\\Roaming\\npm\\sam.exe",
"typescript.updateImportsOnFileMove.enabled": "always",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"explorer.confirmDragAndDrop": false,
"diffEditor.maxComputationTime": 0,
"extensions.ignoreRecommendations": true,
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.renderControlCharacters": true,
"[jsonc]": {
"editor.quickSuggestions": {
"strings": true
},
"editor.suggest.insertMode": "replace"
},
"window.zoomLevel": 0,
"editor.accessibilitySupport": "off",
"workbench.editor.untitled.hint": "hidden",
"terminal.integrated.defaultProfile.windows": "Git Bash",
"terminal.external.windowsExec": "C:\\Program Files\\Git\\bin\\bash.exe",
"terminal.explorerKind": "external",
"terminal.integrated.automationShell.linux": ""
}
I found this related SO post making the default powershell, but I didn't see anything that was incorrect about my setting...especially because my goal is the opposite- to stop Powershell!
Update: Version v1.60.0 had a bug. Upgrade to v1.60.1 or higher for a fix.
The bug manifested in the following symptoms:
The Open in Integrated Terminal shortcut-menu command in the Explorer pane's shortcut always uses the built-in default shell (PowerShell on Windows), ignoring the configured one.
The same goes for running tasks (with or without a separate terminal.integrated.automationShell.* setting).
Also, if a given folder or workspace happened to have an integrated terminal open when quitting Visual Studio Code, the shell that is launched when the integrated terminal automatically reopens the next time is again the built-in default shell, not the configured one. By contrast, if reopening doesn't auto-open the integrated terminal, opening it manually does respect the configured default shell, and so does manually creating another shell instance later.
See GitHub issue #132150
The following information turned out to be unrelated to the bug, but is hopefully still useful general information about Visual Studio Code's recent change in how shells for the integrated terminal are configured:
Migrating from the legacy default shell settings to shell profiles:
Recently, the "terminal.integrated.shell.*" and "terminal.integrated.shellArgs.*" settings were deprecated and replaced with a more flexible model that allows defining multiple shells to select from, via so-called shell profiles, optionally defined in setting "terminal.integrated.profiles.*", with an associated mandatory "terminal.integrated.defaultProfile.*" setting referencing the name of the profile to use by default - which may be an explicitly defined custom profile or one of the built-in, platform-appropriate default profiles.
Note: * in the setting names above represents the appropriate platform identifier, namely windows, linux, or osx (macOS).
As of v1.60.1, if legacy "terminal.integrated.shell.*" settings are also present, the new settings take precedence (even though the tooltip when editing "terminal.integrated.shell.*" in settings.json suggests that this change is yet to come).
In the absence of both settings, Visual Studio Code's built-in default shell is used, which on Windows is PowerShell,[1] and on Unix-like platforms the user's default shell, as specified in the SHELL environment variable.
Recent Visual Studio Code versions, starting before v1.60 - seemingly as one-time opportunity - displayed a prompt offering to migrate the deprecated settings to the new ones.
Accepting the migration results in the following:
Creation of setting "terminal.integrated.shell.*" containing a custom shell profile derived from the values of legacy settings "terminal.integrated.shell.*" and, if present, "terminal.integrated.shellArgs.*"; that custom profile's name has the suffix (migrated)
Creation of setting terminal.integrated.defaultProfile.* whose value is the migrated profile's name, making it the default shell.
Removal of legacy settings "terminal.integrated.shell.*" and "terminal.integrated.shellArgs.*"
If you decline the migration, you can later effectively perform it by re-choosing the default shell, as described below.
Note: The new "terminal.integrated.defaultProfile.*" setting that is created in the process then effectively overrides the legacy "terminal.integrated.shell.*" and "terminal.integrated.shellArgs.*" settings, but the latter won't be removed automatically. To avoid confusion, it's best to remove them from settings.json manually.
Choose the default shell profile to use in order to (re)specify the default shell:
Click on the down-arrow part of the shell-selector icon () on the right side of the integrated terminal, select Select Default Profile, which presents a list of the defined profiles to select the default from - in the absence of explicitly defined profiles, standard profiles are offered (see below).
This translates into a terminal.integrated.defaultProfile.* setting in settings.json, whose value is the name of the chosen shell profile - which may be the name of a built-in profile or one of the ones explicitly defined in "terminal.integrated.profiles.*"
Note: This shell is by default also used for tasks (defined in tasks.json), but that can be overridden with a "terminal.integrated.automationShell.*" setting pointing to the executable of an alternative shell.
Optionally, in your settings.json file, you may create a platform-appropriate terminal.integrated.profiles.* setting with shell profiles of interest:
Note: Even if your settings.json contains no (platform-appropriate) "terminal.integrated.profiles.*" setting, Visual Studio code has built-in standard profiles it knows of and offers them for selection when choosing the default shell.
These standard profiles are a mix of shells that come with the host platform as well as some that Visual Studio detects dynamically on a given system, such as Git Bash on Windows.
To create the standard profiles explicitly, do the following:
Note: You may choose to do this in order to customize the standard profiles. However, if your intent is merely to add custom profiles - see this answer for an example - it isn't necessary to create the standard profiles inside the "terminal.integrated.profiles.*" setting, because Visual Studio Code knows about them even if not explicitly defined.
Via File > Preferences > Settings (Ctrl-,), search for profiles and click on Edit in settings.json below the platform-appropriate Terminal > Integrated > Profiles > * setting; this will open settings.json for editing, with the standard profiles added; simply saving the file is sufficient.
Note: If the "terminal.integrated.profiles.*" setting shown doesn't contain the expected, platform-appropriate standard profiles, a setting by that name may already be present; to force creation of the standard profiles, remove or comment out the existing setting and save the file, then try again.
On Windows, you'll end up with something like the following:
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
},
"Command Prompt": {
"path": [
"${env:windir}\\Sysnative\\cmd.exe",
"${env:windir}\\System32\\cmd.exe"
],
"args": [],
"icon": "terminal-cmd"
},
"Git Bash": {
"source": "Git Bash"
}
}
The answer you link to in your question, which provides an overview of the various types of shells used in Visual Studio Code, has been updated to reflect the information about the new shell profiles.
[1] Note: If a PowerShell (Core) v6+ installation is found, it takes precedence over the built-in Windows PowerShell version.
Edit:1
Note: Now this bug has been fixed by VSCode. Just update your VSCode to the latest version. (17-Sep-2021)
I have a temporary solution.
First paste this code in settings.json and save
"terminal.integrated.defaultProfile.windows": "Git Bash",
"terminal.integrated.profiles.windows": {
"C:\\Program Files\\Git\\bin\\bash.exe": {
"path": "",
"args": []
}
},
Before closing VSCode select Output instead of Terminal
Now you can open VSCode
After VSCode is loaded, you need to click on Terminal. After this you will now see bash.
Select output before whenever you close VSCode.
Reference: VSCode is suddenly defaulting to PowerShell for integrated terminal instead of $Bash in Windows
Note: This is not an solution. I shared this because maybe it can save you from getting disappointed.
This is my first post, if there is any mistake please let me know so that I can correct it.
You can always download and install previous releases from the official website https://code.visualstudio.com/updates/v1_59 (currently at the top).
As version 1.60 was bugged, v1.59 is a good candidate.
Disable automatic updates
Explained here.
Open User Settings File > Preferences > Settings.
Add "update.mode": "none" to your settings.
Install older version
Afterwards you can just overwrite current version with the installation of downloaded version.
Note: Wait for next version to fix it, so remember you had automatic update disabled!
I have same problem but I try run command prompt. I fix it by adding to ...\Code\User\settings.json
"terminal.integrated.automationShell.windows": "cmd.exe",
This could be related to issue 138999 which will add a mitigation/enhancement to VSCode 1.70 (July 2022) with PR 154290 and commit 91b82c0
increase barrier for available profiles to be ready
Wait up to 20 seconds for profiles to be ready so it's assured that we know the actual default terminal before launching the first terminal.
This isn't expected to ever take this long.
For VSCode with synchronized user settings, the profile might take more time than expected to fully load, hence the advantage of that workaround.
Simply replaced the CMD by Git Bash :-) in the settings.json
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
},
"Command Prompt": {
"path": [
//"${env:windir}\\Sysnative\\cmd.exe",
//"${env:windir}\\System32\\cmd.exe"
"C:\\PrivateProgramms\\Git\\bin\\bash.exe"
],
"args": [],
"icon": "terminal-cmd"
},
"Git Bash": {
"source": "Git Bash"
//"path": [ "C:\\PrivateProgramms\\Git\\bin\\bash.exe" ],
//"args": [],
//"icon": "terminal-cmd"
}
},
"terminal.integrated.defaultProfile.windows": "Command Prompt"

How can I stop PowerShell integrated terminal from appearing on VScode startup? [duplicate]

When I woke up this morning and launched VSCode my default terminal on launch, and when running tasks is now powershell, instead of Git Bash. I am on windows. I have tried changing the settings.json to no avail. Is there something I'm missing?
{
"workbench.startupEditor": "newUntitledFile",
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"[javascript]": {
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
},
"aws.samcli.location": "C:\\Users\\king\\AppData\\Roaming\\npm\\sam.exe",
"typescript.updateImportsOnFileMove.enabled": "always",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"editor.formatOnSave": true,
"editor.formatOnPaste": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"explorer.confirmDragAndDrop": false,
"diffEditor.maxComputationTime": 0,
"extensions.ignoreRecommendations": true,
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.renderControlCharacters": true,
"[jsonc]": {
"editor.quickSuggestions": {
"strings": true
},
"editor.suggest.insertMode": "replace"
},
"window.zoomLevel": 0,
"editor.accessibilitySupport": "off",
"workbench.editor.untitled.hint": "hidden",
"terminal.integrated.defaultProfile.windows": "Git Bash",
"terminal.external.windowsExec": "C:\\Program Files\\Git\\bin\\bash.exe",
"terminal.explorerKind": "external",
"terminal.integrated.automationShell.linux": ""
}
I found this related SO post making the default powershell, but I didn't see anything that was incorrect about my setting...especially because my goal is the opposite- to stop Powershell!
Update: Version v1.60.0 had a bug. Upgrade to v1.60.1 or higher for a fix.
The bug manifested in the following symptoms:
The Open in Integrated Terminal shortcut-menu command in the Explorer pane's shortcut always uses the built-in default shell (PowerShell on Windows), ignoring the configured one.
The same goes for running tasks (with or without a separate terminal.integrated.automationShell.* setting).
Also, if a given folder or workspace happened to have an integrated terminal open when quitting Visual Studio Code, the shell that is launched when the integrated terminal automatically reopens the next time is again the built-in default shell, not the configured one. By contrast, if reopening doesn't auto-open the integrated terminal, opening it manually does respect the configured default shell, and so does manually creating another shell instance later.
See GitHub issue #132150
The following information turned out to be unrelated to the bug, but is hopefully still useful general information about Visual Studio Code's recent change in how shells for the integrated terminal are configured:
Migrating from the legacy default shell settings to shell profiles:
Recently, the "terminal.integrated.shell.*" and "terminal.integrated.shellArgs.*" settings were deprecated and replaced with a more flexible model that allows defining multiple shells to select from, via so-called shell profiles, optionally defined in setting "terminal.integrated.profiles.*", with an associated mandatory "terminal.integrated.defaultProfile.*" setting referencing the name of the profile to use by default - which may be an explicitly defined custom profile or one of the built-in, platform-appropriate default profiles.
Note: * in the setting names above represents the appropriate platform identifier, namely windows, linux, or osx (macOS).
As of v1.60.1, if legacy "terminal.integrated.shell.*" settings are also present, the new settings take precedence (even though the tooltip when editing "terminal.integrated.shell.*" in settings.json suggests that this change is yet to come).
In the absence of both settings, Visual Studio Code's built-in default shell is used, which on Windows is PowerShell,[1] and on Unix-like platforms the user's default shell, as specified in the SHELL environment variable.
Recent Visual Studio Code versions, starting before v1.60 - seemingly as one-time opportunity - displayed a prompt offering to migrate the deprecated settings to the new ones.
Accepting the migration results in the following:
Creation of setting "terminal.integrated.shell.*" containing a custom shell profile derived from the values of legacy settings "terminal.integrated.shell.*" and, if present, "terminal.integrated.shellArgs.*"; that custom profile's name has the suffix (migrated)
Creation of setting terminal.integrated.defaultProfile.* whose value is the migrated profile's name, making it the default shell.
Removal of legacy settings "terminal.integrated.shell.*" and "terminal.integrated.shellArgs.*"
If you decline the migration, you can later effectively perform it by re-choosing the default shell, as described below.
Note: The new "terminal.integrated.defaultProfile.*" setting that is created in the process then effectively overrides the legacy "terminal.integrated.shell.*" and "terminal.integrated.shellArgs.*" settings, but the latter won't be removed automatically. To avoid confusion, it's best to remove them from settings.json manually.
Choose the default shell profile to use in order to (re)specify the default shell:
Click on the down-arrow part of the shell-selector icon () on the right side of the integrated terminal, select Select Default Profile, which presents a list of the defined profiles to select the default from - in the absence of explicitly defined profiles, standard profiles are offered (see below).
This translates into a terminal.integrated.defaultProfile.* setting in settings.json, whose value is the name of the chosen shell profile - which may be the name of a built-in profile or one of the ones explicitly defined in "terminal.integrated.profiles.*"
Note: This shell is by default also used for tasks (defined in tasks.json), but that can be overridden with a "terminal.integrated.automationShell.*" setting pointing to the executable of an alternative shell.
Optionally, in your settings.json file, you may create a platform-appropriate terminal.integrated.profiles.* setting with shell profiles of interest:
Note: Even if your settings.json contains no (platform-appropriate) "terminal.integrated.profiles.*" setting, Visual Studio code has built-in standard profiles it knows of and offers them for selection when choosing the default shell.
These standard profiles are a mix of shells that come with the host platform as well as some that Visual Studio detects dynamically on a given system, such as Git Bash on Windows.
To create the standard profiles explicitly, do the following:
Note: You may choose to do this in order to customize the standard profiles. However, if your intent is merely to add custom profiles - see this answer for an example - it isn't necessary to create the standard profiles inside the "terminal.integrated.profiles.*" setting, because Visual Studio Code knows about them even if not explicitly defined.
Via File > Preferences > Settings (Ctrl-,), search for profiles and click on Edit in settings.json below the platform-appropriate Terminal > Integrated > Profiles > * setting; this will open settings.json for editing, with the standard profiles added; simply saving the file is sufficient.
Note: If the "terminal.integrated.profiles.*" setting shown doesn't contain the expected, platform-appropriate standard profiles, a setting by that name may already be present; to force creation of the standard profiles, remove or comment out the existing setting and save the file, then try again.
On Windows, you'll end up with something like the following:
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
},
"Command Prompt": {
"path": [
"${env:windir}\\Sysnative\\cmd.exe",
"${env:windir}\\System32\\cmd.exe"
],
"args": [],
"icon": "terminal-cmd"
},
"Git Bash": {
"source": "Git Bash"
}
}
The answer you link to in your question, which provides an overview of the various types of shells used in Visual Studio Code, has been updated to reflect the information about the new shell profiles.
[1] Note: If a PowerShell (Core) v6+ installation is found, it takes precedence over the built-in Windows PowerShell version.
Edit:1
Note: Now this bug has been fixed by VSCode. Just update your VSCode to the latest version. (17-Sep-2021)
I have a temporary solution.
First paste this code in settings.json and save
"terminal.integrated.defaultProfile.windows": "Git Bash",
"terminal.integrated.profiles.windows": {
"C:\\Program Files\\Git\\bin\\bash.exe": {
"path": "",
"args": []
}
},
Before closing VSCode select Output instead of Terminal
Now you can open VSCode
After VSCode is loaded, you need to click on Terminal. After this you will now see bash.
Select output before whenever you close VSCode.
Reference: VSCode is suddenly defaulting to PowerShell for integrated terminal instead of $Bash in Windows
Note: This is not an solution. I shared this because maybe it can save you from getting disappointed.
This is my first post, if there is any mistake please let me know so that I can correct it.
You can always download and install previous releases from the official website https://code.visualstudio.com/updates/v1_59 (currently at the top).
As version 1.60 was bugged, v1.59 is a good candidate.
Disable automatic updates
Explained here.
Open User Settings File > Preferences > Settings.
Add "update.mode": "none" to your settings.
Install older version
Afterwards you can just overwrite current version with the installation of downloaded version.
Note: Wait for next version to fix it, so remember you had automatic update disabled!
I have same problem but I try run command prompt. I fix it by adding to ...\Code\User\settings.json
"terminal.integrated.automationShell.windows": "cmd.exe",
This could be related to issue 138999 which will add a mitigation/enhancement to VSCode 1.70 (July 2022) with PR 154290 and commit 91b82c0
increase barrier for available profiles to be ready
Wait up to 20 seconds for profiles to be ready so it's assured that we know the actual default terminal before launching the first terminal.
This isn't expected to ever take this long.
For VSCode with synchronized user settings, the profile might take more time than expected to fully load, hence the advantage of that workaround.
Simply replaced the CMD by Git Bash :-) in the settings.json
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell"
},
"Command Prompt": {
"path": [
//"${env:windir}\\Sysnative\\cmd.exe",
//"${env:windir}\\System32\\cmd.exe"
"C:\\PrivateProgramms\\Git\\bin\\bash.exe"
],
"args": [],
"icon": "terminal-cmd"
},
"Git Bash": {
"source": "Git Bash"
//"path": [ "C:\\PrivateProgramms\\Git\\bin\\bash.exe" ],
//"args": [],
//"icon": "terminal-cmd"
}
},
"terminal.integrated.defaultProfile.windows": "Command Prompt"

Small Basic & syntax highlighting in Visual Studio Code [duplicate]

Is there a way to extend the supported languages/grammars in Visual Studio Code?
I'd like to add a custom language syntax, but I've not been able to find any information on how language services are provided.
Can anybody point to any references or even examples of existing language implementations?
It's possible with the new version 0.9.0. There's an official documentation on how to add a custom language: https://github.com/microsoft/vscode-docs/blob/main/release-notes/v0_9_0.md
You need a .tmLanguage file for the language you want to add. You can find existing files e.g. on GitHub or you can define your own language file. Look here to get an idea of how to create one: http://manual.macromates.com/en/language_grammars
After finding a .tmLanguage file you have two ways to create an extension based on it.
Option 1: Using a Yeoman generator
Install node.js (if you haven't already done)
Install yo (if you haven't already done) by executing npm install -g yo
Install the Yo generator for code: npm install -g generator-code
Run yo code and select New language support
Follow the instructions (define the .tmLangauge file, define the plugin name, file extensions etc.)
The generator creates a directory for your extension with the name of the plugin in your current working directory.
Option 2: Create the directory on your own
Create a directory with the name of your plugin (only lowercase letters). Let's say we call it mylang.
Add a subfolder syntaxes and place the .tmlanguage file inside of it
Create a file package.json inside the root of the extension folder with content like this
{
"name": "mylang",
"version": "0.0.1",
"engines": {
"vscode": ">=0.9.0-pre.1"
},
"publisher": "me",
"contributes": {
"languages": [{
"id": "mylang",
"aliases": ["MyLang", "mylang"],
"extensions": [".mylang",".myl"]
}],
"grammars": [{
"language": "mylang",
"scopeName": "source.mylang",
"path": "./syntaxes/mylang.tmLanguage"
}]
}
}
Finally add your extension to Visual Studio Code
Copy the extension folder to the extension directory. This is:
on Windows %USERPROFILE%\.vscode\extensions
on Mac/Linux $HOME/.vscode/extensions
Restart Code. Now your extension will run automatically everytime you open a file with the specified file extension. You can see the name of the used plugin in the down right corner. You can change it by clicking on the name of the extension. If your extension is not the only one registered for a specific file extension then Code may chooses the wrong one.
To extend Wosi's .tmLanguage answer, using a .tmLanguage file is optional. Using a regular .json is a perfectly valid and—in my opinion—better readable alternative.
For an example, see VSCode_SQF: sqf.json
Inside the package.json, you would only need to change the path from ./syntaxes/mylang.tmLanguage to ./syntaxes/mylang.json.
Using reverse engineering you can add a new language to VSCode. You can take a look on how typescript is implemented as a JavaScript plugin and how it communicates with node.exe via pipe. But it's a hard thing since it's coming all without documentation
I'll provide a really short documentation here:
You can define a new plugin in the plugins folder C:\Users\USER\AppData\Local\Code\app-0.3.0\resources\app\plugins.
Copy the typescript plugin folder and rename mentioned file extensions and language names in all files to your new language, so that your new plugin is going to be used when a .mylang file is opened.
In typescriptServiceClient.js you see that a child process is being forked and that its stdout is coupled to a new WireProtocol.Reader. Bind your own mylanguage.exe (you'll probably need to write that exe on your own). VSCode asks that binary to get more language specific information.
In typescriptMain.js you find the feature registration for the language. Delete every call to monaco.Modes.XXXXXXSupport.register except monaco.Modes.DeclarationSupport.register.
Now open a directory in VSCode that contains .mylang files and open one of them via CTRL+P + FileName. Right click on an identifier and select Go to Definition. VSCode sends now a request like this via StdIn to your exe
{"seq":1,"type":"request","command":"definition","arguments":{"file":"d:/Projects/MyProj/Source/MyFile.mylang","line":45,"offset":9}}
VSCode expects an answer like this:
Content-Length: 251
[LINE BREAK]
{ "seq" : 1, "type" : "response", "command" : "definition", "request_seq" : 1, "success" : true, "body" : [{ "file" : "d:/Projects/MyProj/Source/MyOtherFile.mylang", "start" : { "line" : 125, "offset" : 3 }, "end" : { "line" : 145, "offset" : 11} }] }
If everything works VSCode will open MyOtherFile.mylang and set the cursor to line 124 in column 3.
Try it on your own ;-)
Simplest recipe IMHO as of 2021 Q2:
Follow Option 2 in Wosi's answer. You only need two files to get started. Just create the folder structure directly in your extensions directory.
Set "path": "./syntaxes/your_language.plist" in package.json
Use IRO to build your regexes.
Make sure that in the "Scope Information" screen, anything to do with Textmate is green. Don't worry about the other editors.
Save the contents of the "Textmate" tab into the path above, i.e., .syntaxes/your_language.plist
Reload VSCode
That's it. I also save the IRO (left pane) text into my own project.
You can read the source code of the built-in language extensions online:
https://github.com/microsoft/vscode/tree/main/extensions
You can pick an extension that is close to your language's syntax and change it as you wish. (e.g. you can do some modifications to the JavaScript extension and rebrand it for use with jQuery!)
It is important to note that this would be too much work if you choose a language that is so different from your desired language! If you didn't manage to find a language that is similar to your desired language, you may want to create a whole new extension from the ground up - https://stackoverflow.com/a/32996211/14467698 -.

cannot open source file "begin_code.h" (dependency of "SDL2/SDL.h")

When attempting to setup SDL2 with VS Code in Ubuntu 20.01 LTM I get the following VS Code error:
cannot open source file "begin_code.h" (dependency of "SDL2/SDL.h")
Any tips?
Just add "/usr/include/SDL2/" to your c_cpp_properties.json like so:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/SDL2/"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu18",
"cppStandard": "gnu++14",
"intelliSenseMode": "gcc-x64"
}
],
"version": 4
}
in case you don't have the "c_cpp_properties.json" file in your
folder.
Different answer than above, but I believe might be a better approach.
to create the c_cpp_properties.json on your workspace
do the following:
ctrl + shift + p (opens the command palette)
search for "C/C++: Edit Configurations (JSON)" and click on it
"c_cpp_properties.json" file will be created on your workspace
add "/usr/include/SDL2/" to your "c_cpp_properties.json" like
https://stackoverflow.com/a/64187964/8540466
reload C/C++ IntelliSense extension.
I'm assuming you already have the extension
"C/C++ IntelliSense, debugging, and code browsing"
installed on your vscode.
After these steps this problem was fixed for me.
If you, like me, don't have the c_cpp_properties.json file in your project, you can solve it by adding the following line to your settings.json (in VSCode, hit Ctrl+Shift+P and search for Open settings (JSON)):
{
// ...
"C_Cpp.default.includePath": ["/usr/include/SDL2", "${default}"],
//...
}

Resources