We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
'lsp_symbol_definition' via keybinding  using `ccls' as client.
While I was trying to bind the 'lsp_symbol_definition'-command to my custom keys, I had so suffer from a `... type str does not support Buffer API´.
On revisiting the relevant file ("plugin/goto.py") I found the TODO comment which mentions the future implementation of DocumentLink-support.

By dumping the response-payload of the 'lsp_symbol_definition'-command I found out that the received payload has different keys as beeing parsed by the 'handle_response()' function.
See here:
```
[{targetUri: file:///usr/include/bash/builtins/bashgetopt.h, targetRange: {end: {line: 38, character: 30}, start: {line:
38, character: 0}}, targetSelectionRange: {end: {line: 38, character: 26}, start: {line: 38, character: 11}}}]
```

### Solution

So I added the following snippet to provide the right parsing method in case of this setup/scenario:

```python
            if 'targetUri' in location:
                file_path = uri_to_filename(location['targetUri'])
                start = Point.from_lsp(location['targetRange']['start'])
            else:
                file_path = uri_to_filename(location["uri"])
                start = Point.from_lsp(location['range']['start'])
```

By adding this the desired function of my keybinding worked.

I just wanted to share this in the hope it might be useful.
Best regards !


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `plugin/goto.py`
Content:
```
1 import sublime
2 
3 from .core.registry import LspTextCommand
4 from .core.protocol import Request, Point
5 from .core.documents import get_document_position, get_position, is_at_word
6 from .core.url import uri_to_filename
7 from .core.logging import debug
8 from Default.history_list import get_jump_history_for_view
9 
10 try:
11     from typing import List, Dict, Optional, Any
12     assert List and Dict and Optional and Any
13 except ImportError:
14     pass
15 
16 
17 class LspGotoCommand(LspTextCommand):
18 
19     def __init__(self, view: sublime.View) -> None:
20         super().__init__(view)
21         self.goto_kind = "definition"
22 
23     def is_enabled(self, event: 'Optional[dict]' = None) -> bool:
24         if self.has_client_with_capability(self.goto_kind + "Provider"):
25             return is_at_word(self.view, event)
26         return False
27 
28     def run(self, edit: sublime.Edit, event: 'Optional[dict]' = None) -> None:
29         client = self.client_with_capability(self.goto_kind + "Provider")
30         if client:
31             pos = get_position(self.view, event)
32             document_position = get_document_position(self.view, pos)
33             if document_position:
34                 request_type = getattr(Request, self.goto_kind)
35                 if not request_type:
36                     debug("unrecognized goto kind:", self.goto_kind)
37                     return
38                 request = request_type(document_position)
39                 client.send_request(
40                     request, lambda response: self.handle_response(response, pos))
41 
42     def handle_response(self, response: 'Optional[Any]', position: int) -> None:
43         window = sublime.active_window()
44         if response:
45             # Save to jump back history.
46             get_jump_history_for_view(self.view).push_selection(self.view)
47             # TODO: DocumentLink support.
48             location = response if isinstance(response, dict) else response[0]
49             file_path = uri_to_filename(location.get("uri"))
50             start = Point.from_lsp(location['range']['start'])
51             file_location = "{}:{}:{}".format(file_path, start.row + 1, start.col + 1)
52             debug("opening location", location)
53             window.open_file(file_location, sublime.ENCODED_POSITION)
54             # TODO: can add region here.
55         else:
56             sublime.status_message("Empty response from language server, "
57                                    "reverting to Sublime's built-in Goto Definition")
58             window.run_command("goto_definition")
59 
60     def want_event(self) -> bool:
61         return True
62 
63 
64 class LspSymbolDefinitionCommand(LspGotoCommand):
65 
66     def __init__(self, view: sublime.View) -> None:
67         super().__init__(view)
68         self.goto_kind = "definition"
69 
70 
71 class LspSymbolTypeDefinitionCommand(LspGotoCommand):
72 
73     def __init__(self, view: sublime.View) -> None:
74         super().__init__(view)
75         self.goto_kind = "typeDefinition"
76 
77 
78 class LspSymbolDeclarationCommand(LspGotoCommand):
79 
80     def __init__(self, view: sublime.View) -> None:
81         super().__init__(view)
82         self.goto_kind = "declaration"
83 
84 
85 class LspSymbolImplementationCommand(LspGotoCommand):
86 
87     def __init__(self, view: sublime.View) -> None:
88         super().__init__(view)
89         self.goto_kind = "implementation"
90
```

Path: `plugin/core/sessions.py`
Content:
```
1 from .types import ClientConfig, ClientStates, Settings
2 from .protocol import Request
3 from .transports import start_tcp_transport, start_tcp_listener, TCPTransport, Transport
4 from .rpc import Client, attach_stdio_client
5 from .process import start_server
6 from .url import filename_to_uri
7 from .logging import debug
8 import os
9 from .protocol import completion_item_kinds, symbol_kinds
10 try:
11     from typing import Callable, Dict, Any, Optional
12     assert Callable and Dict and Any and Optional and Transport
13 except ImportError:
14     pass
15 
16 
17 def create_session(config: ClientConfig,
18                    project_path: str,
19                    env: dict,
20                    settings: Settings,
21                    on_pre_initialize: 'Optional[Callable[[Session], None]]' = None,
22                    on_post_initialize: 'Optional[Callable[[Session], None]]' = None,
23                    on_post_exit: 'Optional[Callable[[str], None]]' = None,
24                    bootstrap_client: 'Optional[Any]' = None) -> 'Optional[Session]':
25 
26     def with_client(client: Client) -> 'Session':
27         return Session(
28             config=config,
29             project_path=project_path,
30             client=client,
31             on_pre_initialize=on_pre_initialize,
32             on_post_initialize=on_post_initialize,
33             on_post_exit=on_post_exit)
34 
35     session = None
36     if config.binary_args:
37         tcp_port = config.tcp_port
38         server_args = config.binary_args
39 
40         if config.tcp_mode == "host":
41             socket = start_tcp_listener(tcp_port or 0)
42             tcp_port = socket.getsockname()[1]
43             server_args = list(s.replace("{port}", str(tcp_port)) for s in config.binary_args)
44 
45         process = start_server(server_args, project_path, env, settings.log_stderr)
46         if process:
47             if config.tcp_mode == "host":
48                 client_socket, address = socket.accept()
49                 transport = TCPTransport(client_socket)  # type: Transport
50                 session = with_client(Client(transport, settings))
51             elif tcp_port:
52                 transport = start_tcp_transport(tcp_port, config.tcp_host)
53                 if transport:
54                     session = with_client(Client(transport, settings))
55                 else:
56                     # try to terminate the process
57                     try:
58                         process.terminate()
59                     except Exception:
60                         pass
61             else:
62                 session = with_client(attach_stdio_client(process, settings))
63     else:
64         if config.tcp_port:
65             transport = start_tcp_transport(config.tcp_port)
66             session = with_client(Client(transport, settings))
67         elif bootstrap_client:
68             session = with_client(bootstrap_client)
69         else:
70             debug("No way to start session")
71     return session
72 
73 
74 def get_initialize_params(project_path: str, config: ClientConfig) -> dict:
75     initializeParams = {
76         "processId": os.getpid(),
77         "rootUri": filename_to_uri(project_path),
78         "rootPath": project_path,
79         "capabilities": {
80             "textDocument": {
81                 "synchronization": {
82                     "didSave": True,
83                     "willSaveWaitUntil": True
84                 },
85                 "hover": {
86                     "contentFormat": ["markdown", "plaintext"]
87                 },
88                 "completion": {
89                     "completionItem": {
90                         "snippetSupport": True
91                     },
92                     "completionItemKind": {
93                         "valueSet": completion_item_kinds
94                     }
95                 },
96                 "signatureHelp": {
97                     "signatureInformation": {
98                         "documentationFormat": ["markdown", "plaintext"],
99                         "parameterInformation": {
100                             "labelOffsetSupport": True
101                         }
102                     }
103                 },
104                 "references": {},
105                 "documentHighlight": {},
106                 "documentSymbol": {
107                     "symbolKind": {
108                         "valueSet": symbol_kinds
109                     }
110                 },
111                 "formatting": {},
112                 "rangeFormatting": {},
113                 "declaration": {},
114                 "definition": {},
115                 "typeDefinition": {},
116                 "implementation": {},
117                 "codeAction": {
118                     "codeActionLiteralSupport": {
119                         "codeActionKind": {
120                             "valueSet": []
121                         }
122                     }
123                 },
124                 "rename": {},
125                 "colorProvider": {},
126                 "publishDiagnostics": {
127                     "relatedInformation": True
128                 }
129             },
130             "workspace": {
131                 "applyEdit": True,
132                 "didChangeConfiguration": {},
133                 "executeCommand": {},
134                 "symbol": {
135                     "symbolKind": {
136                         "valueSet": symbol_kinds
137                     }
138                 }
139             }
140         }
141     }
142     if config.init_options:
143         initializeParams['initializationOptions'] = config.init_options
144 
145     return initializeParams
146 
147 
148 class Session(object):
149     def __init__(self,
150                  config: ClientConfig,
151                  project_path: str,
152                  client: Client,
153                  on_pre_initialize: 'Optional[Callable[[Session], None]]' = None,
154                  on_post_initialize: 'Optional[Callable[[Session], None]]' = None,
155                  on_post_exit: 'Optional[Callable[[str], None]]' = None) -> None:
156         self.config = config
157         self.state = ClientStates.STARTING
158         self._on_post_initialize = on_post_initialize
159         self._on_post_exit = on_post_exit
160         self.capabilities = dict()  # type: Dict[str, Any]
161         self.client = client
162         if on_pre_initialize:
163             on_pre_initialize(self)
164         self._initialize(project_path)
165 
166     def has_capability(self, capability: str) -> bool:
167         return capability in self.capabilities and self.capabilities[capability] is not False
168 
169     def get_capability(self, capability: str) -> 'Optional[Any]':
170         return self.capabilities.get(capability)
171 
172     def _initialize(self, project_path: str) -> None:
173         params = get_initialize_params(project_path, self.config)
174         self.client.send_request(
175             Request.initialize(params),
176             lambda result: self._handle_initialize_result(result))
177 
178     def _handle_initialize_result(self, result: 'Any') -> None:
179         self.state = ClientStates.READY
180         self.capabilities = result.get('capabilities', dict())
181         if self._on_post_initialize:
182             self._on_post_initialize(self)
183 
184     def end(self) -> None:
185         self.state = ClientStates.STOPPING
186         self.client.send_request(
187             Request.shutdown(),
188             lambda result: self._handle_shutdown_result(),
189             lambda error: self._handle_shutdown_result())
190 
191     def _handle_shutdown_result(self) -> None:
192         self.client.exit()
193         self.client = None  # type: ignore
194         self.capabilities = dict()
195         if self._on_post_exit:
196             self._on_post_exit(self.config.name)
197
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/plugin/core/sessions.py b/plugin/core/sessions.py
--- a/plugin/core/sessions.py
+++ b/plugin/core/sessions.py
@@ -110,10 +110,10 @@
                 },
                 "formatting": {},
                 "rangeFormatting": {},
-                "declaration": {},
-                "definition": {},
-                "typeDefinition": {},
-                "implementation": {},
+                "declaration": {"linkSupport": True},
+                "definition": {"linkSupport": True},
+                "typeDefinition": {"linkSupport": True},
+                "implementation": {"linkSupport": True},
                 "codeAction": {
                     "codeActionLiteralSupport": {
                         "codeActionKind": {
diff --git a/plugin/goto.py b/plugin/goto.py
--- a/plugin/goto.py
+++ b/plugin/goto.py
@@ -46,8 +46,13 @@
             get_jump_history_for_view(self.view).push_selection(self.view)
             # TODO: DocumentLink support.
             location = response if isinstance(response, dict) else response[0]
-            file_path = uri_to_filename(location.get("uri"))
-            start = Point.from_lsp(location['range']['start'])
+            if "targetUri" in location:
+                # TODO: Do something clever with originSelectionRange and targetRange.
+                file_path = uri_to_filename(location["targetUri"])
+                start = Point.from_lsp(location["targetSelectionRange"]["start"])
+            else:
+                file_path = uri_to_filename(location["uri"])
+                start = Point.from_lsp(location["range"]["start"])
             file_location = "{}:{}:{}".format(file_path, start.row + 1, start.col + 1)
             debug("opening location", location)
             window.open_file(file_location, sublime.ENCODED_POSITION)

{"golden_diff": "diff --git a/plugin/core/sessions.py b/plugin/core/sessions.py\n--- a/plugin/core/sessions.py\n+++ b/plugin/core/sessions.py\n@@ -110,10 +110,10 @@\n                 },\n                 \"formatting\": {},\n                 \"rangeFormatting\": {},\n-                \"declaration\": {},\n-                \"definition\": {},\n-                \"typeDefinition\": {},\n-                \"implementation\": {},\n+                \"declaration\": {\"linkSupport\": True},\n+                \"definition\": {\"linkSupport\": True},\n+                \"typeDefinition\": {\"linkSupport\": True},\n+                \"implementation\": {\"linkSupport\": True},\n                 \"codeAction\": {\n                     \"codeActionLiteralSupport\": {\n                         \"codeActionKind\": {\ndiff --git a/plugin/goto.py b/plugin/goto.py\n--- a/plugin/goto.py\n+++ b/plugin/goto.py\n@@ -46,8 +46,13 @@\n             get_jump_history_for_view(self.view).push_selection(self.view)\n             # TODO: DocumentLink support.\n             location = response if isinstance(response, dict) else response[0]\n-            file_path = uri_to_filename(location.get(\"uri\"))\n-            start = Point.from_lsp(location['range']['start'])\n+            if \"targetUri\" in location:\n+                # TODO: Do something clever with originSelectionRange and targetRange.\n+                file_path = uri_to_filename(location[\"targetUri\"])\n+                start = Point.from_lsp(location[\"targetSelectionRange\"][\"start\"])\n+            else:\n+                file_path = uri_to_filename(location[\"uri\"])\n+                start = Point.from_lsp(location[\"range\"][\"start\"])\n             file_location = \"{}:{}:{}\".format(file_path, start.row + 1, start.col + 1)\n             debug(\"opening location\", location)\n             window.open_file(file_location, sublime.ENCODED_POSITION)\n", "issue": "'lsp_symbol_definition' via keybinding  using `ccls' as client.\nWhile I was trying to bind the 'lsp_symbol_definition'-command to my custom keys, I had so suffer from a `... type str does not support Buffer API\u00b4.\r\nOn revisiting the relevant file (\"plugin/goto.py\") I found the TODO comment which mentions the future implementation of DocumentLink-support.\r\n\r\nBy dumping the response-payload of the 'lsp_symbol_definition'-command I found out that the received payload has different keys as beeing parsed by the 'handle_response()' function.\r\nSee here:\r\n```\r\n[{targetUri: file:///usr/include/bash/builtins/bashgetopt.h, targetRange: {end: {line: 38, character: 30}, start: {line:\r\n38, character: 0}}, targetSelectionRange: {end: {line: 38, character: 26}, start: {line: 38, character: 11}}}]\r\n```\r\n\r\n### Solution\r\n\r\nSo I added the following snippet to provide the right parsing method in case of this setup/scenario:\r\n\r\n```python\r\n            if 'targetUri' in location:\r\n                file_path = uri_to_filename(location['targetUri'])\r\n                start = Point.from_lsp(location['targetRange']['start'])\r\n            else:\r\n                file_path = uri_to_filename(location[\"uri\"])\r\n                start = Point.from_lsp(location['range']['start'])\r\n```\r\n\r\nBy adding this the desired function of my keybinding worked.\r\n\r\nI just wanted to share this in the hope it might be useful.\r\nBest regards !\r\n\n", "before_files": [{"content": "import sublime\n\nfrom .core.registry import LspTextCommand\nfrom .core.protocol import Request, Point\nfrom .core.documents import get_document_position, get_position, is_at_word\nfrom .core.url import uri_to_filename\nfrom .core.logging import debug\nfrom Default.history_list import get_jump_history_for_view\n\ntry:\n    from typing import List, Dict, Optional, Any\n    assert List and Dict and Optional and Any\nexcept ImportError:\n    pass\n\n\nclass LspGotoCommand(LspTextCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"definition\"\n\n    def is_enabled(self, event: 'Optional[dict]' = None) -> bool:\n        if self.has_client_with_capability(self.goto_kind + \"Provider\"):\n            return is_at_word(self.view, event)\n        return False\n\n    def run(self, edit: sublime.Edit, event: 'Optional[dict]' = None) -> None:\n        client = self.client_with_capability(self.goto_kind + \"Provider\")\n        if client:\n            pos = get_position(self.view, event)\n            document_position = get_document_position(self.view, pos)\n            if document_position:\n                request_type = getattr(Request, self.goto_kind)\n                if not request_type:\n                    debug(\"unrecognized goto kind:\", self.goto_kind)\n                    return\n                request = request_type(document_position)\n                client.send_request(\n                    request, lambda response: self.handle_response(response, pos))\n\n    def handle_response(self, response: 'Optional[Any]', position: int) -> None:\n        window = sublime.active_window()\n        if response:\n            # Save to jump back history.\n            get_jump_history_for_view(self.view).push_selection(self.view)\n            # TODO: DocumentLink support.\n            location = response if isinstance(response, dict) else response[0]\n            file_path = uri_to_filename(location.get(\"uri\"))\n            start = Point.from_lsp(location['range']['start'])\n            file_location = \"{}:{}:{}\".format(file_path, start.row + 1, start.col + 1)\n            debug(\"opening location\", location)\n            window.open_file(file_location, sublime.ENCODED_POSITION)\n            # TODO: can add region here.\n        else:\n            sublime.status_message(\"Empty response from language server, \"\n                                   \"reverting to Sublime's built-in Goto Definition\")\n            window.run_command(\"goto_definition\")\n\n    def want_event(self) -> bool:\n        return True\n\n\nclass LspSymbolDefinitionCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"definition\"\n\n\nclass LspSymbolTypeDefinitionCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"typeDefinition\"\n\n\nclass LspSymbolDeclarationCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"declaration\"\n\n\nclass LspSymbolImplementationCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"implementation\"\n", "path": "plugin/goto.py"}, {"content": "from .types import ClientConfig, ClientStates, Settings\nfrom .protocol import Request\nfrom .transports import start_tcp_transport, start_tcp_listener, TCPTransport, Transport\nfrom .rpc import Client, attach_stdio_client\nfrom .process import start_server\nfrom .url import filename_to_uri\nfrom .logging import debug\nimport os\nfrom .protocol import completion_item_kinds, symbol_kinds\ntry:\n    from typing import Callable, Dict, Any, Optional\n    assert Callable and Dict and Any and Optional and Transport\nexcept ImportError:\n    pass\n\n\ndef create_session(config: ClientConfig,\n                   project_path: str,\n                   env: dict,\n                   settings: Settings,\n                   on_pre_initialize: 'Optional[Callable[[Session], None]]' = None,\n                   on_post_initialize: 'Optional[Callable[[Session], None]]' = None,\n                   on_post_exit: 'Optional[Callable[[str], None]]' = None,\n                   bootstrap_client: 'Optional[Any]' = None) -> 'Optional[Session]':\n\n    def with_client(client: Client) -> 'Session':\n        return Session(\n            config=config,\n            project_path=project_path,\n            client=client,\n            on_pre_initialize=on_pre_initialize,\n            on_post_initialize=on_post_initialize,\n            on_post_exit=on_post_exit)\n\n    session = None\n    if config.binary_args:\n        tcp_port = config.tcp_port\n        server_args = config.binary_args\n\n        if config.tcp_mode == \"host\":\n            socket = start_tcp_listener(tcp_port or 0)\n            tcp_port = socket.getsockname()[1]\n            server_args = list(s.replace(\"{port}\", str(tcp_port)) for s in config.binary_args)\n\n        process = start_server(server_args, project_path, env, settings.log_stderr)\n        if process:\n            if config.tcp_mode == \"host\":\n                client_socket, address = socket.accept()\n                transport = TCPTransport(client_socket)  # type: Transport\n                session = with_client(Client(transport, settings))\n            elif tcp_port:\n                transport = start_tcp_transport(tcp_port, config.tcp_host)\n                if transport:\n                    session = with_client(Client(transport, settings))\n                else:\n                    # try to terminate the process\n                    try:\n                        process.terminate()\n                    except Exception:\n                        pass\n            else:\n                session = with_client(attach_stdio_client(process, settings))\n    else:\n        if config.tcp_port:\n            transport = start_tcp_transport(config.tcp_port)\n            session = with_client(Client(transport, settings))\n        elif bootstrap_client:\n            session = with_client(bootstrap_client)\n        else:\n            debug(\"No way to start session\")\n    return session\n\n\ndef get_initialize_params(project_path: str, config: ClientConfig) -> dict:\n    initializeParams = {\n        \"processId\": os.getpid(),\n        \"rootUri\": filename_to_uri(project_path),\n        \"rootPath\": project_path,\n        \"capabilities\": {\n            \"textDocument\": {\n                \"synchronization\": {\n                    \"didSave\": True,\n                    \"willSaveWaitUntil\": True\n                },\n                \"hover\": {\n                    \"contentFormat\": [\"markdown\", \"plaintext\"]\n                },\n                \"completion\": {\n                    \"completionItem\": {\n                        \"snippetSupport\": True\n                    },\n                    \"completionItemKind\": {\n                        \"valueSet\": completion_item_kinds\n                    }\n                },\n                \"signatureHelp\": {\n                    \"signatureInformation\": {\n                        \"documentationFormat\": [\"markdown\", \"plaintext\"],\n                        \"parameterInformation\": {\n                            \"labelOffsetSupport\": True\n                        }\n                    }\n                },\n                \"references\": {},\n                \"documentHighlight\": {},\n                \"documentSymbol\": {\n                    \"symbolKind\": {\n                        \"valueSet\": symbol_kinds\n                    }\n                },\n                \"formatting\": {},\n                \"rangeFormatting\": {},\n                \"declaration\": {},\n                \"definition\": {},\n                \"typeDefinition\": {},\n                \"implementation\": {},\n                \"codeAction\": {\n                    \"codeActionLiteralSupport\": {\n                        \"codeActionKind\": {\n                            \"valueSet\": []\n                        }\n                    }\n                },\n                \"rename\": {},\n                \"colorProvider\": {},\n                \"publishDiagnostics\": {\n                    \"relatedInformation\": True\n                }\n            },\n            \"workspace\": {\n                \"applyEdit\": True,\n                \"didChangeConfiguration\": {},\n                \"executeCommand\": {},\n                \"symbol\": {\n                    \"symbolKind\": {\n                        \"valueSet\": symbol_kinds\n                    }\n                }\n            }\n        }\n    }\n    if config.init_options:\n        initializeParams['initializationOptions'] = config.init_options\n\n    return initializeParams\n\n\nclass Session(object):\n    def __init__(self,\n                 config: ClientConfig,\n                 project_path: str,\n                 client: Client,\n                 on_pre_initialize: 'Optional[Callable[[Session], None]]' = None,\n                 on_post_initialize: 'Optional[Callable[[Session], None]]' = None,\n                 on_post_exit: 'Optional[Callable[[str], None]]' = None) -> None:\n        self.config = config\n        self.state = ClientStates.STARTING\n        self._on_post_initialize = on_post_initialize\n        self._on_post_exit = on_post_exit\n        self.capabilities = dict()  # type: Dict[str, Any]\n        self.client = client\n        if on_pre_initialize:\n            on_pre_initialize(self)\n        self._initialize(project_path)\n\n    def has_capability(self, capability: str) -> bool:\n        return capability in self.capabilities and self.capabilities[capability] is not False\n\n    def get_capability(self, capability: str) -> 'Optional[Any]':\n        return self.capabilities.get(capability)\n\n    def _initialize(self, project_path: str) -> None:\n        params = get_initialize_params(project_path, self.config)\n        self.client.send_request(\n            Request.initialize(params),\n            lambda result: self._handle_initialize_result(result))\n\n    def _handle_initialize_result(self, result: 'Any') -> None:\n        self.state = ClientStates.READY\n        self.capabilities = result.get('capabilities', dict())\n        if self._on_post_initialize:\n            self._on_post_initialize(self)\n\n    def end(self) -> None:\n        self.state = ClientStates.STOPPING\n        self.client.send_request(\n            Request.shutdown(),\n            lambda result: self._handle_shutdown_result(),\n            lambda error: self._handle_shutdown_result())\n\n    def _handle_shutdown_result(self) -> None:\n        self.client.exit()\n        self.client = None  # type: ignore\n        self.capabilities = dict()\n        if self._on_post_exit:\n            self._on_post_exit(self.config.name)\n", "path": "plugin/core/sessions.py"}], "after_files": [{"content": "import sublime\n\nfrom .core.registry import LspTextCommand\nfrom .core.protocol import Request, Point\nfrom .core.documents import get_document_position, get_position, is_at_word\nfrom .core.url import uri_to_filename\nfrom .core.logging import debug\nfrom Default.history_list import get_jump_history_for_view\n\ntry:\n    from typing import List, Dict, Optional, Any\n    assert List and Dict and Optional and Any\nexcept ImportError:\n    pass\n\n\nclass LspGotoCommand(LspTextCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"definition\"\n\n    def is_enabled(self, event: 'Optional[dict]' = None) -> bool:\n        if self.has_client_with_capability(self.goto_kind + \"Provider\"):\n            return is_at_word(self.view, event)\n        return False\n\n    def run(self, edit: sublime.Edit, event: 'Optional[dict]' = None) -> None:\n        client = self.client_with_capability(self.goto_kind + \"Provider\")\n        if client:\n            pos = get_position(self.view, event)\n            document_position = get_document_position(self.view, pos)\n            if document_position:\n                request_type = getattr(Request, self.goto_kind)\n                if not request_type:\n                    debug(\"unrecognized goto kind:\", self.goto_kind)\n                    return\n                request = request_type(document_position)\n                client.send_request(\n                    request, lambda response: self.handle_response(response, pos))\n\n    def handle_response(self, response: 'Optional[Any]', position: int) -> None:\n        window = sublime.active_window()\n        if response:\n            # Save to jump back history.\n            get_jump_history_for_view(self.view).push_selection(self.view)\n            # TODO: DocumentLink support.\n            location = response if isinstance(response, dict) else response[0]\n            if \"targetUri\" in location:\n                # TODO: Do something clever with originSelectionRange and targetRange.\n                file_path = uri_to_filename(location[\"targetUri\"])\n                start = Point.from_lsp(location[\"targetSelectionRange\"][\"start\"])\n            else:\n                file_path = uri_to_filename(location[\"uri\"])\n                start = Point.from_lsp(location[\"range\"][\"start\"])\n            file_location = \"{}:{}:{}\".format(file_path, start.row + 1, start.col + 1)\n            debug(\"opening location\", location)\n            window.open_file(file_location, sublime.ENCODED_POSITION)\n            # TODO: can add region here.\n        else:\n            sublime.status_message(\"Empty response from language server, \"\n                                   \"reverting to Sublime's built-in Goto Definition\")\n            window.run_command(\"goto_definition\")\n\n    def want_event(self) -> bool:\n        return True\n\n\nclass LspSymbolDefinitionCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"definition\"\n\n\nclass LspSymbolTypeDefinitionCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"typeDefinition\"\n\n\nclass LspSymbolDeclarationCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"declaration\"\n\n\nclass LspSymbolImplementationCommand(LspGotoCommand):\n\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.goto_kind = \"implementation\"\n", "path": "plugin/goto.py"}, {"content": "from .types import ClientConfig, ClientStates, Settings\nfrom .protocol import Request\nfrom .transports import start_tcp_transport, start_tcp_listener, TCPTransport, Transport\nfrom .rpc import Client, attach_stdio_client\nfrom .process import start_server\nfrom .url import filename_to_uri\nfrom .logging import debug\nimport os\nfrom .protocol import completion_item_kinds, symbol_kinds\ntry:\n    from typing import Callable, Dict, Any, Optional\n    assert Callable and Dict and Any and Optional and Transport\nexcept ImportError:\n    pass\n\n\ndef create_session(config: ClientConfig,\n                   project_path: str,\n                   env: dict,\n                   settings: Settings,\n                   on_pre_initialize: 'Optional[Callable[[Session], None]]' = None,\n                   on_post_initialize: 'Optional[Callable[[Session], None]]' = None,\n                   on_post_exit: 'Optional[Callable[[str], None]]' = None,\n                   bootstrap_client: 'Optional[Any]' = None) -> 'Optional[Session]':\n\n    def with_client(client: Client) -> 'Session':\n        return Session(\n            config=config,\n            project_path=project_path,\n            client=client,\n            on_pre_initialize=on_pre_initialize,\n            on_post_initialize=on_post_initialize,\n            on_post_exit=on_post_exit)\n\n    session = None\n    if config.binary_args:\n        tcp_port = config.tcp_port\n        server_args = config.binary_args\n\n        if config.tcp_mode == \"host\":\n            socket = start_tcp_listener(tcp_port or 0)\n            tcp_port = socket.getsockname()[1]\n            server_args = list(s.replace(\"{port}\", str(tcp_port)) for s in config.binary_args)\n\n        process = start_server(server_args, project_path, env, settings.log_stderr)\n        if process:\n            if config.tcp_mode == \"host\":\n                client_socket, address = socket.accept()\n                transport = TCPTransport(client_socket)  # type: Transport\n                session = with_client(Client(transport, settings))\n            elif tcp_port:\n                transport = start_tcp_transport(tcp_port, config.tcp_host)\n                if transport:\n                    session = with_client(Client(transport, settings))\n                else:\n                    # try to terminate the process\n                    try:\n                        process.terminate()\n                    except Exception:\n                        pass\n            else:\n                session = with_client(attach_stdio_client(process, settings))\n    else:\n        if config.tcp_port:\n            transport = start_tcp_transport(config.tcp_port)\n            session = with_client(Client(transport, settings))\n        elif bootstrap_client:\n            session = with_client(bootstrap_client)\n        else:\n            debug(\"No way to start session\")\n    return session\n\n\ndef get_initialize_params(project_path: str, config: ClientConfig) -> dict:\n    initializeParams = {\n        \"processId\": os.getpid(),\n        \"rootUri\": filename_to_uri(project_path),\n        \"rootPath\": project_path,\n        \"capabilities\": {\n            \"textDocument\": {\n                \"synchronization\": {\n                    \"didSave\": True,\n                    \"willSaveWaitUntil\": True\n                },\n                \"hover\": {\n                    \"contentFormat\": [\"markdown\", \"plaintext\"]\n                },\n                \"completion\": {\n                    \"completionItem\": {\n                        \"snippetSupport\": True\n                    },\n                    \"completionItemKind\": {\n                        \"valueSet\": completion_item_kinds\n                    }\n                },\n                \"signatureHelp\": {\n                    \"signatureInformation\": {\n                        \"documentationFormat\": [\"markdown\", \"plaintext\"],\n                        \"parameterInformation\": {\n                            \"labelOffsetSupport\": True\n                        }\n                    }\n                },\n                \"references\": {},\n                \"documentHighlight\": {},\n                \"documentSymbol\": {\n                    \"symbolKind\": {\n                        \"valueSet\": symbol_kinds\n                    }\n                },\n                \"formatting\": {},\n                \"rangeFormatting\": {},\n                \"declaration\": {\"linkSupport\": True},\n                \"definition\": {\"linkSupport\": True},\n                \"typeDefinition\": {\"linkSupport\": True},\n                \"implementation\": {\"linkSupport\": True},\n                \"codeAction\": {\n                    \"codeActionLiteralSupport\": {\n                        \"codeActionKind\": {\n                            \"valueSet\": []\n                        }\n                    }\n                },\n                \"rename\": {},\n                \"colorProvider\": {},\n                \"publishDiagnostics\": {\n                    \"relatedInformation\": True\n                }\n            },\n            \"workspace\": {\n                \"applyEdit\": True,\n                \"didChangeConfiguration\": {},\n                \"executeCommand\": {},\n                \"symbol\": {\n                    \"symbolKind\": {\n                        \"valueSet\": symbol_kinds\n                    }\n                }\n            }\n        }\n    }\n    if config.init_options:\n        initializeParams['initializationOptions'] = config.init_options\n\n    return initializeParams\n\n\nclass Session(object):\n    def __init__(self,\n                 config: ClientConfig,\n                 project_path: str,\n                 client: Client,\n                 on_pre_initialize: 'Optional[Callable[[Session], None]]' = None,\n                 on_post_initialize: 'Optional[Callable[[Session], None]]' = None,\n                 on_post_exit: 'Optional[Callable[[str], None]]' = None) -> None:\n        self.config = config\n        self.state = ClientStates.STARTING\n        self._on_post_initialize = on_post_initialize\n        self._on_post_exit = on_post_exit\n        self.capabilities = dict()  # type: Dict[str, Any]\n        self.client = client\n        if on_pre_initialize:\n            on_pre_initialize(self)\n        self._initialize(project_path)\n\n    def has_capability(self, capability: str) -> bool:\n        return capability in self.capabilities and self.capabilities[capability] is not False\n\n    def get_capability(self, capability: str) -> 'Optional[Any]':\n        return self.capabilities.get(capability)\n\n    def _initialize(self, project_path: str) -> None:\n        params = get_initialize_params(project_path, self.config)\n        self.client.send_request(\n            Request.initialize(params),\n            lambda result: self._handle_initialize_result(result))\n\n    def _handle_initialize_result(self, result: 'Any') -> None:\n        self.state = ClientStates.READY\n        self.capabilities = result.get('capabilities', dict())\n        if self._on_post_initialize:\n            self._on_post_initialize(self)\n\n    def end(self) -> None:\n        self.state = ClientStates.STOPPING\n        self.client.send_request(\n            Request.shutdown(),\n            lambda result: self._handle_shutdown_result(),\n            lambda error: self._handle_shutdown_result())\n\n    def _handle_shutdown_result(self) -> None:\n        self.client.exit()\n        self.client = None  # type: ignore\n        self.capabilities = dict()\n        if self._on_post_exit:\n            self._on_post_exit(self.config.name)\n", "path": "plugin/core/sessions.py"}]}