internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: sublimelsp/LSP

Issue:
goto commands don't restore selection when location picking is canceled
**Describe the bug**
when there's more than one location available for a `goto*` command, a quick panel is shown to pick.
highlighting entries modifies the selection, canceling the operation doesn't restore the initial selection.

**Expected behavior**
it should restore the selection, like ST's built-in

**Screenshots**
![lsp_goto_cancel_bug](https://user-images.githubusercontent.com/33235928/174485692-f6eb2c91-e309-464d-b44e-9dad258a58e3.gif)

**Environment (please complete the following information):**
- OS: Windows 10
- Sublime Text version: 4126
- LSP version: 1.16.3
- Language servers used: LSP-rust-analyzer

**Additional context**
Add any other context about the problem here. For example, whether you're using a helper
package or your manual server configuration in LSP.sublime-settings. When using
a manual server configuration please include it here if you believe it's applicable.



Discussion:
I guess the problem is here:
https://github.com/sublimelsp/LSP/blob/f83cb8654be9fa1bb07efa5bfc89924020a62324/plugin/locationpicker.py#L84-L85

Resolving patch:
diff --git a/plugin/locationpicker.py b/plugin/locationpicker.py
--- a/plugin/locationpicker.py
+++ b/plugin/locationpicker.py
@@ -53,6 +53,7 @@ def __init__(
         side_by_side: bool
     ) -> None:
         self._view = view
+        self._view_states = ([r.to_tuple() for r in view.sel()], view.viewport_position())
         window = view.window()
         if not window:
             raise ValueError("missing window")
@@ -76,6 +77,9 @@ def _unpack(self, index: int) -> Tuple[Optional[Session], Union[Location, Locati
         return self._weaksession(), location, uri, position
 
     def _select_entry(self, index: int) -> None:
+        if self._view.is_valid() and not self._side_by_side:
+            self._view.set_viewport_position(self._view_states[1])
+            self._view.run_command('lsp_selection_set', {'regions': self._view_states[0]})
         if index >= 0 and self._view.is_valid():
             session, location, uri, position = self._unpack(index)
             if not session:


Test patch:
Repository: sublimelsp/LSP

Issue:
Ampersands (&) in inlay hints are broken
**Describe the bug**
Ampersands (&) in inlay hints break the hint.

**To Reproduce**
1. Install the latest (dev) LSP (in my case this is commit bd4e0149c40cc53fa1f0925fecda38920f7cedc4)
2. Install [LSP-rust-analyzer](https://github.com/sublimelsp/LSP-rust-analyzer) via package control or manually.
3. Configure LSP-rust-analyzer to use the latest (system) rust-analyser. LSP-rust-analyzer hasn't quite yet got full support for the new inlay hints system. Use the setting `"command": ["rust-analyzer"]`
4. Enable the rust-analyzer engine globally or just for the project
5. Input this test code:
```rust
fn main(){
    let a = 1337;
    
    let b = "deez nuts";

    println!("Haha funny number: {}, and funny words: {}!", a, b);
}
```

6. Note that b is of type &str, and the type hint is completely busted. Hints which do not contain ampersands are not affected.

![image](https://user-images.githubusercontent.com/20499616/187150743-4ceab171-6241-4000-9d12-e7390a4ade71.png)

**Environment:**
- OS: Arch Linux
- Sublime Text version: 4126
- LSP version: main branch, commit bd4e0149c40cc53fa1f0925fecda38920f7cedc4
- Language servers used: rust-analyzer



Discussion:

Resolving patch:
diff --git a/plugin/hover.py b/plugin/hover.py
--- a/plugin/hover.py
+++ b/plugin/hover.py
@@ -38,6 +38,7 @@
 from .session_view import HOVER_HIGHLIGHT_KEY
 from urllib.parse import unquote, urlparse
 import functools
+import html
 import re
 import sublime
 import webbrowser
@@ -224,7 +225,7 @@ def _on_all_document_links_resolved(
             title = link.get("tooltip") or "Follow link"
             if title != "Follow link":
                 link_has_standard_tooltip = False
-            contents.append('<a href="{}">{}</a>'.format(target, title))
+            contents.append('<a href="{}">{}</a>'.format(html.escape(target), html.escape(title)))
         if len(contents) > 1:
             link_has_standard_tooltip = False
         link_range = range_to_region(Range.from_lsp(links[0]["range"]), self.view) if links else None
diff --git a/plugin/inlay_hint.py b/plugin/inlay_hint.py
--- a/plugin/inlay_hint.py
+++ b/plugin/inlay_hint.py
@@ -101,9 +101,9 @@ def get_inlay_hint_html(view: sublime.View, inlay_hint: InlayHint, session: Sess
 
 def format_inlay_hint_tooltip(tooltip: Optional[Union[str, MarkupContent]]) -> str:
     if isinstance(tooltip, str):
-        return tooltip
+        return html.escape(tooltip)
     if isinstance(tooltip, dict):  # MarkupContent
-        return tooltip.get('value') or ""
+        return html.escape(tooltip.get('value') or "")
     return ""
 
 


Test patch:
Repository: sublimelsp/LSP

Issue:
Goto Diagnostic is broken under certain conditions
**Describe the bug**
The "LSP: Goto Diagnostic..." and "LSP: Goto Diagnostic in Project..." commands are broken under certain conditions.

**To Reproduce**

1. Install LSP-pyright (for example)
2. In LSP.sublime-settings, set `"diagnostics_panel_include_severity_level": 2`
3. Open a file with the following content:
```python
print(x)

def foo(y):
    pass
```
5. "LSP: Goto Diagnostic..." and "LSP: Goto Diagnostic in Project..." work as expected
6. Comment out the first line with the error "x is not defined"
7. Now, "LSP: Goto Diagnostic..." will just open the command palette, and "LSP: Goto Diagnostic in Project..." will crash Sublime Text (it just closes without error message)

Probably the `max_severity` restriction for the ListInputHandlers of LspGotoDiagnosticCommand should be dropped, or it needs also to be used for `is_enabled`.

**Environment (please complete the following information):**
- OS: Windows 11
- Sublime Text version: 4126
- LSP version: latest
- Language servers used: LSP-pyright



Discussion:

Resolving patch:
diff --git a/plugin/goto_diagnostic.py b/plugin/goto_diagnostic.py
--- a/plugin/goto_diagnostic.py
+++ b/plugin/goto_diagnostic.py
@@ -46,10 +46,16 @@ def is_enabled(self, uri: Optional[DocumentUri] = None, diagnostic: Optional[dic
                 uri = uri_from_view(view)
             except MissingUriError:
                 return False
+        max_severity = userprefs().diagnostics_panel_include_severity_level
         if uri:
             parsed_uri = parse_uri(uri)
-            return any(parsed_uri in session.diagnostics for session in get_sessions(self.window))
-        return any(bool(session.diagnostics) for session in get_sessions(self.window))
+            return any(diagnostic for session in get_sessions(self.window)
+                       for diagnostic in session.diagnostics.diagnostics_by_parsed_uri(parsed_uri)
+                       if is_severity_included(max_severity)(diagnostic))
+        return any(diagnostic for session in get_sessions(self.window)
+                   for diagnostics in session.diagnostics.values()
+                   for diagnostic in diagnostics
+                   if is_severity_included(max_severity)(diagnostic))
 
     def input(self, args: dict) -> Optional[sublime_plugin.CommandInputHandler]:
         uri, diagnostic = args.get("uri"), args.get("diagnostic")


Test patch:
Repository: sublimelsp/LSP

Issue:
`lsp_document_symbols` should initially focus on current symbol under caret
Sublime's default implementation of Goto Symbol pops up with current symbol having focus in the dropdown list, this way I can use up/down arrows to go to prev/next symbols (since Sublime doesn't have goto next/prev symbol features built-in, this is imo a superior way to mimic that feature).

LSP is capable of finding all the symbols for a given language but the problem is, `lsp_document_symbols` commands focuses the first symbol in the file, so I can't easily use the arrow keys to browse the next/previous symbols.

So it would be better if LSP's replacement Goto Symbol popup focused the symbol of the current scope / the symbol under the caret.


Discussion:

Resolving patch:
diff --git a/plugin/symbols.py b/plugin/symbols.py
--- a/plugin/symbols.py
+++ b/plugin/symbols.py
@@ -94,7 +94,6 @@ def __init__(self, view: sublime.View) -> None:
         super().__init__(view)
         self.old_regions = []  # type: List[sublime.Region]
         self.regions = []  # type: List[Tuple[sublime.Region, Optional[sublime.Region], str]]
-        self.is_first_selection = False
 
     def run(self, edit: sublime.Edit, event: Optional[Dict[str, Any]] = None) -> None:
         self.view.settings().set(SUPPRESS_INPUT_SETTING_KEY, True)
@@ -109,13 +108,22 @@ def handle_response(self, response: Union[List[DocumentSymbol], List[SymbolInfor
         self.view.settings().erase(SUPPRESS_INPUT_SETTING_KEY)
         window = self.view.window()
         if window and isinstance(response, list) and len(response) > 0:
+            panel_items = self.process_symbols(response)
             self.old_regions = [sublime.Region(r.a, r.b) for r in self.view.sel()]
-            self.is_first_selection = True
+            # Find region that is either intersecting or before to the current selection end.
+            selected_index = 0
+            if len(self.old_regions):
+                first_selection = self.old_regions[0]
+                for i, (r, _, _) in enumerate(self.regions):
+                    if r.begin() <= first_selection.b:
+                        selected_index = i
+                    else:
+                        break
             window.show_quick_panel(
-                self.process_symbols(response),
+                panel_items,
                 self.on_symbol_selected,
                 sublime.KEEP_OPEN_ON_FOCUS_LOST,
-                0,
+                selected_index,
                 self.on_highlighted)
             self.view.run_command("lsp_selection_clear")
 
@@ -146,9 +154,6 @@ def on_symbol_selected(self, index: int) -> None:
         self.regions.clear()
 
     def on_highlighted(self, index: int) -> None:
-        if self.is_first_selection:
-            self.is_first_selection = False
-            return
         region = self.region(index)
         self.view.show_at_center(region.a)
         self.view.add_regions(self.REGIONS_KEY, [region], self.scope(index), '', sublime.DRAW_NO_FILL)


Test patch:
Repository: sublimelsp/LSP

Issue:
diagnostics_additional_delay_auto_complete_ms doesn't work after split view
**To Reproduce**
1. Install LSP-pyright (for example)
2. Set `"diagnostics_additional_delay_auto_complete_ms": 5000` is LSP settings
3. Create and open a Python file
4. Type `im`
5. Confirm that there is an auto-completion popup and that the diagnostic(s) ("im" is not defined) appear after a delay of 5 seconds - so far so good
6. Remove the text and use *File > Split View*
7. Select the left (original) view
8. Type `im`
9. Observe that the diagnostic(s) immediately appears 

**Expected behavior**
Diagnostics appear only after the delay specified in "diagnostics_additional_delay_auto_complete_ms"

**Environment (please complete the following information):**
- OS: Windows 11
- Sublime Text version: 4126
- LSP version: main branch

**Additional context**
Looks like the bug is here:
https://github.com/sublimelsp/LSP/blob/deeb0cbafce3deba4a37af47f9629b52179f8075/plugin/session_buffer.py#L439-L443

By using `SessionBuffer.some_view()`, a random view is checked for visibility of the autocompletion popup. But instead it should use the *active* view, i.e. the view where I'm currently typing.


Discussion:
Might make sense to make `some_view()` prefer the active view, if possible.

Resolving patch:
diff --git a/plugin/session_buffer.py b/plugin/session_buffer.py
--- a/plugin/session_buffer.py
+++ b/plugin/session_buffer.py
@@ -322,9 +322,15 @@ def on_post_save_async(self, view: sublime.View, new_uri: DocumentUri) -> None:
                 self.session.send_notification(did_save(view, include_text, self.last_known_uri))
 
     def some_view(self) -> Optional[sublime.View]:
+        if not self.session_views:
+            return None
+        # Prefer active view if possible
+        active_view = self.session.window.active_view()
+        for sv in self.session_views:
+            if sv.view == active_view:
+                return active_view
         for sv in self.session_views:
             return sv.view
-        return None
 
     def _if_view_unchanged(self, f: Callable[[sublime.View, Any], None], version: int) -> Callable[[Any], None]:
         """


Test patch:
Repository: sublimelsp/LSP

Issue:
Provide a way to save all modified files after applying workspace edits
**Is your feature request related to a problem? Please describe.**

When applying refactorings (like renames) it's often the case that multiple files are modified. It's a chore to then have to find and save all those modified files.

**Describe the solution you'd like**

We could provide a dialog after more than one file was modified asking the user whether all modified files should be saved. Note that some people don't like dialogs (#1922).

Or maybe even show a "tree view" in a sheet, showing all modified files and allowing the user to navigate to them and save all at once.

**Describe alternatives you've considered**

- Saving all edited files one by one.
- Using "save all" command but that fails when there is some unsaved buffer in the window (for example I like to have some to keep notes in them)



Discussion:
What about adding a setting, that lets LSP save all modified files without user interaction?

Resolving patch:
diff --git a/plugin/save_command.py b/plugin/save_command.py
--- a/plugin/save_command.py
+++ b/plugin/save_command.py
@@ -117,7 +117,7 @@ def _trigger_native_save(self) -> None:
 
 
 class LspSaveAllCommand(sublime_plugin.WindowCommand):
-    def run(self) -> None:
+    def run(self, only_files: bool = False) -> None:
         done = set()
         for view in self.window.views():
             buffer_id = view.buffer_id()
@@ -125,5 +125,7 @@ def run(self) -> None:
                 continue
             if not view.is_dirty():
                 continue
+            if only_files and view.file_name() is None:
+                continue
             done.add(buffer_id)
             view.run_command("lsp_save", None)


Test patch:
Repository: sublimelsp/LSP

Issue:
`KeyError` in LSP plugin when trying to open Preferences
My ST4 setup: version: 4169 osx arm64 channel: stable

LSP v1.27.0

I see this trace in the console whenever I try to open Settings/Preferences (it opens successfully, but this error worries me):

```
Unable to open /Users/samir.bajaj/Library/Application Support/Sublime Text/Packages/Default/Preferences.sublime-settings
Traceback (most recent call last):
  File "/Users/samir.bajaj/Library/Application Support/Sublime Text/Installed Packages/LSP.sublime-package/plugin/documents.py", line 968, in clear_async
  File "/Users/samir.bajaj/Library/Application Support/Sublime Text/Installed Packages/LSP.sublime-package/plugin/session_view.py", line 104, in on_before_remove
  File "/Users/samir.bajaj/Library/Application Support/Sublime Text/Installed Packages/LSP.sublime-package/plugin/session_buffer.py", line 203, in remove_session_view
  File "./python3.3/_weakrefset.py", line 109, in remove
KeyError: <weakref at 0x104a93ef8; to 'SessionView' at 0x104a5b7b8>
```


I originally posted this on the Sublime Forum, but got no responses.

Thank you for your help.



Discussion:
Can you record a video of you opening the preferences?

Also you can try in [safe mode](https://www.sublimetext.com/docs/safe_mode.html). It doesn't reproduce here.
Hi @rchl -- thank you for your response.

Here's a video I recorded.

Also, I couldn't reproduce it in safe mode.

Hope this helps!

https://github.com/sublimelsp/LSP/assets/37282578/e0d1356c-f5be-4d2c-b831-f92826b9c102


Thanks. I can reproduce it in safe mode with just LSP and LSP-json installed.

Resolving patch:
diff --git a/plugin/core/windows.py b/plugin/core/windows.py
--- a/plugin/core/windows.py
+++ b/plugin/core/windows.py
@@ -545,7 +545,7 @@ def listener_for_view(self, view: sublime.View) -> Optional[AbstractViewListener
     def discard(self, window: sublime.Window) -> None:
         wm = self._windows.pop(window.id(), None)
         if wm:
-            wm.destroy()
+            sublime.set_timeout_async(wm.destroy)
 
 
 class RequestTimeTracker:


Test patch:
Repository: sublimelsp/LSP

Issue:
Goto Definition throws
**Describe the bug**
Using `LSP-pyright`, click `Definition`. Nothing will happen visually.

**To Reproduce**
1. `LSP-pyright`
2. hover over something
3. click `Definition` (or `Type Definition` or `Declaration`)
4. see error in console: 
```py
Traceback (most recent call last):
  File "D:\Programs\Sublime Text 4\Data\Installed Packages\LSP.sublime-package\plugin/core/sessions.py", line 1681, in <lambda>
  File "D:\Programs\Sublime Text 4\Data\Installed Packages\LSP.sublime-package\plugin/core/open.py", line 96, in open_file
  File "D:\Programs\Sublime Text 4\Data\Installed Packages\LSP.sublime-package\plugin/core/open.py", line 82, in _find_open_file
TypeError: find_open_file() takes 2 positional arguments but 3 were given
```

**Expected behavior**
no error, I go to definition

**Environment (please complete the following information):**
- OS: windows
- Sublime Text version: 4121
- LSP version: 1.28.0
- Language servers used: pyright-1.2.42



Discussion:
You need to update your Sublime Text version to the latest stable version.
I think we could and should still fix it easily here.
```diff
- return window.find_open_file(fname, group)
+ return window.find_open_file(fname, group) if ST_VERSION >= 41XX else window.find_open_file(fname)
```

Just need to find out which ST version added the optional `group` argument for this method. It doesn't seem to be listed in the changelog.

Alternative would be to use the proper version restriction for LSP at https://github.com/sublimelsp/repository/blob/200d5081fdbbff3c2c21f85a4e84f600ec2a7a84/repository.json#L50
I suppose we should but at the same I'd prefer a world where people are on latest versions so that they benefit from latest fixes and don't waste time reporting issues that might already be fixed.

But then I suppose in case of paid software (ST) it might be a bit insensitive to require always the latest version given that someone might be using older version due to expired license, for example...
I upgraded to ST4169, it fixed the problem. Thank you.


Resolving patch:
diff --git a/plugin/core/open.py b/plugin/core/open.py
--- a/plugin/core/open.py
+++ b/plugin/core/open.py
@@ -1,3 +1,4 @@
+from .constants import ST_VERSION
 from .logging import exception_log
 from .promise import Promise
 from .promise import ResolveFunc
@@ -79,7 +80,7 @@ def _find_open_file(window: sublime.Window, fname: str, group: int = -1) -> Opti
     view = window.active_view_in_group(_group)
     if view and fname == view.file_name():
         return view
-    return window.find_open_file(fname, group)
+    return window.find_open_file(fname, group) if ST_VERSION >= 4136 else window.find_open_file(fname)
 
 
 def open_file(


Test patch:
Repository: googleapis/google-cloud-python

Issue:
attribute 'timedelta'  Datetime property when performance a Query
  File "/home/albertog/Documents/spyder-2.3.0beta1/scripts/semtable/test/test.py", line 43, in main
    q.fetch(1)

  File "gcloud/datastore/query.py", line 247, in fetch
    return [Entity.from_protobuf(entity) for entity in entity_pbs]

  File "gcloud/datastore/entity.py", line 148, in from_protobuf
    value = helpers.get_value_from_protobuf(property_pb)

  File "gcloud/datastore/helpers.py", line 82, in get_value_from_protobuf
    datetime.timedelta(microseconds=microseconds))

AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'



Discussion:

Resolving patch:
diff --git a/gcloud/datastore/helpers.py b/gcloud/datastore/helpers.py
--- a/gcloud/datastore/helpers.py
+++ b/gcloud/datastore/helpers.py
@@ -1,6 +1,6 @@
 """Helper methods for dealing with Cloud Datastore's Protobuf API."""
 import calendar
-from datetime import datetime
+from datetime import datetime, timedelta
 
 import pytz
 
@@ -79,7 +79,7 @@ def get_value_from_protobuf(pb):
   if pb.value.HasField('timestamp_microseconds_value'):
     microseconds = pb.value.timestamp_microseconds_value
     return (datetime.utcfromtimestamp(0) +
-            datetime.timedelta(microseconds=microseconds))
+            timedelta(microseconds=microseconds))
 
   elif pb.value.HasField('key_value'):
     return Key.from_protobuf(pb.value.key_value)


Test patch:
Repository: googleapis/google-cloud-python

Issue:
Add a Getting started with Cloud Storage walk-through



Discussion:

Resolving patch:
diff --git a/gcloud/storage/acl.py b/gcloud/storage/acl.py
--- a/gcloud/storage/acl.py
+++ b/gcloud/storage/acl.py
@@ -15,22 +15,25 @@
 Adding and removing permissions can be done with the following methods
 (in increasing order of granularity):
 
- - :func:`ACL.all`
-   corresponds to access for all users.
- - :func:`ACL.all_authenticated` corresponds
-   to access for all users that are signed into a Google account.
- - :func:`ACL.domain` corresponds to access on a
-   per Google Apps domain (ie, ``example.com``).
- - :func:`ACL.group` corresponds to access on a
-   per group basis (either by ID or e-mail address).
- - :func:`ACL.user` corresponds to access on a
-   per user basis (either by ID or e-mail address).
-
-And you are able to ``grant`` and ``revoke`` the following roles::
-
-  - :func:`ACL.Entity.grant_read` and :func:`ACL.Entity.revoke_read`
-  - :func:`ACL.Entity.grant_write` and :func:`ACL.Entity.revoke_write`
-  - :func:`ACL.Entity.grant_owner` and :func:`ACL.Entity.revoke_owner`
+- :func:`ACL.all`
+  corresponds to access for all users.
+- :func:`ACL.all_authenticated` corresponds
+  to access for all users that are signed into a Google account.
+- :func:`ACL.domain` corresponds to access on a
+  per Google Apps domain (ie, ``example.com``).
+- :func:`ACL.group` corresponds to access on a
+  per group basis (either by ID or e-mail address).
+- :func:`ACL.user` corresponds to access on a
+  per user basis (either by ID or e-mail address).
+
+And you are able to ``grant`` and ``revoke`` the following roles:
+
+- **Reading**:
+  :func:`ACL.Entity.grant_read` and :func:`ACL.Entity.revoke_read`
+- **Writing**:
+  :func:`ACL.Entity.grant_write` and :func:`ACL.Entity.revoke_write`
+- **Owning**:
+  :func:`ACL.Entity.grant_owner` and :func:`ACL.Entity.revoke_owner`
 
 You can use any of these like any other factory method
 (these happen to be :class:`ACL.Entity` factories)::


Test patch: