prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Reduce impact of LSP color listener by default.
  @predragnikolic: Noticed while closing views after find-replace in pyls:
  
  ```
  Traceback (most recent call last):
    File "/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py", line 506, in run_async_view_listener_callback
      vel.__class__.__dict__[name](vel)
    File "/Users/tomv/Library/Application Support/Sublime Text 3/Packages/LSP/plugin/color.py", line 47, in on_activated_async
      self.schedule_request()
    File "/Users/tomv/Library/Application Support/Sublime Text 3/Packages/LSP/plugin/color.py", line 53, in schedule_request
      current_point = self.view.sel()[0].begin()
    File "/Applications/Sublime Text.app/Contents/MacOS/sublime.py", line 649, in __getitem__
      raise IndexError()
  IndexError
  ```
  
  * We should probably fix the above issue (maybe it's rare but I ran into this edge case pretty quickly)
  * We could avoid creating ViewEventListeners for a few kinds of irrelevant views: Read-only, transient, unsupported syntaxes ( Maybe `DocumentSyncListener` `is_applicable` is suitable?)
  * We could avoid running `LspColorListener`'s `schedule_request` until a session with colorProvider for a given view has been found.
  
  
  --- 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/color.py`
  Content:
  ```
  1 import sublime_plugin
  2 import sublime
  3 
  4 try:
  5     from typing import Any, List, Dict, Callable, Optional
  6     assert Any and List and Dict and Callable and Optional
  7 except ImportError:
  8     pass
  9 
  10 from .core.protocol import Request
  11 from .core.url import filename_to_uri
  12 from .core.registry import session_for_view
  13 from .core.settings import settings
  14 from .core.views import range_to_region
  15 from .core.protocol import Range
  16 
  17 
  18 def send_color_request(view, on_response_recieved: 'Callable'):
  19     session = session_for_view(view)
  20     if not session or not session.has_capability('colorProvider'):
  21         # the server doesn't support colors, just return
  22         return
  23 
  24     params = {
  25         "textDocument": {
  26             "uri": filename_to_uri(view.file_name())
  27         }
  28     }
  29     session.client.send_request(
  30         Request.documentColor(params),
  31         lambda response: on_response_recieved(response))
  32 
  33 
  34 class LspColorListener(sublime_plugin.ViewEventListener):
  35     def __init__(self, view: sublime.View) -> None:
  36         super().__init__(view)
  37         self.color_phantom_set = None  # type: Optional[sublime.PhantomSet]
  38         self._stored_point = -1
  39 
  40     @classmethod
  41     def is_applicable(cls, _settings):
  42         return 'colorProvider' not in settings.disabled_capabilities
  43 
  44     def on_activated_async(self):
  45         self.schedule_request()
  46 
  47     def on_modified_async(self):
  48         self.schedule_request()
  49 
  50     def schedule_request(self):
  51         current_point = self.view.sel()[0].begin()
  52         if self._stored_point != current_point:
  53             self._stored_point = current_point
  54             sublime.set_timeout_async(lambda: self.fire_request(current_point), 800)
  55 
  56     def fire_request(self, current_point: int) -> None:
  57         if current_point == self._stored_point:
  58             send_color_request(self.view, self.handle_response)
  59 
  60     def handle_response(self, response) -> None:
  61         phantoms = []
  62         for val in response:
  63             color = val['color']
  64             red = color['red'] * 255
  65             green = color['green'] * 255
  66             blue = color['blue'] * 255
  67             alpha = color['alpha']
  68 
  69             content = """
  70             <div style='padding: 0.4em;
  71                         margin-top: 0.1em;
  72                         border: 1px solid color(var(--foreground) alpha(0.25));
  73                         background-color: rgba({}, {}, {}, {})'>
  74             </div>""".format(red, green, blue, alpha)
  75 
  76             range = Range.from_lsp(val['range'])
  77             region = range_to_region(range, self.view)
  78 
  79             phantoms.append(sublime.Phantom(region, content, sublime.LAYOUT_INLINE))
  80 
  81         if phantoms:
  82             if not self.color_phantom_set:
  83                 self.color_phantom_set = sublime.PhantomSet(self.view, "lsp_color")
  84             self.color_phantom_set.update(phantoms)
  85         else:
  86             self.color_phantom_set = None
  87 
  88 
  89 def remove_color_boxes(view):
  90     view.erase_phantoms('lsp_color')
  91
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/plugin/color.py b/plugin/color.py
  --- a/plugin/color.py
  +++ b/plugin/color.py
  @@ -9,26 +9,12 @@
   
   from .core.protocol import Request
   from .core.url import filename_to_uri
  -from .core.registry import session_for_view
  -from .core.settings import settings
  +from .core.registry import session_for_view, config_for_scope
  +from .core.settings import settings, client_configs
   from .core.views import range_to_region
   from .core.protocol import Range
  -
  -
  -def send_color_request(view, on_response_recieved: 'Callable'):
  -    session = session_for_view(view)
  -    if not session or not session.has_capability('colorProvider'):
  -        # the server doesn't support colors, just return
  -        return
  -
  -    params = {
  -        "textDocument": {
  -            "uri": filename_to_uri(view.file_name())
  -        }
  -    }
  -    session.client.send_request(
  -        Request.documentColor(params),
  -        lambda response: on_response_recieved(response))
  +from .core.configurations import is_supported_syntax
  +from .core.documents import is_transient_view
   
   
   class LspColorListener(sublime_plugin.ViewEventListener):
  @@ -36,26 +22,72 @@
           super().__init__(view)
           self.color_phantom_set = None  # type: Optional[sublime.PhantomSet]
           self._stored_point = -1
  +        self.initialized = False
  +        self.enabled = False
   
       @classmethod
       def is_applicable(cls, _settings):
  -        return 'colorProvider' not in settings.disabled_capabilities
  +        syntax = _settings.get('syntax')
  +        is_supported = syntax and is_supported_syntax(syntax, client_configs.all)
  +        disabled_by_user = 'colorProvider' in settings.disabled_capabilities
  +        return is_supported and not disabled_by_user
   
       def on_activated_async(self):
  -        self.schedule_request()
  +        if not self.initialized:
  +            self.initialize()
  +
  +    def initialize(self, is_retry=False):
  +        config = config_for_scope(self.view)
  +        if not config:
  +            self.initialized = True  # no server enabled, re-open file to activate feature.
  +
  +        session = session_for_view(self.view)
  +        if session:
  +            self.initialized = True
  +            self.enabled = session.has_capability('colorProvider')
  +            if self.enabled:
  +                self.send_color_request()
  +        elif not is_retry:
  +            # session may be starting, try again once in a second.
  +            sublime.set_timeout_async(lambda: self.initialize(is_retry=True), 1000)
  +        else:
  +            self.initialized = True  # we retried but still no session available.
   
       def on_modified_async(self):
  -        self.schedule_request()
  +        if self.enabled:
  +            self.schedule_request()
   
       def schedule_request(self):
  -        current_point = self.view.sel()[0].begin()
  +        sel = self.view.sel()
  +        if len(sel) < 1:
  +            return
  +
  +        current_point = sel[0].begin()
           if self._stored_point != current_point:
               self._stored_point = current_point
               sublime.set_timeout_async(lambda: self.fire_request(current_point), 800)
   
       def fire_request(self, current_point: int) -> None:
           if current_point == self._stored_point:
  -            send_color_request(self.view, self.handle_response)
  +            self.send_color_request()
  +
  +    def send_color_request(self):
  +        if is_transient_view(self.view):
  +            return
  +
  +        session = session_for_view(self.view)
  +        if not session:
  +            return
  +
  +        params = {
  +            "textDocument": {
  +                "uri": filename_to_uri(self.view.file_name())
  +            }
  +        }
  +        session.client.send_request(
  +            Request.documentColor(params),
  +            self.handle_response
  +        )
   
       def handle_response(self, response) -> None:
           phantoms = []
  @@ -68,7 +100,7 @@
   
               content = """
               <div style='padding: 0.4em;
  -                        margin-top: 0.1em;
  +                        margin-top: 0.2em;
                           border: 1px solid color(var(--foreground) alpha(0.25));
                           background-color: rgba({}, {}, {}, {})'>
               </div>""".format(red, green, blue, alpha)
  
verification_info: {"golden_diff": "diff --git a/plugin/color.py b/plugin/color.py\n--- a/plugin/color.py\n+++ b/plugin/color.py\n@@ -9,26 +9,12 @@\n \n from .core.protocol import Request\n from .core.url import filename_to_uri\n-from .core.registry import session_for_view\n-from .core.settings import settings\n+from .core.registry import session_for_view, config_for_scope\n+from .core.settings import settings, client_configs\n from .core.views import range_to_region\n from .core.protocol import Range\n-\n-\n-def send_color_request(view, on_response_recieved: 'Callable'):\n-    session = session_for_view(view)\n-    if not session or not session.has_capability('colorProvider'):\n-        # the server doesn't support colors, just return\n-        return\n-\n-    params = {\n-        \"textDocument\": {\n-            \"uri\": filename_to_uri(view.file_name())\n-        }\n-    }\n-    session.client.send_request(\n-        Request.documentColor(params),\n-        lambda response: on_response_recieved(response))\n+from .core.configurations import is_supported_syntax\n+from .core.documents import is_transient_view\n \n \n class LspColorListener(sublime_plugin.ViewEventListener):\n@@ -36,26 +22,72 @@\n         super().__init__(view)\n         self.color_phantom_set = None  # type: Optional[sublime.PhantomSet]\n         self._stored_point = -1\n+        self.initialized = False\n+        self.enabled = False\n \n     @classmethod\n     def is_applicable(cls, _settings):\n-        return 'colorProvider' not in settings.disabled_capabilities\n+        syntax = _settings.get('syntax')\n+        is_supported = syntax and is_supported_syntax(syntax, client_configs.all)\n+        disabled_by_user = 'colorProvider' in settings.disabled_capabilities\n+        return is_supported and not disabled_by_user\n \n     def on_activated_async(self):\n-        self.schedule_request()\n+        if not self.initialized:\n+            self.initialize()\n+\n+    def initialize(self, is_retry=False):\n+        config = config_for_scope(self.view)\n+        if not config:\n+            self.initialized = True  # no server enabled, re-open file to activate feature.\n+\n+        session = session_for_view(self.view)\n+        if session:\n+            self.initialized = True\n+            self.enabled = session.has_capability('colorProvider')\n+            if self.enabled:\n+                self.send_color_request()\n+        elif not is_retry:\n+            # session may be starting, try again once in a second.\n+            sublime.set_timeout_async(lambda: self.initialize(is_retry=True), 1000)\n+        else:\n+            self.initialized = True  # we retried but still no session available.\n \n     def on_modified_async(self):\n-        self.schedule_request()\n+        if self.enabled:\n+            self.schedule_request()\n \n     def schedule_request(self):\n-        current_point = self.view.sel()[0].begin()\n+        sel = self.view.sel()\n+        if len(sel) < 1:\n+            return\n+\n+        current_point = sel[0].begin()\n         if self._stored_point != current_point:\n             self._stored_point = current_point\n             sublime.set_timeout_async(lambda: self.fire_request(current_point), 800)\n \n     def fire_request(self, current_point: int) -> None:\n         if current_point == self._stored_point:\n-            send_color_request(self.view, self.handle_response)\n+            self.send_color_request()\n+\n+    def send_color_request(self):\n+        if is_transient_view(self.view):\n+            return\n+\n+        session = session_for_view(self.view)\n+        if not session:\n+            return\n+\n+        params = {\n+            \"textDocument\": {\n+                \"uri\": filename_to_uri(self.view.file_name())\n+            }\n+        }\n+        session.client.send_request(\n+            Request.documentColor(params),\n+            self.handle_response\n+        )\n \n     def handle_response(self, response) -> None:\n         phantoms = []\n@@ -68,7 +100,7 @@\n \n             content = \"\"\"\n             <div style='padding: 0.4em;\n-                        margin-top: 0.1em;\n+                        margin-top: 0.2em;\n                         border: 1px solid color(var(--foreground) alpha(0.25));\n                         background-color: rgba({}, {}, {}, {})'>\n             </div>\"\"\".format(red, green, blue, alpha)\n", "issue": "Reduce impact of LSP color listener by default.\n@predragnikolic: Noticed while closing views after find-replace in pyls:\r\n\r\n```\r\nTraceback (most recent call last):\r\n  File \"/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py\", line 506, in run_async_view_listener_callback\r\n    vel.__class__.__dict__[name](vel)\r\n  File \"/Users/tomv/Library/Application Support/Sublime Text 3/Packages/LSP/plugin/color.py\", line 47, in on_activated_async\r\n    self.schedule_request()\r\n  File \"/Users/tomv/Library/Application Support/Sublime Text 3/Packages/LSP/plugin/color.py\", line 53, in schedule_request\r\n    current_point = self.view.sel()[0].begin()\r\n  File \"/Applications/Sublime Text.app/Contents/MacOS/sublime.py\", line 649, in __getitem__\r\n    raise IndexError()\r\nIndexError\r\n```\r\n\r\n* We should probably fix the above issue (maybe it's rare but I ran into this edge case pretty quickly)\r\n* We could avoid creating ViewEventListeners for a few kinds of irrelevant views: Read-only, transient, unsupported syntaxes ( Maybe `DocumentSyncListener` `is_applicable` is suitable?)\r\n* We could avoid running `LspColorListener`'s `schedule_request` until a session with colorProvider for a given view has been found.\r\n\n", "before_files": [{"content": "import sublime_plugin\nimport sublime\n\ntry:\n    from typing import Any, List, Dict, Callable, Optional\n    assert Any and List and Dict and Callable and Optional\nexcept ImportError:\n    pass\n\nfrom .core.protocol import Request\nfrom .core.url import filename_to_uri\nfrom .core.registry import session_for_view\nfrom .core.settings import settings\nfrom .core.views import range_to_region\nfrom .core.protocol import Range\n\n\ndef send_color_request(view, on_response_recieved: 'Callable'):\n    session = session_for_view(view)\n    if not session or not session.has_capability('colorProvider'):\n        # the server doesn't support colors, just return\n        return\n\n    params = {\n        \"textDocument\": {\n            \"uri\": filename_to_uri(view.file_name())\n        }\n    }\n    session.client.send_request(\n        Request.documentColor(params),\n        lambda response: on_response_recieved(response))\n\n\nclass LspColorListener(sublime_plugin.ViewEventListener):\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.color_phantom_set = None  # type: Optional[sublime.PhantomSet]\n        self._stored_point = -1\n\n    @classmethod\n    def is_applicable(cls, _settings):\n        return 'colorProvider' not in settings.disabled_capabilities\n\n    def on_activated_async(self):\n        self.schedule_request()\n\n    def on_modified_async(self):\n        self.schedule_request()\n\n    def schedule_request(self):\n        current_point = self.view.sel()[0].begin()\n        if self._stored_point != current_point:\n            self._stored_point = current_point\n            sublime.set_timeout_async(lambda: self.fire_request(current_point), 800)\n\n    def fire_request(self, current_point: int) -> None:\n        if current_point == self._stored_point:\n            send_color_request(self.view, self.handle_response)\n\n    def handle_response(self, response) -> None:\n        phantoms = []\n        for val in response:\n            color = val['color']\n            red = color['red'] * 255\n            green = color['green'] * 255\n            blue = color['blue'] * 255\n            alpha = color['alpha']\n\n            content = \"\"\"\n            <div style='padding: 0.4em;\n                        margin-top: 0.1em;\n                        border: 1px solid color(var(--foreground) alpha(0.25));\n                        background-color: rgba({}, {}, {}, {})'>\n            </div>\"\"\".format(red, green, blue, alpha)\n\n            range = Range.from_lsp(val['range'])\n            region = range_to_region(range, self.view)\n\n            phantoms.append(sublime.Phantom(region, content, sublime.LAYOUT_INLINE))\n\n        if phantoms:\n            if not self.color_phantom_set:\n                self.color_phantom_set = sublime.PhantomSet(self.view, \"lsp_color\")\n            self.color_phantom_set.update(phantoms)\n        else:\n            self.color_phantom_set = None\n\n\ndef remove_color_boxes(view):\n    view.erase_phantoms('lsp_color')\n", "path": "plugin/color.py"}], "after_files": [{"content": "import sublime_plugin\nimport sublime\n\ntry:\n    from typing import Any, List, Dict, Callable, Optional\n    assert Any and List and Dict and Callable and Optional\nexcept ImportError:\n    pass\n\nfrom .core.protocol import Request\nfrom .core.url import filename_to_uri\nfrom .core.registry import session_for_view, config_for_scope\nfrom .core.settings import settings, client_configs\nfrom .core.views import range_to_region\nfrom .core.protocol import Range\nfrom .core.configurations import is_supported_syntax\nfrom .core.documents import is_transient_view\n\n\nclass LspColorListener(sublime_plugin.ViewEventListener):\n    def __init__(self, view: sublime.View) -> None:\n        super().__init__(view)\n        self.color_phantom_set = None  # type: Optional[sublime.PhantomSet]\n        self._stored_point = -1\n        self.initialized = False\n        self.enabled = False\n\n    @classmethod\n    def is_applicable(cls, _settings):\n        syntax = _settings.get('syntax')\n        is_supported = syntax and is_supported_syntax(syntax, client_configs.all)\n        disabled_by_user = 'colorProvider' in settings.disabled_capabilities\n        return is_supported and not disabled_by_user\n\n    def on_activated_async(self):\n        if not self.initialized:\n            self.initialize()\n\n    def initialize(self, is_retry=False):\n        config = config_for_scope(self.view)\n        if not config:\n            self.initialized = True  # no server enabled, re-open file to activate feature.\n\n        session = session_for_view(self.view)\n        if session:\n            self.initialized = True\n            self.enabled = session.has_capability('colorProvider')\n            if self.enabled:\n                self.send_color_request()\n        elif not is_retry:\n            # session may be starting, try again once in a second.\n            sublime.set_timeout_async(lambda: self.initialize(is_retry=True), 1000)\n        else:\n            self.initialized = True  # we retried but still no session available.\n\n    def on_modified_async(self):\n        if self.enabled:\n            self.schedule_request()\n\n    def schedule_request(self):\n        sel = self.view.sel()\n        if len(sel) < 1:\n            return\n\n        current_point = sel[0].begin()\n        if self._stored_point != current_point:\n            self._stored_point = current_point\n            sublime.set_timeout_async(lambda: self.fire_request(current_point), 800)\n\n    def fire_request(self, current_point: int) -> None:\n        if current_point == self._stored_point:\n            self.send_color_request()\n\n    def send_color_request(self):\n        if is_transient_view(self.view):\n            return\n\n        session = session_for_view(self.view)\n        if not session:\n            return\n\n        params = {\n            \"textDocument\": {\n                \"uri\": filename_to_uri(self.view.file_name())\n            }\n        }\n        session.client.send_request(\n            Request.documentColor(params),\n            self.handle_response\n        )\n\n    def handle_response(self, response) -> None:\n        phantoms = []\n        for val in response:\n            color = val['color']\n            red = color['red'] * 255\n            green = color['green'] * 255\n            blue = color['blue'] * 255\n            alpha = color['alpha']\n\n            content = \"\"\"\n            <div style='padding: 0.4em;\n                        margin-top: 0.2em;\n                        border: 1px solid color(var(--foreground) alpha(0.25));\n                        background-color: rgba({}, {}, {}, {})'>\n            </div>\"\"\".format(red, green, blue, alpha)\n\n            range = Range.from_lsp(val['range'])\n            region = range_to_region(range, self.view)\n\n            phantoms.append(sublime.Phantom(region, content, sublime.LAYOUT_INLINE))\n\n        if phantoms:\n            if not self.color_phantom_set:\n                self.color_phantom_set = sublime.PhantomSet(self.view, \"lsp_color\")\n            self.color_phantom_set.update(phantoms)\n        else:\n            self.color_phantom_set = None\n\n\ndef remove_color_boxes(view):\n    view.erase_phantoms('lsp_color')\n", "path": "plugin/color.py"}]}