How to set vscode format golang code on save? - go

I'm using vscode with Go extensions to edit golang source code. Each time I want to format code, I have to press Ctrl-Shift-i on linux, Shift-Alt-F on Windows, or Ctrl-Shift-p and type format. Is it possible to set format on save, that is, when I press ctrl-s, it format the code automatically using go.fmt (or something alike)?

From my visual code version, i cannot use config go.formatOnSave": false.
Then I can turn them off in settings as below:
Build (Turn off using go.buildOnSave setting)
Lint (Turn off using go.lintOnSave setting)
Vet (Turn off using go.vetOnSave setting)
Format (Turn off by adding the below in your settings):
"[go]": {
"editor.formatOnSave": false
}

You should install this plugin: https://github.com/golang/vscode-go. One of the options is to set "auto format" on save: go.formatOnSave": false. It uses the Golang tooling for formatting.

For me, none of the answers worked. My Go version is 1.17.1, VSCode version is 1.60.1 and I'm using Linux Pop!_os.
After some digging online found this in the official VSCode documentation for Go. https://code.visualstudio.com/docs/languages/go#_formatting
My settings.json looks like this
"[go]": {
"editor.insertSpaces": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "golang.go"
},
Note: You need to install the required extensions for the go lang in VS code. Check the bottom left bar after opening a *.go file and you should see the go version. If you see an exclamation icon click on it and install the suggested extensions.

For me the followed settings worked. I disabled the annoying import refactoring.
"[go]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": false
},
}

Related

How can I configure the 'staticcheck' linter in Visual Studio Code?

I installed staticcheck, but it doesn't tell me any problems in my Visual Studio Code.
I configured my linter to use staticcheck and I looked everywhere on the Internet. It still doesn't work.
Here is a part of my settings.json file:
{
"go.formatTool": "goimports",
"go.useLanguageServer": true,
"go.lintTool": "staticcheck",
"go.lintFlags": [],
"go.testFlags": ["-v"],
"go.toolsManagement.autoUpdate": true,
"editor.codeActionsOnSave": { "source.fixAll.eslint": true }
}
I already tried to add "-check=all" on the go.lintFlags. I reloaded my Visual Studio Code, but it still doesn't work.
When I checked the official website they talk about staticcheck.conf, but I don't get it since there are multiple files named staticcheck.conf on my system.
You don't need "go.lintTool": "staticcheck", because, this is (staticcheck) default linting tool in vscode-go.
If you have language serve enabled, you need to turn staticcheck explicitly with
"gopls": { "ui.diagnostic.staticcheck": true }.
As alternative, you can set up golangci-lint as your linter and turn staticcheck in it.

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"

The option formatting.local in vscode-go its working?

I'm using vscode-go extension and reading the options I see than exist the formatting.local option but this option seems not be working Im trying to configure like this...
settings.json
"go.formatTool": "goimports",
"go.formatting.local": "github.com/mycompany/my_app"
What could be wrong?
"formatting.local" is a gopls setting. https://github.com/golang/vscode-go/blob/master/docs/settings.md#settings-for-gopls So, please add it inside the "gopls" block for now.
"gopls": {
"formatting.local": "github.com/mycompany/my_app"
}

How is VSCode finding this Go linting Problem and how do I ignore it?

I'm setting up linting with golangci-lint in my Go project. I have a file generated by go-bindata that VSCode is listing the following under the Problems tab:
assets/assets.go: redundant type from array, slice, or map composite literal (simplifycompositelit)
I can't seem to get rid of it. It's not a compiler error and I'll be re-running go-bindata from time to time so I don't want to make a habit of modifying generated code.
Right now, with the configuration below, I can't make VSCode stop reporting this error. If I run golangci-lint run ./... in the root of the workspace I get no output. I can provide my linting config if needed but VSCode seems to be running something else. How do I figure out what's reporting this error and how do I make it stop reporting anything for the file assets/assets.go in this one workspace?
Here's Go-related vscode settings:
{
"go.formatTool": "gofmt",
"go.lintTool": "golangci-lint",
"go.liveErrors": {
"enabled": true,
"delay": 500
},
"go.lintOnSave": "workspace",
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"go.useLanguageServer": true,
"go.languageServerExperimentalFeatures": {
"diagnostics": true,
"documentLink": true
},
}
Here's the line in question even with a nolint comment to show it's not behaving as expected. If it were golangci-lint outputting this, the nolint would prevent the warning from showing. I reloaded the window and closed/reopened vscode to be sure the change was noticed.
After reproducing locally, it seems this message comes from gopls, as disabling gopls silences the message. There are a couple of related complaints/issues on the Go issue tracker:
hide gofmt -s diagnostics (and others?) in generated files
should not issue lint-style warnings on generated code
Neither offers an actual solution.
However, this issue on the vscode-go repo, provides a work-around. In your VSCode config, add the gopls.analyses.simplifycompositelit key, with a value of false:
"gopls": {
"analyses": {
"simplifycompositelit": false
},
}
Of course, this disables it for all projects, not just generated files, but if you're also using golangci-lint, it can be configured to catch the same types of errors, and can be configured on a more granular basis, so that you won't miss the same class of errors in non-generated code.

vscode( vscode-ruby + rubocop ) how to auto correct on save?

Environments
vscode Version 1.19.1 (1.19.1)
rubocop (0.52.1)
Darwin mbp 16.7.0 Darwin Kernel Version 16.7.0: Wed Oct 4 00:17:00 PDT 2017; root:xnu-3789.71.6~1/RELEASE_X86_64 x86_64
ruby 2.3.5p376 (2017-09-14 revision 59905) [x86_64-darwin16]
followed https://github.com/rubyide/vscode-ruby#linters and installed all gems and edited the settings.json like this.
{
"ruby.rubocop.executePath": "/Users/ac/.rbenv/shims/",
"ruby.rubocop.onSave": true,
"ruby.lint": {
"ruby": {
"unicode": true //Runs ruby -wc -Ku
},
"reek": true,
"rubocop": {
"lint": true,
"rails": true
},
"fasterer": true,
"debride": {
"rails": true //Add some rails call conversions.
},
"ruby-lint": true
},
"ruby.locate": {
"include": "**/*.rb",
"exclude": "{**/#(test|spec|tmp|.*),**/#(test|spec|tmp|.*)/**,**/*_spec.rb}"
}
}
On vscode, code highlighting is working fine.
*just to note, you see the extensions installed, and warnings in the problem tab.
Question
I was under the inpression that vscode-ruby and rubocop would auto-correct indentations and cop rules on file save, but apparently it doesn't.
If I want it to format my code like prettier, how should I set this up?
Per this comment on the vscode-ruby-rubocop GitHub, you can use the following settings:
{
"editor.formatOnSave": true,
"editor.formatOnSaveTimeout": 5000,
"ruby.rubocop.executePath": "path/where/rubocop/is/located",
"ruby.format": "rubocop",
}
Just applied them to my user settings on my local box and it appears to work. VS Code was throwing an error for my ruby.rubocop.executePath setting saying it wasn't executable, and removing the line appears to not cause that error to show, and still formats my code accordingly. Setting a lower timeout (I tried 2500) also seems to break auto format on saving, so I'd suggest leaving it at 5000.
I've tried all the options other people shared and it fixed linking for me (so I would get warnings when my code wasn't formatted correctly) but it didn't fix indentation or other formatting on save.
What seemed to work for me is adding a default formatter option. If you look at the bottom right corner in vscode you should see a notification icon which might throw in a few warnings that can help with your config. For me it was adding:
"[ruby]": {
"editor.defaultFormatter": "misogi.ruby-rubocop"
}
Now, it's enough just adding these lines:
{
"ruby.rubocop.onSave": true,
"editor.formatOnSave": true,
}
I had this problem for a while and none of the other solutions worked for me.
According to a github comment, what solved was:
I Replace bin in the PATH with wrappers and solved the issue:
vscode setting:
ruby.rubocop.executePath": "/Users/USER_NAME/.rvm/gems/ruby-2.6.5/wrappers/
Note: Another useful thing you could check if none of the above worked for you is to check your home folder for a .rubocop.yml file (~/.rubocop.yml) and delete it so you only have your project's .rubocop.yml working on.
To make sure autocorrection works with ruby-rubocop add below settings
make sure "ruby.rubocop.executePath": "path/where/rubocop/is/located", is set to default
"ruby.rubocop.executePath": "",
Add the following to your json file in vscode
"editor.formatOnSave": true,
"editor.formatOnSaveTimeout": 5000,
"ruby.rubocop.executePath": "",
"ruby.format": "rubocop",
I struggled with the extension ruby-rubocop, last updated in Dec 2021. It seems it's still using the auto-correct command --autocorrect while Rubocop now uses --auto-correct. I switched to another extension, ruby-rubocop-revived, which fixed my auto-correct issue.
It also introduces the useServer option that speeds up the execution.
Here are the settings I used:
# .vscode/settings.json
"ruby.format": "rubocop",
"ruby.rubocop.onSave": true,
"ruby.rubocop.useServer": true,
"[ruby]": {
"editor.defaultFormatter": "rebornix.ruby"
},
This comment is now thankfully outdated
--
Unfortunately this cannot be done with the current rubocop extension. The primary use case is to lint your ruby and show visual cues in the IDE.
It is currently an open issue/feature request on github. View this issue to see progress until it is resolved.
https://github.com/misogi/vscode-ruby-rubocop/issues/49

Resources