Repository: sublimelsp/LSP

Issue:
gopls: Format on save is disabled globally for the duration of the session after syntax error
# System information
macOS Catalina 10.15.5 (19F101)
Sublime Text Dev Channel, Build 4074

# Install
Package Control

# Reproduction
Assuming the LSP configuration
```json
{
    "lsp_format_on_save": true,
    "lsp_code_actions_on_save": {
        "source.fixAll": true,
        "source.organizeImports": true
    },
    "show_symbol_action_links": true,
    "only_show_lsp_completions": true,
    "clients": {
        "gopls": {
            "enabled": true,
            "settings": {
                "gopls.usePlaceholders": true,
                "gopls.analyses": {
                  "fillreturns": true,
                  "nonewvars": true,
                  "undeclaredname": true,
                  "unusedparams": true
                },
                "gopls.completeUnimported": true,
                "gopls.staticcheck": true
            }
        }
    }
}
```

Then, given the snippet (note the superfluous indentation, and missing `.`)
```go
package main

import "fmt"

func main() {



                fmt Println("Hello, world!")
}
```

Save the snippet as `main.go`, open `main.go` in `subl` and save (to run the format on save).

Then replace
```go
fmt Println("Hello, world!")
```
with
```go
fmt.Println("Hello, world!")
```

From this point, saving the file does not do any formatting. However, it does still do imports, if
```go
import "fmt"
```
is removed.

# Logs
```
Traceback (most recent call last):
  File "/Applications/Sublime Text.app/Contents/MacOS/Lib/python33/sublime_plugin.py", line 795, in on_activated_async
    run_view_callbacks('on_activated_async', view_id)
  File "/Applications/Sublime Text.app/Contents/MacOS/Lib/python33/sublime_plugin.py", line 622, in run_view_callbacks
    callback(*args)
  File "/Applications/Sublime Text.app/Contents/MacOS/Lib/python33/sublime_plugin.py", line 167, in exception_handler
    return event_handler(*args)
  File "/Users/thomas/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/documents.py", line 52, in on_activated_async
    self.manager.activate_view(self.view)
  File "/Users/thomas/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/windows.py", line 419, in activate_view
    self._initialize_on_open(view)
  File "/Users/thomas/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/windows.py", line 461, in _initialize_on_open
    startable_configs = needed_configs(self._configs.match_view(view))  # type: ignore
  File "/Users/thomas/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/windows.py", line 441, in needed_configs
    for c in configs:
  File "/Users/thomas/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/configurations.py", line 47, in match_view
    configs = self.match_document(view2scope(view))
  File "/Users/thomas/Library/Application Support/Sublime Text 3/Installed Packages/LSP.sublime-package/plugin/core/types.py", line 115, in view2scope
    return view.scope_name(0).split()[0]
IndexError: list index out of range
```


Discussion:
I think the log is unrelated as it shows an error that triggered on file activation, not at saving.

Can you try reproducing again and check when does that error appear exactly?

BTW. I can't reproduce that failure to format breaking anything. It does trigger error response from gopls but if I add the dot then it formats just fine.

Can you check your version of gopls? Here I have:
```
> gopls version
golang.org/x/tools/gopls 0.4.1
    golang.org/x/tools/gopls@v0.4.1 h1:0e3BPxGV4B3cd0zdMuccwW72SgmHp92lAjOyxX/ScAw=
```
I had a feeling that might be the case - it's the only output I get, and it doesn't always show up. Otherwise it's quiet, even with all the lsp log options enabled.

```sh
$ gopls version
version master, built in $GOPATH mode

➜  tools git:(master) git rev-parse HEAD
20370b0cb4b25d20a35ee592d915c5e0640a0258
```
>  Otherwise it's quiet, even with all the lsp log options enabled.

You can run "LSP: Toggle Log Panel" from the command palette to see the barrage of RPC messages.
Could you try latest released gopls version to make sure we are on the same page?
Thanks for the tip @rwols! When I save with invalid code the panel closes (crashes?). Here's some logs you might find interesting
```
--> gopls textDocument/codeAction(61): {'context': {'diagnostics': [], 'only': ['source.fixAll', 'source.organizeImports']}, 'textDocument': {'uri': 'file:///Users/thomas/a/main.go'}, 'range': {'end': {'character': 0, 'line': 282}, 'start': {'character': 0, 'line': 0}}}
:: <~~ gopls 61: {'message': 'invalid response payload', 'code': -32602}
:: ==> gopls textDocument/formatting(62): {'options': {'insertFinalNewline': True, 'insertSpaces': False, 'trimTrailingWhitespace': True, 'trimFinalNewlines': True, 'tabSize': 8}, 'textDocument': {'uri': 'file:///Users/thomas/a/main.go'}}
::  -> gopls textDocument/didSave: {'textDocument': {'uri': 'file:///Users/thomas/a/main.go'}}
```

```
<<< gopls 84: None
```

I'll go ahead and try with 0.4.1   @rchl 
@rchl Same behaviour with 0.4.1

Given this snippet
```go
package main

type    b    bo ol

func main() {



}
```

Like before, create a new file `main.go`, and open in `subl`. Save it, and then fix it by replacing `bo ol` with `bool`. Once saved again, it should not fix formatting.

Let me know if this helps!
That "invalid response payload" is our own created error response. It's created here: https://github.com/sublimelsp/LSP/blob/85ea2570993526794bb3fd05a1662364d0974980/plugin/core/rpc.py#L310-L311

This means the payload from gopls either has both `"result"` and `"error"` keys, or neither. Unfortunately it's not printed to the console at the moment, we should probably do that.

The JSON-RPC spec states that `"result"` XOR `"error"` is present in the JSON payload https://www.jsonrpc.org/specification

We should verify whether this is really the case.
Great! It's still a little suspect that all consequent formatting then fails. As before, it's not like it's _completely_ broken. Imports still work, and it can be manually formatted, but format on save is permanently broken globally.
I'd say it's a bug in gopls. It seems like it has some internal state that breaks after you try to format invalid code.
> and it can be manually formatted, but format on save is permanently broken globally.

I've missed that part. That sounds like an LSP bug then.
Someone should still verify my claims before pointing to gopls :)
Well, regardless of what gopls sends, it shouldn't break subsequent formatting attempts after the syntax was made valid. :)

Resolving patch:
diff --git a/plugin/core/rpc.py b/plugin/core/rpc.py
--- a/plugin/core/rpc.py
+++ b/plugin/core/rpc.py
@@ -106,6 +106,7 @@ def flush_error(self) -> Dict[str, Any]:
 
     def reset(self) -> None:
         self.__payload = None
+        self.__error = None
         self.__request_id = -1
         self.__response_id = -1
 


Test patch: