We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
'Window' object has no attribute 'children'
<!--- Provide a general summary of the issue in the Title above -->
<!--- If you have a question along the lines of "How do I do this Bash command in xonsh"
please first look over the Bash to Xonsh translation guide: https://xon.sh/bash_to_xsh.html
If you don't find an answer there, please do open an issue! -->

## xonfig

<details>

```
+------------------+----------------------+
| xonsh            | 0.9.24               |
| Git SHA          | 74543ea9             |
| Commit Date      | Oct 10 15:12:47 2020 |
| Python           | 3.8.6                |
| PLY              | 3.11                 |
| have readline    | True                 |
| prompt toolkit   | 3.0.3                |
| shell type       | prompt_toolkit       |
| pygments         | 2.7.2                |
| on posix         | True                 |
| on linux         | True                 |
| distro           | manjaro              |
| on darwin        | False                |
| on windows       | False                |
| on cygwin        | False                |
| on msys2         | False                |
| is superuser     | False                |
| default encoding | utf-8                |
| xonsh encoding   | utf-8                |
| encoding errors  | surrogateescape      |
| on jupyter       | False                |
| jupyter kernel   | None                 |
| xontrib 1        | abbrevs              |
| xontrib 2        | argcomplete          |
| xontrib 3        | autovox              |
| xontrib 4        | back2dir             |
| xontrib 5        | cmd_done             |
| xontrib 6        | hist_navigator       |
| xontrib 7        | jedi                 |
| xontrib 8        | kitty                |
| xontrib 9        | pdb                  |
| xontrib 10       | prompt_ret_code      |
| xontrib 11       | vox                  |
| xontrib 12       | voxapi               |
+------------------+----------------------+
```

</details>

## Expected Behavior
interactive shell runs without any error

## Current Behavior
<!--- Tell us what happens instead of the expected behavior -->
<!--- If part of your bug report is a traceback, please first enter debug mode before triggering the error
To enter debug mode, set the environment variable `XONSH_DEBUG=1` _before_ starting `xonsh`.
On Linux and OSX, an easy way to to do this is to run `env XONSH_DEBUG=1 xonsh` -->
I get the above error randomly when `$UPDATE_COMPLETIONS_ON_KEYPRESS = True`

### Traceback (if applicable)

<details>

```
2020-11-08 22:06:05.995 | INFO     | xonsh.ptk_shell.completer:reserve_space:118 - 8735829483909
2020-11-08 22:06:06.000 | ERROR    | xonsh.ptk_shell.completer:reserve_space:126 - 'Window' object has no attribute 'children'
Traceback (most recent call last):

  File "/usr/lib/python3.8/threading.py", line 890, in _bootstrap
    self._bootstrap_inner()
    │    └ <function Thread._bootstrap_inner at 0x7f1f895e01f0>
    └ <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
    │    └ <function Thread.run at 0x7f1f895dfee0>
    └ <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
    │    │        │    │        │    └ {}
    │    │        │    │        └ <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>
    │    │        │    └ (<weakref at 0x7f1f803ed270; to 'ThreadPoolExecutor' at 0x7f1f81e857c0>, <_queue.SimpleQueue object at 0x7f1f82a8b2c0>, None,...
    │    │        └ <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>
    │    └ <function _worker at 0x7f1f81edb670>
    └ <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>
  File "/usr/lib/python3.8/concurrent/futures/thread.py", line 80, in _worker
    work_item.run()
    │         └ <function _WorkItem.run at 0x7f1f81edb790>
    └ <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>
  File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
             │    │   │    │       │    └ {}
             │    │   │    │       └ <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>
             │    │   │    └ [<function generator_to_async_generator.<locals>.runner at 0x7f1f81f13e50>]
             │    │   └ <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>
             │    └ <built-in method run of Context object at 0x7f1f8039c9c0>
             └ <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>
  File "/home/noor/.config/xonsh/.venv/lib/python3.8/site-packages/prompt_toolkit/eventloop/async_generator.py", line 43, in runner
    for item in get_iterable():
                └ <function ThreadedCompleter.get_completions_async.<locals>.<lambda> at 0x7f1f81f13ee0>

  File "/home/noor/.config/xonsh/xsh-src/xonsh/ptk_shell/completer.py", line 73, in get_completions
    self.reserve_space()
    │    └ <function PromptToolkitCompleter.reserve_space at 0x7f1f82aa4430>
    └ <xonsh.ptk_shell.completer.PromptToolkitCompleter object at 0x7f1f82aed8e0>

> File "/home/noor/.config/xonsh/xsh-src/xonsh/ptk_shell/completer.py", line 123, in reserve_space
    hash(app.layout.container.children[0].content.children[1].content)
         │   │      └ Window(content=FormattedTextControl(HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.')))
         │   └ Layout(Window(content=FormattedTextControl(HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'))), current_wi...
         └ <prompt_toolkit.application.dummy.DummyApplication object at 0x7f1f803eb8b0>

AttributeError: 'Window' object has no attribute 'children'

```

</details>

## Steps to Reproduce
<!--- Please try to write out a minimal reproducible snippet to trigger the bug, it will help us fix it! -->
1. it happens randomly. sometime doing simple `ls -a` triggers the error

## For community
⬇️  **Please click the 👍 reaction instead of leaving a `+1` or 👍  comment**


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `xonsh/ptk_shell/completer.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """Completer implementation to use with prompt_toolkit."""
3 import os
4 import builtins
5 
6 from prompt_toolkit.completion import Completer, Completion
7 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
8 from prompt_toolkit.application.current import get_app
9 
10 from xonsh.completers.tools import RichCompletion
11 
12 
13 class PromptToolkitCompleter(Completer):
14     """Simple prompt_toolkit Completer object.
15 
16     It just redirects requests to normal Xonsh completer.
17     """
18 
19     def __init__(self, completer, ctx, shell):
20         """Takes instance of xonsh.completer.Completer, the xonsh execution
21         context, and the shell instance itself.
22         """
23         self.completer = completer
24         self.ctx = ctx
25         self.shell = shell
26         self.hist_suggester = AutoSuggestFromHistory()
27         self.current_document = None
28 
29     def get_completions(self, document, complete_event):
30         """Returns a generator for list of completions."""
31         env = builtins.__xonsh__.env
32         should_complete = complete_event.completion_requested or env.get(
33             "UPDATE_COMPLETIONS_ON_KEYPRESS"
34         )
35         #  Only generate completions when the user hits tab.
36         if not should_complete or self.completer is None:
37             return
38         # generate actual completions
39         line = document.current_line.lstrip()
40         line_ex = builtins.aliases.expand_alias(line)
41 
42         endidx = document.cursor_position_col
43         begidx = line[:endidx].rfind(" ") + 1 if line[:endidx].rfind(" ") >= 0 else 0
44         prefix = line[begidx:endidx]
45         expand_offset = len(line_ex) - len(line)
46 
47         # enable completers to access entire document
48         self.current_document = document
49 
50         # get normal completions
51         completions, l = self.completer.complete(
52             prefix, line_ex, begidx + expand_offset, endidx + expand_offset, self.ctx
53         )
54 
55         self.current_document = None
56 
57         # completions from auto suggest
58         sug_comp = None
59         if env.get("AUTO_SUGGEST") and env.get("AUTO_SUGGEST_IN_COMPLETIONS"):
60             sug_comp = self.suggestion_completion(document, line)
61             if sug_comp is None:
62                 pass
63             elif len(completions) == 0:
64                 completions = (sug_comp,)
65             else:
66                 completions = set(completions)
67                 completions.discard(sug_comp)
68                 completions = (sug_comp,) + tuple(sorted(completions))
69         # reserve space, if needed.
70         if len(completions) <= 1:
71             pass
72         elif len(os.path.commonprefix(completions)) <= len(prefix):
73             self.reserve_space()
74         # Find common prefix (strip quoting)
75         c_prefix = os.path.commonprefix([a.strip("'\"") for a in completions])
76         # Find last split symbol, do not trim the last part
77         while c_prefix:
78             if c_prefix[-1] in r"/\.:@,":
79                 break
80             c_prefix = c_prefix[:-1]
81         # yield completions
82         if sug_comp is None:
83             pre = min(document.cursor_position_col - begidx, len(c_prefix))
84         else:
85             pre = len(c_prefix)
86         for comp in completions:
87             # do not display quote
88             if isinstance(comp, RichCompletion):
89                 yield Completion(
90                     comp,
91                     -comp.prefix_len if comp.prefix_len is not None else -l,
92                     display=comp.display,
93                     display_meta=comp.description or None,
94                 )
95             else:
96                 disp = comp[pre:].strip("'\"")
97                 yield Completion(comp, -l, display=disp)
98 
99     def suggestion_completion(self, document, line):
100         """Provides a completion based on the current auto-suggestion."""
101         app = self.shell.prompter.app
102         sug = self.hist_suggester.get_suggestion(app.current_buffer, document)
103         if sug is None:
104             return None
105         comp, _, _ = sug.text.partition(" ")
106         _, _, prev = line.rpartition(" ")
107         return prev + comp
108 
109     def reserve_space(self):
110         """Adjust the height for showing autocompletion menu."""
111         app = get_app()
112         render = app.renderer
113         window = app.layout.container.children[0].content.children[1].content
114 
115         if window and window.render_info:
116             h = window.render_info.content_height
117             r = builtins.__xonsh__.env.get("COMPLETIONS_MENU_ROWS")
118             size = h + r
119             last_h = render._last_screen.height if render._last_screen else 0
120             last_h = max(render._min_available_height, last_h)
121             if last_h < size:
122                 if render._last_screen:
123                     render._last_screen.height = size
124
```
--- 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/xonsh/ptk_shell/completer.py b/xonsh/ptk_shell/completer.py
--- a/xonsh/ptk_shell/completer.py
+++ b/xonsh/ptk_shell/completer.py
@@ -110,7 +110,7 @@
         """Adjust the height for showing autocompletion menu."""
         app = get_app()
         render = app.renderer
-        window = app.layout.container.children[0].content.children[1].content
+        window = app.layout.current_window
 
         if window and window.render_info:
             h = window.render_info.content_height

{"golden_diff": "diff --git a/xonsh/ptk_shell/completer.py b/xonsh/ptk_shell/completer.py\n--- a/xonsh/ptk_shell/completer.py\n+++ b/xonsh/ptk_shell/completer.py\n@@ -110,7 +110,7 @@\n         \"\"\"Adjust the height for showing autocompletion menu.\"\"\"\n         app = get_app()\n         render = app.renderer\n-        window = app.layout.container.children[0].content.children[1].content\n+        window = app.layout.current_window\n \n         if window and window.render_info:\n             h = window.render_info.content_height\n", "issue": "'Window' object has no attribute 'children'\n<!--- Provide a general summary of the issue in the Title above -->\r\n<!--- If you have a question along the lines of \"How do I do this Bash command in xonsh\"\r\nplease first look over the Bash to Xonsh translation guide: https://xon.sh/bash_to_xsh.html\r\nIf you don't find an answer there, please do open an issue! -->\r\n\r\n## xonfig\r\n\r\n<details>\r\n\r\n```\r\n+------------------+----------------------+\r\n| xonsh            | 0.9.24               |\r\n| Git SHA          | 74543ea9             |\r\n| Commit Date      | Oct 10 15:12:47 2020 |\r\n| Python           | 3.8.6                |\r\n| PLY              | 3.11                 |\r\n| have readline    | True                 |\r\n| prompt toolkit   | 3.0.3                |\r\n| shell type       | prompt_toolkit       |\r\n| pygments         | 2.7.2                |\r\n| on posix         | True                 |\r\n| on linux         | True                 |\r\n| distro           | manjaro              |\r\n| on darwin        | False                |\r\n| on windows       | False                |\r\n| on cygwin        | False                |\r\n| on msys2         | False                |\r\n| is superuser     | False                |\r\n| default encoding | utf-8                |\r\n| xonsh encoding   | utf-8                |\r\n| encoding errors  | surrogateescape      |\r\n| on jupyter       | False                |\r\n| jupyter kernel   | None                 |\r\n| xontrib 1        | abbrevs              |\r\n| xontrib 2        | argcomplete          |\r\n| xontrib 3        | autovox              |\r\n| xontrib 4        | back2dir             |\r\n| xontrib 5        | cmd_done             |\r\n| xontrib 6        | hist_navigator       |\r\n| xontrib 7        | jedi                 |\r\n| xontrib 8        | kitty                |\r\n| xontrib 9        | pdb                  |\r\n| xontrib 10       | prompt_ret_code      |\r\n| xontrib 11       | vox                  |\r\n| xontrib 12       | voxapi               |\r\n+------------------+----------------------+\r\n```\r\n\r\n</details>\r\n\r\n## Expected Behavior\r\ninteractive shell runs without any error\r\n\r\n## Current Behavior\r\n<!--- Tell us what happens instead of the expected behavior -->\r\n<!--- If part of your bug report is a traceback, please first enter debug mode before triggering the error\r\nTo enter debug mode, set the environment variable `XONSH_DEBUG=1` _before_ starting `xonsh`.\r\nOn Linux and OSX, an easy way to to do this is to run `env XONSH_DEBUG=1 xonsh` -->\r\nI get the above error randomly when `$UPDATE_COMPLETIONS_ON_KEYPRESS = True`\r\n\r\n### Traceback (if applicable)\r\n\r\n<details>\r\n\r\n```\r\n2020-11-08 22:06:05.995 | INFO     | xonsh.ptk_shell.completer:reserve_space:118 - 8735829483909\r\n2020-11-08 22:06:06.000 | ERROR    | xonsh.ptk_shell.completer:reserve_space:126 - 'Window' object has no attribute 'children'\r\nTraceback (most recent call last):\r\n\r\n  File \"/usr/lib/python3.8/threading.py\", line 890, in _bootstrap\r\n    self._bootstrap_inner()\r\n    \u2502    \u2514 <function Thread._bootstrap_inner at 0x7f1f895e01f0>\r\n    \u2514 <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>\r\n  File \"/usr/lib/python3.8/threading.py\", line 932, in _bootstrap_inner\r\n    self.run()\r\n    \u2502    \u2514 <function Thread.run at 0x7f1f895dfee0>\r\n    \u2514 <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>\r\n  File \"/usr/lib/python3.8/threading.py\", line 870, in run\r\n    self._target(*self._args, **self._kwargs)\r\n    \u2502    \u2502        \u2502    \u2502        \u2502    \u2514 {}\r\n    \u2502    \u2502        \u2502    \u2502        \u2514 <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>\r\n    \u2502    \u2502        \u2502    \u2514 (<weakref at 0x7f1f803ed270; to 'ThreadPoolExecutor' at 0x7f1f81e857c0>, <_queue.SimpleQueue object at 0x7f1f82a8b2c0>, None,...\r\n    \u2502    \u2502        \u2514 <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>\r\n    \u2502    \u2514 <function _worker at 0x7f1f81edb670>\r\n    \u2514 <Thread(ThreadPoolExecutor-1_0, started daemon 139773312693824)>\r\n  File \"/usr/lib/python3.8/concurrent/futures/thread.py\", line 80, in _worker\r\n    work_item.run()\r\n    \u2502         \u2514 <function _WorkItem.run at 0x7f1f81edb790>\r\n    \u2514 <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>\r\n  File \"/usr/lib/python3.8/concurrent/futures/thread.py\", line 57, in run\r\n    result = self.fn(*self.args, **self.kwargs)\r\n             \u2502    \u2502   \u2502    \u2502       \u2502    \u2514 {}\r\n             \u2502    \u2502   \u2502    \u2502       \u2514 <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>\r\n             \u2502    \u2502   \u2502    \u2514 [<function generator_to_async_generator.<locals>.runner at 0x7f1f81f13e50>]\r\n             \u2502    \u2502   \u2514 <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>\r\n             \u2502    \u2514 <built-in method run of Context object at 0x7f1f8039c9c0>\r\n             \u2514 <concurrent.futures.thread._WorkItem object at 0x7f1f803eb460>\r\n  File \"/home/noor/.config/xonsh/.venv/lib/python3.8/site-packages/prompt_toolkit/eventloop/async_generator.py\", line 43, in runner\r\n    for item in get_iterable():\r\n                \u2514 <function ThreadedCompleter.get_completions_async.<locals>.<lambda> at 0x7f1f81f13ee0>\r\n\r\n  File \"/home/noor/.config/xonsh/xsh-src/xonsh/ptk_shell/completer.py\", line 73, in get_completions\r\n    self.reserve_space()\r\n    \u2502    \u2514 <function PromptToolkitCompleter.reserve_space at 0x7f1f82aa4430>\r\n    \u2514 <xonsh.ptk_shell.completer.PromptToolkitCompleter object at 0x7f1f82aed8e0>\r\n\r\n> File \"/home/noor/.config/xonsh/xsh-src/xonsh/ptk_shell/completer.py\", line 123, in reserve_space\r\n    hash(app.layout.container.children[0].content.children[1].content)\r\n         \u2502   \u2502      \u2514 Window(content=FormattedTextControl(HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.')))\r\n         \u2502   \u2514 Layout(Window(content=FormattedTextControl(HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'))), current_wi...\r\n         \u2514 <prompt_toolkit.application.dummy.DummyApplication object at 0x7f1f803eb8b0>\r\n\r\nAttributeError: 'Window' object has no attribute 'children'\r\n\r\n```\r\n\r\n</details>\r\n\r\n## Steps to Reproduce\r\n<!--- Please try to write out a minimal reproducible snippet to trigger the bug, it will help us fix it! -->\r\n1. it happens randomly. sometime doing simple `ls -a` triggers the error\r\n\r\n## For community\r\n\u2b07\ufe0f  **Please click the \ud83d\udc4d reaction instead of leaving a `+1` or \ud83d\udc4d  comment**\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Completer implementation to use with prompt_toolkit.\"\"\"\nimport os\nimport builtins\n\nfrom prompt_toolkit.completion import Completer, Completion\nfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory\nfrom prompt_toolkit.application.current import get_app\n\nfrom xonsh.completers.tools import RichCompletion\n\n\nclass PromptToolkitCompleter(Completer):\n    \"\"\"Simple prompt_toolkit Completer object.\n\n    It just redirects requests to normal Xonsh completer.\n    \"\"\"\n\n    def __init__(self, completer, ctx, shell):\n        \"\"\"Takes instance of xonsh.completer.Completer, the xonsh execution\n        context, and the shell instance itself.\n        \"\"\"\n        self.completer = completer\n        self.ctx = ctx\n        self.shell = shell\n        self.hist_suggester = AutoSuggestFromHistory()\n        self.current_document = None\n\n    def get_completions(self, document, complete_event):\n        \"\"\"Returns a generator for list of completions.\"\"\"\n        env = builtins.__xonsh__.env\n        should_complete = complete_event.completion_requested or env.get(\n            \"UPDATE_COMPLETIONS_ON_KEYPRESS\"\n        )\n        #  Only generate completions when the user hits tab.\n        if not should_complete or self.completer is None:\n            return\n        # generate actual completions\n        line = document.current_line.lstrip()\n        line_ex = builtins.aliases.expand_alias(line)\n\n        endidx = document.cursor_position_col\n        begidx = line[:endidx].rfind(\" \") + 1 if line[:endidx].rfind(\" \") >= 0 else 0\n        prefix = line[begidx:endidx]\n        expand_offset = len(line_ex) - len(line)\n\n        # enable completers to access entire document\n        self.current_document = document\n\n        # get normal completions\n        completions, l = self.completer.complete(\n            prefix, line_ex, begidx + expand_offset, endidx + expand_offset, self.ctx\n        )\n\n        self.current_document = None\n\n        # completions from auto suggest\n        sug_comp = None\n        if env.get(\"AUTO_SUGGEST\") and env.get(\"AUTO_SUGGEST_IN_COMPLETIONS\"):\n            sug_comp = self.suggestion_completion(document, line)\n            if sug_comp is None:\n                pass\n            elif len(completions) == 0:\n                completions = (sug_comp,)\n            else:\n                completions = set(completions)\n                completions.discard(sug_comp)\n                completions = (sug_comp,) + tuple(sorted(completions))\n        # reserve space, if needed.\n        if len(completions) <= 1:\n            pass\n        elif len(os.path.commonprefix(completions)) <= len(prefix):\n            self.reserve_space()\n        # Find common prefix (strip quoting)\n        c_prefix = os.path.commonprefix([a.strip(\"'\\\"\") for a in completions])\n        # Find last split symbol, do not trim the last part\n        while c_prefix:\n            if c_prefix[-1] in r\"/\\.:@,\":\n                break\n            c_prefix = c_prefix[:-1]\n        # yield completions\n        if sug_comp is None:\n            pre = min(document.cursor_position_col - begidx, len(c_prefix))\n        else:\n            pre = len(c_prefix)\n        for comp in completions:\n            # do not display quote\n            if isinstance(comp, RichCompletion):\n                yield Completion(\n                    comp,\n                    -comp.prefix_len if comp.prefix_len is not None else -l,\n                    display=comp.display,\n                    display_meta=comp.description or None,\n                )\n            else:\n                disp = comp[pre:].strip(\"'\\\"\")\n                yield Completion(comp, -l, display=disp)\n\n    def suggestion_completion(self, document, line):\n        \"\"\"Provides a completion based on the current auto-suggestion.\"\"\"\n        app = self.shell.prompter.app\n        sug = self.hist_suggester.get_suggestion(app.current_buffer, document)\n        if sug is None:\n            return None\n        comp, _, _ = sug.text.partition(\" \")\n        _, _, prev = line.rpartition(\" \")\n        return prev + comp\n\n    def reserve_space(self):\n        \"\"\"Adjust the height for showing autocompletion menu.\"\"\"\n        app = get_app()\n        render = app.renderer\n        window = app.layout.container.children[0].content.children[1].content\n\n        if window and window.render_info:\n            h = window.render_info.content_height\n            r = builtins.__xonsh__.env.get(\"COMPLETIONS_MENU_ROWS\")\n            size = h + r\n            last_h = render._last_screen.height if render._last_screen else 0\n            last_h = max(render._min_available_height, last_h)\n            if last_h < size:\n                if render._last_screen:\n                    render._last_screen.height = size\n", "path": "xonsh/ptk_shell/completer.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"Completer implementation to use with prompt_toolkit.\"\"\"\nimport os\nimport builtins\n\nfrom prompt_toolkit.completion import Completer, Completion\nfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory\nfrom prompt_toolkit.application.current import get_app\n\nfrom xonsh.completers.tools import RichCompletion\n\n\nclass PromptToolkitCompleter(Completer):\n    \"\"\"Simple prompt_toolkit Completer object.\n\n    It just redirects requests to normal Xonsh completer.\n    \"\"\"\n\n    def __init__(self, completer, ctx, shell):\n        \"\"\"Takes instance of xonsh.completer.Completer, the xonsh execution\n        context, and the shell instance itself.\n        \"\"\"\n        self.completer = completer\n        self.ctx = ctx\n        self.shell = shell\n        self.hist_suggester = AutoSuggestFromHistory()\n        self.current_document = None\n\n    def get_completions(self, document, complete_event):\n        \"\"\"Returns a generator for list of completions.\"\"\"\n        env = builtins.__xonsh__.env\n        should_complete = complete_event.completion_requested or env.get(\n            \"UPDATE_COMPLETIONS_ON_KEYPRESS\"\n        )\n        #  Only generate completions when the user hits tab.\n        if not should_complete or self.completer is None:\n            return\n        # generate actual completions\n        line = document.current_line.lstrip()\n        line_ex = builtins.aliases.expand_alias(line)\n\n        endidx = document.cursor_position_col\n        begidx = line[:endidx].rfind(\" \") + 1 if line[:endidx].rfind(\" \") >= 0 else 0\n        prefix = line[begidx:endidx]\n        expand_offset = len(line_ex) - len(line)\n\n        # enable completers to access entire document\n        self.current_document = document\n\n        # get normal completions\n        completions, l = self.completer.complete(\n            prefix, line_ex, begidx + expand_offset, endidx + expand_offset, self.ctx\n        )\n\n        self.current_document = None\n\n        # completions from auto suggest\n        sug_comp = None\n        if env.get(\"AUTO_SUGGEST\") and env.get(\"AUTO_SUGGEST_IN_COMPLETIONS\"):\n            sug_comp = self.suggestion_completion(document, line)\n            if sug_comp is None:\n                pass\n            elif len(completions) == 0:\n                completions = (sug_comp,)\n            else:\n                completions = set(completions)\n                completions.discard(sug_comp)\n                completions = (sug_comp,) + tuple(sorted(completions))\n        # reserve space, if needed.\n        if len(completions) <= 1:\n            pass\n        elif len(os.path.commonprefix(completions)) <= len(prefix):\n            self.reserve_space()\n        # Find common prefix (strip quoting)\n        c_prefix = os.path.commonprefix([a.strip(\"'\\\"\") for a in completions])\n        # Find last split symbol, do not trim the last part\n        while c_prefix:\n            if c_prefix[-1] in r\"/\\.:@,\":\n                break\n            c_prefix = c_prefix[:-1]\n        # yield completions\n        if sug_comp is None:\n            pre = min(document.cursor_position_col - begidx, len(c_prefix))\n        else:\n            pre = len(c_prefix)\n        for comp in completions:\n            # do not display quote\n            if isinstance(comp, RichCompletion):\n                yield Completion(\n                    comp,\n                    -comp.prefix_len if comp.prefix_len is not None else -l,\n                    display=comp.display,\n                    display_meta=comp.description or None,\n                )\n            else:\n                disp = comp[pre:].strip(\"'\\\"\")\n                yield Completion(comp, -l, display=disp)\n\n    def suggestion_completion(self, document, line):\n        \"\"\"Provides a completion based on the current auto-suggestion.\"\"\"\n        app = self.shell.prompter.app\n        sug = self.hist_suggester.get_suggestion(app.current_buffer, document)\n        if sug is None:\n            return None\n        comp, _, _ = sug.text.partition(\" \")\n        _, _, prev = line.rpartition(\" \")\n        return prev + comp\n\n    def reserve_space(self):\n        \"\"\"Adjust the height for showing autocompletion menu.\"\"\"\n        app = get_app()\n        render = app.renderer\n        window = app.layout.current_window\n\n        if window and window.render_info:\n            h = window.render_info.content_height\n            r = builtins.__xonsh__.env.get(\"COMPLETIONS_MENU_ROWS\")\n            size = h + r\n            last_h = render._last_screen.height if render._last_screen else 0\n            last_h = max(render._min_available_height, last_h)\n            if last_h < size:\n                if render._last_screen:\n                    render._last_screen.height = size\n", "path": "xonsh/ptk_shell/completer.py"}]}