Go: vim autocomplete <ENTER> command don't works - go

autocomplete in vim doesn't work when I hit ENTER and the cursor go to the next line.
this is my .vimrc configuration: https://github.com/marcosvidolin/dotfiles/blob/master/.vimrc
Popup example:
Thanks

you need to add this to your .vimrc
inoremap <silent><expr> <cr> coc#pum#visible() ? coc#_select_confirm() : "\<C-g>u\<CR>"
source : Completion with sources

I am using vim and using Coc module for language server configuration.
Try to run these following steps:
Install gopls GO111MODULE=on go get golang.org/x/tools/gopls#latest
Open you vim and type :CocConfig and setting up go language configuration like the following bellow. (note: feel free to customize the value, especially in field rootPatterns)
{
"languageserver": {
"golang": {
"command": "gopls",
"rootPatterns": ["go.mod", "main.go", ".vim/", ".git/", ".hg/"],
"filetypes": ["go"],
"initializationOptions": {
"usePlaceholders": true
}
}
}
}
Save File and Reload your vim configuration

Related

How to set vscode format golang code on save?

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
},
}

vim filetype plugin conflict with session

Problem
When I restore from a session, It'll be impossible for to load my filetype plugin.
For example, I have an arduino filetype plugin of ~/.vim/ftplugin/arduino.vim, and the content is like this.
SyntasticToggleMode
call feedkeys("\<CR>")
nnoremap <leader>s :w<cr>:ArduinoVerify<cr>
nnoremap M :ArduinoUpload<cr>
I create an arduino file named test.ino to do some coding.
Every thing seems pretty smooth.
The filetype plugin is loaded properly.
Then I close vim with the following commands.
:mksession!
:wviminfo viminfo
:qa
Now there is a session file named Session.vim.
Then I open vim again, and it automatically load the session because I have something like this in my .vimrc.
filetype indent plugin on
if filereadable("Session.vim")
source Session.vim
endif
if filereadable("viminfo")
rviminfo viminfo
endif
Now something went wrong, the key mapping in my arduino filetype plugin is not working.
Also it prints some error message like this.
Error detected while processing /home/lotp/.vim/ftplugin/arduino.vim:
line 1:
E492: Not an editor command: SyntasticToggleMode"sketch_dec06a.ino" "sketch_dec06a.ino" 12L, 150C
E492: Not an editor command: SyntasticToggleMode
IndeedSyntasticToggleMode is a valid vim command belonging to a vim plugin named syntastic.
Question
Is there a solution to solve this problem?
By this I mean using the session and filetype plugin feather simultaneously.
A partial answer:
The plugins are not loaded directly in .vimrc if you use a plugin manager. Their paths are just appended to 'runtimepath', and they are sourced later in the initialisation process.
You can try to add (i.e. in .vimrc) your own custom path to runtimepath, AFTER the end of the plugin initialisation. (i.e., for Vundle, after this line: call vundle#end()) Then add a vim file in your_custom_path/plugin where you put your code to source the session file.
I didn't check all the infos I gave, so sorry for mistakes, but hope it gives you some ideas.
See :h startup, :h 'runtimepath'
Finally I work around this problem by using an vim plugin.
That's somekind of improved version of the built in vim session system
It's called vim-session

Sublime Text: "MarGo: Missing required environment variables: GOPATH"

In order to program with Golang in a more productive way, I just installed GoSublime for Sublime Text 2, as explained on their official GitHub repository:
Installation
Sublime Package Control allows you to easily install or remove
GoSublime (and many other ST2 packages) from within the editor. It
offers automatically updating packages as well so you no longer need
to keep track of changes in GoSublime.
Install Sublime Package Control (if you haven't done so already) from
http://wbond.net/sublime_packages/package_control .
Be sure to restart
ST2 to complete the installation.
Bring up the command palette (default ctrl+shift+p or cmd+shift+p) and
start typing Package Control: Install Package then press return or
click on that option to activate it. You will be presented with a new
Quick Panel with the list of available packages. Type GoSublime and
press return or on its entry to install GoSublime. If there is no
entry for GoSublime, you most likely already have it installed.
Now, whenever I launch Sublime Text, I have the following error message:
MarGo: Missing required environment variables: GOPATH
See the `Quirks` section of USAGE.md for info
And a usage.md file opens automatically, with the following content:
Usage
=====
Note
----
* Unless otherwise mentioned, `super` replaces `ctrl` in key bindings on OS X.
* A mention of a (GO)PATH variable uses a colon(`:`) as the separator.
This is the PATH separator on Linux and OS X, Windows uses a semi-colon(`;`)
Settings
--------
You may customize GoSublime's behaviour by (creating and) customizing the file `Packages/User/GoSublime.sublime-settings`. Default settings are documented in `Packages/GoSublime/GoSublime.sublime-settings`. **WARNING** Do not edit any package file outside of `Packages/User/`, including files inside `Packages/GoSublime/` unless you have a reason to. These files are subject to being overwritten on update of the respective package and/or Sublime Text itself. You may also inadvertently prevent the respective package from being able to update via git etc.
Quirks
------
This section assumes you know what `GOPATH` is and how to set it. If you don't, please see http://golang.org/doc/code.html
In some systems, environment variables are not passed around as expected.
The result of which is that some commands e.g `go build` don't work
as the command cannot be found or `GOPATH` is not set. To get around this
the simplest thing to do is to set these variables in the settings file.
See the documentation for the `env` and/or `shell` setting, both documented in the default
settings file `Packages/User/GoSublime.sublime-settings`
Code Completion
---------------
Completion can be accessed by typing the (default) key combination `CTRL+[SPACE]` inside a Golang file.
Key Bindings
------------
By default, a number of key bindings are provided. They can be viewed by opening the command palette
and typing `GoSublime:` or via the key binding `ctrl+dot`,`ctrl+dot` (or `super+dot`,`super+dot` on OS X).
Wherever I refer to a key binding with `ctrl+` it is by default defined as `super+` on OS X unless stated otherwise.
Useful Key Bindings
-------------------
Often when commenting out a line, the immediate action following this is to move the cursor to the next line either to continue working or comment out the following line.
With this key binding, you can have the line commented out and the cursor automatically moved to the next line.
{ "keys": ["ctrl+/"], "command": "gs_comment_forward", "context": [{ "key": "selector", "operator": "equal", "operand": "source.go" }] },
Package Imports
---------------
Pressing `ctrl+dot`,`ctrl+p` will open the package list from which you can quickly import or delete a package import.
The usage is the same for both operations. If the package is already imported then it will appear near the top
and be marked as a *delete* operation, so in effect it is a toggle. If you want to edit the alias of a package e.g
a database driver: first import the package as normal and then press `ctrl+dot`,`ctrl+i` to quickly jump
the last imported package. Once edited you can return to where you were by pressing `ctrl+dot`,`ctrl+[`
Building, Testing and the Go command
------------------------------------
GoSublime comes with partial command/shell integration `9o`. For more information about 9o, see Packages/GoSublime/9o.md
or from within Sublime Text press `ctrl+9` or `super+9` and type `help`.
To run package tests you have 3 options.
* press `ctrl+dot`,`ctrl+t` to open the testing quick panel. This offers basic/common options such
as running all benchmark functions or running a single test function.
* inside a `_test.go` file, press `ctrl+shift` and left-click on the name of a Test, Benchmark or Example
function e.g. `TestAbc` to execute that function only.
* if the above options are too minimalistic or you would otherwise like to call `go test` with your own options,
open 9o by pressing `ctrl+9` where you have access to the `go` command.
In the case of building a package, 9o provides a replay command (see 9o.md for details) that will execute
the command if the pkg is a command pkg (package main) or run all tests if it's a normal pkg.
The replay command is bound to `ctrl+dot`,`ctrl+r` for easy access.
GoSublime provides an override for the Sublime Text build-system via `ctrl+b`. In the menu `Tools > Build System` it's named `GoSublime`.
`ctrl+b` is automatically handled by Sublime Text, so if you have another `Go` build system chosen, `ctrl+b`
will execute that instead. To access the `GoSublime` build system directly press `ctrl+dot`,`ctrl+b`.
This build system simply opens 9o and expand the last command. i.e. executes the 9o command `^1`.
Per-project Settings & Project-based GOPATH
-------------------------------------------
If you have a settings object called `GoSublime` in your project settings its values will override those
inside the `GoSublime.sublime-settings` file. As a side-effect you may set a specific GOPATH for a single
project.
`my-project.sublime-project`
{
"settings": {
"GoSublime": {
"env": {
"GOPATH": "$HOME/my-project"
}
}
},
"folders": []
}
If the only setting you use this functionality to change is the GOPATH, then you may be able to find
success by adding the string `$GS_GOPATH` to your global `GOPATH` setting e.g.
{
"env": { "GOPATH": "$HOME/go:$GS_GOPATH" }
}
`GS_GOPATH` is a pseudo-environment-variable. It's changed to match a possible GOPATH based on:
* the current working directory, e.g. `~/go/src/pkg` then `$GS_GOPATH` will be `~/go/`
* or the path the current `.go` file (or last activated `.go` file if the current file is not `.go`) e.g. if your file path is `/tmp/go/src/hello/main.go` then it will be `/tmp/go`
If you would like to use `GS_GOPATH` exclusively, you may set the option `use_gs_gopath` to true.
This automatically changes `GOPATH` to the value of `$GS_GOPATH` if `$GS_GOPATH` is not empty.
This allows you to e.g. automatically adapt `GOPATH` to your current project rather than
reverting to your normal `GOPATH`.
Lint/Syntax Check
-----------------
The source is continuously scanned for syntax errors. GoSublime will try to catch some common errors, like
forgetting to call flag.Parse (if this causes false positives, please file a bug report).
Apart from the highlighting in the view using a dot icon in the gutter and usually underlining the
first character of an error region. You are given an entry in the status bar in the form: `GsLint (N)`
where `N` is the number of errors found in that file. You can show the list of errors and navigate to
them by pressing `ctrl+dot`,`ctrl+e`. Errors for the current line are shown in the status bar.
Fmt
---
By default `ctrl+s` and `ctrl+shift+s` are overridden to fmt the the file before saving it. You may also
fmt a file without saving it by pressing `ctrl+dot`,`ctrl+f`
Godoc/Goto Definition
---------------------
To show the source and associated comments(documentation) of a variable press `ctrl+dot`,`ctrl+h` or
using the mouse `ctrl+shift+right-click`. This will show an output panel that presents the full
definition of the variable or function under the (first) cursor along with its comments.
To goto the definition instead, press `ctrl+dot`,`ctrl+g` or alternatively using the mouse `ctrl+shift+left-click`.
Declarations/Code Outline?
--------------------------
A very minimal form of code outline is provided. You can press `ctrl+dot`,`ctrl+d` to list all the declarations
in the current file.
New File
--------
Pressing `ctrl+dot`,`ctrl+n` will create a new Go file with the package declaration filled out.
It will try to be intelligent about it, so if the current directory contains package `mypkg` it will use that as the package name.
Misc. Helper Commands
---------------------
The following commands can be assigned key bindings to further improve your editing experience.
* gs_fmt - this command runs `gofmt` on the current buffer. Also available via the key binding `ctrl+dot`,`ctrl+f`.
* gs_fmt_save, gs_fmt_prompt_save_as - these commands will run the `go_fmt` followed by `save` or `prompt_save_as` - these are bound to `ctrl+s` and `ctrl+shift+s` respectively, by default.
* gs_comment_forward - this command will activate the `ctrl+/` commenting and move the cursor to the next line, allowing you to comment/uncomment multiple lines in sequence without breaking to move the cursor. You can replace the default behaviour by overriding it in your user key bindings (Preferences > Key Bindings - User) with `{ "keys": ["ctrl+/"], "command": "gs_comment_forward", "context": [{ "key": "selector", "operator": "equal", "operand": "source.go" }] }`
Some people seem to have had the same issue:
Idiotproof instructions for MarGo: Missing required environment variables: GOPATH #310
How come USAGE.MD opens everytime I open Sublime? #601
gopath is set, but still show "MarGo: Missing required environment variables: GOPATH" #520
And the root cause of the problem could be that the GOPATH has not been defined.
Mine has been — export GOPATH=$HOME/code/go — and I am able to run Go (and .go files) on my computer.
Any idea of how this can be fixed?
You need to set gopath in the GoSublime settings.
Go to:
Preferences -> Package Settings -> GoSublime -> Settings – User
And paste that code there:
{
"env": {
"GOPATH": "$HOME/code/go"
}
}

Is there a JSX formatter for sublime text?

I'm using Sublime Text as a text editor.
There's a jsFormat for formatting javascript files but I can't find one for JSX.
How you guys deal with formatting JSX?
Update 4
Check prettier, not that configurable as esformatter, but currently used to format some big projects (like React itself)
Update 3
Check sublime jsfmt. If you add esformatter-jsx to the config and install the package inside the forlder for sublime-jsfmt. You will be able to format JSX files directly from Sublime. Here is a guide for that
Update 2
from the command line you can also use esbeautifier. It is a wrapper around esformatter that accept a list of globs to format
# install the dependencies globally
npm i -g esbeautifier
# beautify the files under src/ and specs/ both .js and .jsx
esbeautifier src/**/*.js* specs/**/*.js*
Update
So I ended up doing a plugin for esformatter to enable the formatting of JSX files:
https://www.npmjs.com/package/esformatter-jsx
Here is a live demo on requirebin
It should be somehow feasible to call esformatter from Sublime passing the current file as the argument. In any case to use it from the command line you can follow these instructions:
From the command line it can be used like this:
# install the dependencies globally
npm i -g esformatter esformatter-jsx
# call it (this will print to stdout)
esformatter --plugins=esformatter-jsx ./path/to/your/file
# to actually modify the file
esformatter --plugins=esformatter-jsx ./path/to/your/file > ./path/to/your/file
# to specify a config file (where you can also specify the plugins)
# check esformatter for more info about the configuration options
esformatter -c ./path/to/.esformatter ./path/to/your/file > ./path/to/your/file
==== old answer below ===
So if what you're looking is just to make your jsx files to be formatted while allowing the jsx syntax (basically beautify all the javascript syntax and ignore jsx tags, meaning leave them as is), this is what I'm doing using esformatter
// needed for grunt.file.expand
var grunt = require('grunt');
// use it with care, I haven't check if there
// isn't any side effect from using proxyquire to
// inject esprima-fb into the esformatter
// but this type of dependency replacement
// seems to be very fragile... if rocambole deps change
// this will certainly break, same is true for esformatter
// use it with care
var proxyquire = require('proxyquire');
var rocambole = proxyquire('rocambole', {
'esprima': require('esprima-fb')
});
var esformatter = proxyquire('esformatter', {
rocambole: rocambole
});
// path to your esformatter configuration
var cfg = grunt.file.readJSON('./esformatter.json');
// expand the files from the glob
var files = grunt.file.expand('./js/**/*.jsx');
// do the actual formatting
files.forEach(function (fIn) {
console.log('formatting', fIn);
var output = esformatter.format(grunt.file.read(fIn), cfg);
grunt.file.write(fIn, output);
});
I would actually like that esformatter use a version of rocambole that use esprima-fb instead of esprima, to avoid proxyquire.
There is a setting in the HTML-CSS-JS Prettify plugin that allows you to ignore xml syntax in the js/jsx file. That way it doesn't mess up the jsx code.
The setting is: "e4x": true in the "js" section of the settings file
Preferences > Package Settings > HTML\CSS\JS Prettify > Set Prettify Preferences
This does not work well if you have self closing tags eg. tags ending in />
You can install a JsPrettier package for Sublime 2 & 3. It's a fairly new JavaScript formatter (at the time of writing this: Feb-2017). It supports most of the latest developments like: ES2017, JSX, and Flow.
Quickstart
Install prettier globally using terminal: $ npm install -g prettier
In Sublime go to Tools -> Command Palette... -> Package Control: Install Package, type the word JsPrettier, then select it to complete the installation.
Format your file using context menu inside the editor or bind it to a keyboard shortcut: { "keys": ["super+b"], "command": "js_prettier" }
Links:
https://github.com/jonlabelle/SublimeJsPrettier
https://github.com/jlongster/prettier
To add to what #Shoobah said:
There is a setting in the HTML-CSS-JS Prettify plugin that allows you
to ignore xml syntax in the js/jsx file. That way it doesn't mess up
the jsx code. The setting is: "e4x": true in the "js" section of the
settings file
Go to: Preferences > Package Settings > HTML\CSS\JS Prettify > Set
Prettify Preferences
Go to "js" section:
Add "jsx" to the "allowed_file_extension", and then change "e4x" to "true"
the answer in the internet that always told you set 'e4x' to true,
but sometimes, we have to set option of 'format_on_save_extensions' then add 'jsx' in array
modify jsFormat.sublime-settings
{
"e4x": true,
"format_on_save": true,
"format_on_save_extensions": ["js", "json", "jsx"]
}
Using Sublime's Package Installer, install Babel. Then:
Open a .jsx file.
Select View from the menu,
Then Syntax -> Open all with current extension as... -> Babel -> JavaScript (Babel).
Not specifically for Sublime Text, but there is a beautifier in JavaScript for React JSX.
http://prettydiff.com/?m=beautify claims to support JSX at:
http://prettydiff.com/guide/react_jsx.xhtml

Enable Package Control to Sublimetext-2

My Question is regarding to sublime text2 editor. I need to install Package Controller on it. And i want to enable sublime-terminal. I am very confused. please help me to resolve it.
Thanks,
Shamith c
The Sublime Console is triggered with CTRL+`.
The instructions to install Package Control can be found here: http://wbond.net/sublime_packages/package_control/installation.
I've noticed that Ctrl+' does it sometimes (on Windows, at any rate)
The comibation ctrl+` never worked for me (Linux AND Windows :-/ ) So I pasted the following into the user specific key bindings:
[
{ "keys": ["ctrl+#"], "command": "show_panel", "args": {"panel": "console", "toggle": true} }
]
An alternative would be the menu: View >> Show console

Resources