We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Tab completion on __xonsh_shell__.shell. fails
[See this mailing list discussion.](https://groups.google.com/d/msgid/xonsh/eb9b3b50-33c0-4652-949b-f042ec160f78%40googlegroups.com?utm_medium=email&utm_source=footer) I think that this is caused by the coloring code being updated and something in the completions not taking this into account.


--- 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/base_shell.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """The base class for xonsh shell"""
3 import io
4 import os
5 import sys
6 import time
7 import builtins
8 
9 from xonsh.tools import XonshError, escape_windows_cmd_string, ON_WINDOWS, \
10     print_exception, HAVE_PYGMENTS
11 from xonsh.codecache import (should_use_cache, code_cache_name,
12                              code_cache_check, get_cache_filename,
13                              update_cache, run_compiled_code)
14 from xonsh.completer import Completer
15 from xonsh.environ import multiline_prompt, format_prompt
16 if HAVE_PYGMENTS:
17     from xonsh.pyghooks import XonshStyle
18 
19 
20 class _TeeOut(object):
21     """Tees stdout into the original sys.stdout and another buffer."""
22 
23     def __init__(self, buf):
24         self.buffer = buf
25         self.stdout = sys.stdout
26         self.encoding = self.stdout.encoding
27         sys.stdout = self
28 
29     def __del__(self):
30         sys.stdout = self.stdout
31 
32     def close(self):
33         """Restores the original stdout."""
34         sys.stdout = self.stdout
35 
36     def write(self, data):
37         """Writes data to the original stdout and the buffer."""
38         #data = data.replace('\001', '').replace('\002', '')
39         self.stdout.write(data)
40         self.buffer.write(data)
41 
42     def flush(self):
43         """Flushes both the original stdout and the buffer."""
44         self.stdout.flush()
45         self.buffer.flush()
46 
47     def fileno(self):
48         """Tunnel fileno() calls."""
49         _ = self
50         return sys.stdout.fileno()
51 
52 
53 class _TeeErr(object):
54     """Tees stderr into the original sys.stdout and another buffer."""
55 
56     def __init__(self, buf):
57         self.buffer = buf
58         self.stderr = sys.stderr
59         self.encoding = self.stderr.encoding
60         sys.stderr = self
61 
62     def __del__(self):
63         sys.stderr = self.stderr
64 
65     def close(self):
66         """Restores the original stderr."""
67         sys.stderr = self.stderr
68 
69     def write(self, data):
70         """Writes data to the original stderr and the buffer."""
71         #data = data.replace('\001', '').replace('\002', '')
72         self.stderr.write(data)
73         self.buffer.write(data)
74 
75     def flush(self):
76         """Flushes both the original stderr and the buffer."""
77         self.stderr.flush()
78         self.buffer.flush()
79 
80     def fileno(self):
81         """Tunnel fileno() calls."""
82         _ = self
83         return sys.stderr.fileno()
84 
85 
86 class Tee(io.StringIO):
87     """Class that merges tee'd stdout and stderr into a single buffer.
88 
89     This represents what a user would actually see on the command line.
90     """
91     # pylint is a stupid about counting public methods when using inheritance.
92     # pylint: disable=too-few-public-methods
93 
94     def __init__(self, *args, **kwargs):
95         super().__init__(*args, **kwargs)
96         self.stdout = _TeeOut(self)
97         self.stderr = _TeeErr(self)
98 
99     def __del__(self):
100         del self.stdout, self.stderr
101         super().__del__()
102 
103     def close(self):
104         """Closes the buffer as well as the stdout and stderr tees."""
105         self.stdout.close()
106         self.stderr.close()
107         super().close()
108 
109 
110 class BaseShell(object):
111     """The xonsh shell."""
112 
113     def __init__(self, execer, ctx, **kwargs):
114         super().__init__()
115         self.execer = execer
116         self.ctx = ctx
117         if kwargs.get('completer', True):
118             self.completer = Completer()
119         self.buffer = []
120         self.need_more_lines = False
121         self.mlprompt = None
122         if HAVE_PYGMENTS:
123             env = builtins.__xonsh_env__
124             self.styler = XonshStyle(env.get('XONSH_COLOR_STYLE'))
125         else:
126             self.styler = None
127 
128     def emptyline(self):
129         """Called when an empty line has been entered."""
130         self.need_more_lines = False
131         self.default('')
132 
133     def singleline(self, **kwargs):
134         """Reads a single line of input from the shell."""
135         msg = '{0} has not implemented singleline().'
136         raise RuntimeError(msg.format(self.__class__.__name__))
137 
138     def precmd(self, line):
139         """Called just before execution of line."""
140         return line if self.need_more_lines else line.lstrip()
141 
142     def default(self, line):
143         """Implements code execution."""
144         line = line if line.endswith('\n') else line + '\n'
145         src, code = self.push(line)
146         if code is None:
147             return
148         hist = builtins.__xonsh_history__  # pylint: disable=no-member
149         ts1 = None
150         store_stdout = builtins.__xonsh_env__.get('XONSH_STORE_STDOUT')  # pylint: disable=no-member
151         tee = Tee() if store_stdout else io.StringIO()
152         try:
153             ts0 = time.time()
154             run_compiled_code(code, self.ctx, None, 'single')
155             ts1 = time.time()
156             if hist.last_cmd_rtn is None:
157                 hist.last_cmd_rtn = 0  # returncode for success
158         except XonshError as e:
159             print(e.args[0], file=sys.stderr)
160             if hist.last_cmd_rtn is None:
161                 hist.last_cmd_rtn = 1  # return code for failure
162         except Exception:  # pylint: disable=broad-except
163             print_exception()
164             if hist.last_cmd_rtn is None:
165                 hist.last_cmd_rtn = 1  # return code for failure
166         finally:
167             ts1 = ts1 or time.time()
168             self._append_history(inp=src, ts=[ts0, ts1], tee_out=tee.getvalue())
169             tee.close()
170         if builtins.__xonsh_exit__:  # pylint: disable=no-member
171             return True
172 
173     def push(self, line):
174         """Pushes a line onto the buffer and compiles the code in a way that
175         enables multiline input.
176         """
177         code = None
178         self.buffer.append(line)
179         if self.need_more_lines:
180             return None, code
181         src = ''.join(self.buffer)
182         _cache = should_use_cache(self.execer, 'single')
183         if _cache:
184             codefname = code_cache_name(src)
185             cachefname = get_cache_filename(codefname, code=True)
186             usecache, code = code_cache_check(cachefname)
187             if usecache:
188                 self.reset_buffer()
189                 return src, code
190         try:
191             code = self.execer.compile(src,
192                                        mode='single',
193                                        glbs=self.ctx,
194                                        locs=None)
195             if _cache:
196                 update_cache(code, cachefname)
197             self.reset_buffer()
198         except SyntaxError:
199             if line == '\n':
200                 self.reset_buffer()
201                 print_exception()
202                 return src, None
203             self.need_more_lines = True
204         except Exception:  # pylint: disable=broad-except
205             self.reset_buffer()
206             print_exception()
207             return src, None
208         return src, code
209 
210     def reset_buffer(self):
211         """Resets the line buffer."""
212         self.buffer.clear()
213         self.need_more_lines = False
214         self.mlprompt = None
215 
216     def settitle(self):
217         """Sets terminal title."""
218         _ = self
219         env = builtins.__xonsh_env__  # pylint: disable=no-member
220         term = env.get('TERM', None)
221         # Shells running in emacs sets TERM to "dumb" or "eterm-color".
222         # Do not set title for these to avoid garbled prompt.
223         if term is None or term in ['dumb', 'eterm-color', 'linux']:
224             return
225         t = env.get('TITLE')
226         if t is None:
227             return
228         t = format_prompt(t)
229         if ON_WINDOWS and 'ANSICON' not in env:
230             t = escape_windows_cmd_string(t)
231             os.system('title {}'.format(t))
232         else:
233             os.write(1, "\x1b]2;{0}\x07".format(t).encode())
234 
235     @property
236     def prompt(self):
237         """Obtains the current prompt string."""
238         if self.need_more_lines:
239             if self.mlprompt is None:
240                 try:
241                     self.mlprompt = multiline_prompt()
242                 except Exception:  # pylint: disable=broad-except
243                     print_exception()
244                     self.mlprompt = '<multiline prompt error> '
245             return self.mlprompt
246         env = builtins.__xonsh_env__  # pylint: disable=no-member
247         p = env.get('PROMPT')
248         try:
249             p = format_prompt(p)
250         except Exception:  # pylint: disable=broad-except
251             print_exception()
252         self.settitle()
253         return p
254 
255     def _append_history(self, tee_out=None, **info):
256         """Append information about the command to the history."""
257         _ = self
258         hist = builtins.__xonsh_history__  # pylint: disable=no-member
259         info['rtn'] = hist.last_cmd_rtn
260         tee_out = tee_out or None
261         last_out = hist.last_cmd_out or None
262         if last_out is None and tee_out is None:
263             pass
264         elif last_out is None and tee_out is not None:
265             info['out'] = tee_out
266         elif last_out is not None and tee_out is None:
267             info['out'] = last_out
268         else:
269             info['out'] = tee_out + '\n' + last_out
270         hist.append(info)
271         hist.last_cmd_rtn = hist.last_cmd_out = None
272 
273     def format_color(self, string, **kwargs):
274         """Formats the colors in a string. This base implmentation does not
275         actually do any coloring, but just returns the string directly.
276         """
277         return string
278 
279     def print_color(self, string, **kwargs):
280         """Prints a string in color. This base implmentation does not actually
281         do any coloring, but just prints the string directly.
282         """
283         if not isinstance(string, str):
284             string = ''.join([x for _, x in string])
285         print(string, **kwargs)
286 
287     def color_style_names(self):
288         """Returns an iterable of all available style names."""
289         return ()
290 
291     def color_style(self):
292         """Returns the current color map."""
293         return {}
294
```
--- 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/base_shell.py b/xonsh/base_shell.py
--- a/xonsh/base_shell.py
+++ b/xonsh/base_shell.py
@@ -12,7 +12,7 @@
                              code_cache_check, get_cache_filename,
                              update_cache, run_compiled_code)
 from xonsh.completer import Completer
-from xonsh.environ import multiline_prompt, format_prompt
+from xonsh.environ import multiline_prompt, format_prompt, partial_format_prompt
 if HAVE_PYGMENTS:
     from xonsh.pyghooks import XonshStyle
 
@@ -246,7 +246,7 @@
         env = builtins.__xonsh_env__  # pylint: disable=no-member
         p = env.get('PROMPT')
         try:
-            p = format_prompt(p)
+            p = partial_format_prompt(p)
         except Exception:  # pylint: disable=broad-except
             print_exception()
         self.settitle()

{"golden_diff": "diff --git a/xonsh/base_shell.py b/xonsh/base_shell.py\n--- a/xonsh/base_shell.py\n+++ b/xonsh/base_shell.py\n@@ -12,7 +12,7 @@\n                              code_cache_check, get_cache_filename,\n                              update_cache, run_compiled_code)\n from xonsh.completer import Completer\n-from xonsh.environ import multiline_prompt, format_prompt\n+from xonsh.environ import multiline_prompt, format_prompt, partial_format_prompt\n if HAVE_PYGMENTS:\n     from xonsh.pyghooks import XonshStyle\n \n@@ -246,7 +246,7 @@\n         env = builtins.__xonsh_env__  # pylint: disable=no-member\n         p = env.get('PROMPT')\n         try:\n-            p = format_prompt(p)\n+            p = partial_format_prompt(p)\n         except Exception:  # pylint: disable=broad-except\n             print_exception()\n         self.settitle()\n", "issue": "Tab completion on __xonsh_shell__.shell. fails\n[See this mailing list discussion.](https://groups.google.com/d/msgid/xonsh/eb9b3b50-33c0-4652-949b-f042ec160f78%40googlegroups.com?utm_medium=email&utm_source=footer) I think that this is caused by the coloring code being updated and something in the completions not taking this into account.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"The base class for xonsh shell\"\"\"\nimport io\nimport os\nimport sys\nimport time\nimport builtins\n\nfrom xonsh.tools import XonshError, escape_windows_cmd_string, ON_WINDOWS, \\\n    print_exception, HAVE_PYGMENTS\nfrom xonsh.codecache import (should_use_cache, code_cache_name,\n                             code_cache_check, get_cache_filename,\n                             update_cache, run_compiled_code)\nfrom xonsh.completer import Completer\nfrom xonsh.environ import multiline_prompt, format_prompt\nif HAVE_PYGMENTS:\n    from xonsh.pyghooks import XonshStyle\n\n\nclass _TeeOut(object):\n    \"\"\"Tees stdout into the original sys.stdout and another buffer.\"\"\"\n\n    def __init__(self, buf):\n        self.buffer = buf\n        self.stdout = sys.stdout\n        self.encoding = self.stdout.encoding\n        sys.stdout = self\n\n    def __del__(self):\n        sys.stdout = self.stdout\n\n    def close(self):\n        \"\"\"Restores the original stdout.\"\"\"\n        sys.stdout = self.stdout\n\n    def write(self, data):\n        \"\"\"Writes data to the original stdout and the buffer.\"\"\"\n        #data = data.replace('\\001', '').replace('\\002', '')\n        self.stdout.write(data)\n        self.buffer.write(data)\n\n    def flush(self):\n        \"\"\"Flushes both the original stdout and the buffer.\"\"\"\n        self.stdout.flush()\n        self.buffer.flush()\n\n    def fileno(self):\n        \"\"\"Tunnel fileno() calls.\"\"\"\n        _ = self\n        return sys.stdout.fileno()\n\n\nclass _TeeErr(object):\n    \"\"\"Tees stderr into the original sys.stdout and another buffer.\"\"\"\n\n    def __init__(self, buf):\n        self.buffer = buf\n        self.stderr = sys.stderr\n        self.encoding = self.stderr.encoding\n        sys.stderr = self\n\n    def __del__(self):\n        sys.stderr = self.stderr\n\n    def close(self):\n        \"\"\"Restores the original stderr.\"\"\"\n        sys.stderr = self.stderr\n\n    def write(self, data):\n        \"\"\"Writes data to the original stderr and the buffer.\"\"\"\n        #data = data.replace('\\001', '').replace('\\002', '')\n        self.stderr.write(data)\n        self.buffer.write(data)\n\n    def flush(self):\n        \"\"\"Flushes both the original stderr and the buffer.\"\"\"\n        self.stderr.flush()\n        self.buffer.flush()\n\n    def fileno(self):\n        \"\"\"Tunnel fileno() calls.\"\"\"\n        _ = self\n        return sys.stderr.fileno()\n\n\nclass Tee(io.StringIO):\n    \"\"\"Class that merges tee'd stdout and stderr into a single buffer.\n\n    This represents what a user would actually see on the command line.\n    \"\"\"\n    # pylint is a stupid about counting public methods when using inheritance.\n    # pylint: disable=too-few-public-methods\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.stdout = _TeeOut(self)\n        self.stderr = _TeeErr(self)\n\n    def __del__(self):\n        del self.stdout, self.stderr\n        super().__del__()\n\n    def close(self):\n        \"\"\"Closes the buffer as well as the stdout and stderr tees.\"\"\"\n        self.stdout.close()\n        self.stderr.close()\n        super().close()\n\n\nclass BaseShell(object):\n    \"\"\"The xonsh shell.\"\"\"\n\n    def __init__(self, execer, ctx, **kwargs):\n        super().__init__()\n        self.execer = execer\n        self.ctx = ctx\n        if kwargs.get('completer', True):\n            self.completer = Completer()\n        self.buffer = []\n        self.need_more_lines = False\n        self.mlprompt = None\n        if HAVE_PYGMENTS:\n            env = builtins.__xonsh_env__\n            self.styler = XonshStyle(env.get('XONSH_COLOR_STYLE'))\n        else:\n            self.styler = None\n\n    def emptyline(self):\n        \"\"\"Called when an empty line has been entered.\"\"\"\n        self.need_more_lines = False\n        self.default('')\n\n    def singleline(self, **kwargs):\n        \"\"\"Reads a single line of input from the shell.\"\"\"\n        msg = '{0} has not implemented singleline().'\n        raise RuntimeError(msg.format(self.__class__.__name__))\n\n    def precmd(self, line):\n        \"\"\"Called just before execution of line.\"\"\"\n        return line if self.need_more_lines else line.lstrip()\n\n    def default(self, line):\n        \"\"\"Implements code execution.\"\"\"\n        line = line if line.endswith('\\n') else line + '\\n'\n        src, code = self.push(line)\n        if code is None:\n            return\n        hist = builtins.__xonsh_history__  # pylint: disable=no-member\n        ts1 = None\n        store_stdout = builtins.__xonsh_env__.get('XONSH_STORE_STDOUT')  # pylint: disable=no-member\n        tee = Tee() if store_stdout else io.StringIO()\n        try:\n            ts0 = time.time()\n            run_compiled_code(code, self.ctx, None, 'single')\n            ts1 = time.time()\n            if hist.last_cmd_rtn is None:\n                hist.last_cmd_rtn = 0  # returncode for success\n        except XonshError as e:\n            print(e.args[0], file=sys.stderr)\n            if hist.last_cmd_rtn is None:\n                hist.last_cmd_rtn = 1  # return code for failure\n        except Exception:  # pylint: disable=broad-except\n            print_exception()\n            if hist.last_cmd_rtn is None:\n                hist.last_cmd_rtn = 1  # return code for failure\n        finally:\n            ts1 = ts1 or time.time()\n            self._append_history(inp=src, ts=[ts0, ts1], tee_out=tee.getvalue())\n            tee.close()\n        if builtins.__xonsh_exit__:  # pylint: disable=no-member\n            return True\n\n    def push(self, line):\n        \"\"\"Pushes a line onto the buffer and compiles the code in a way that\n        enables multiline input.\n        \"\"\"\n        code = None\n        self.buffer.append(line)\n        if self.need_more_lines:\n            return None, code\n        src = ''.join(self.buffer)\n        _cache = should_use_cache(self.execer, 'single')\n        if _cache:\n            codefname = code_cache_name(src)\n            cachefname = get_cache_filename(codefname, code=True)\n            usecache, code = code_cache_check(cachefname)\n            if usecache:\n                self.reset_buffer()\n                return src, code\n        try:\n            code = self.execer.compile(src,\n                                       mode='single',\n                                       glbs=self.ctx,\n                                       locs=None)\n            if _cache:\n                update_cache(code, cachefname)\n            self.reset_buffer()\n        except SyntaxError:\n            if line == '\\n':\n                self.reset_buffer()\n                print_exception()\n                return src, None\n            self.need_more_lines = True\n        except Exception:  # pylint: disable=broad-except\n            self.reset_buffer()\n            print_exception()\n            return src, None\n        return src, code\n\n    def reset_buffer(self):\n        \"\"\"Resets the line buffer.\"\"\"\n        self.buffer.clear()\n        self.need_more_lines = False\n        self.mlprompt = None\n\n    def settitle(self):\n        \"\"\"Sets terminal title.\"\"\"\n        _ = self\n        env = builtins.__xonsh_env__  # pylint: disable=no-member\n        term = env.get('TERM', None)\n        # Shells running in emacs sets TERM to \"dumb\" or \"eterm-color\".\n        # Do not set title for these to avoid garbled prompt.\n        if term is None or term in ['dumb', 'eterm-color', 'linux']:\n            return\n        t = env.get('TITLE')\n        if t is None:\n            return\n        t = format_prompt(t)\n        if ON_WINDOWS and 'ANSICON' not in env:\n            t = escape_windows_cmd_string(t)\n            os.system('title {}'.format(t))\n        else:\n            os.write(1, \"\\x1b]2;{0}\\x07\".format(t).encode())\n\n    @property\n    def prompt(self):\n        \"\"\"Obtains the current prompt string.\"\"\"\n        if self.need_more_lines:\n            if self.mlprompt is None:\n                try:\n                    self.mlprompt = multiline_prompt()\n                except Exception:  # pylint: disable=broad-except\n                    print_exception()\n                    self.mlprompt = '<multiline prompt error> '\n            return self.mlprompt\n        env = builtins.__xonsh_env__  # pylint: disable=no-member\n        p = env.get('PROMPT')\n        try:\n            p = format_prompt(p)\n        except Exception:  # pylint: disable=broad-except\n            print_exception()\n        self.settitle()\n        return p\n\n    def _append_history(self, tee_out=None, **info):\n        \"\"\"Append information about the command to the history.\"\"\"\n        _ = self\n        hist = builtins.__xonsh_history__  # pylint: disable=no-member\n        info['rtn'] = hist.last_cmd_rtn\n        tee_out = tee_out or None\n        last_out = hist.last_cmd_out or None\n        if last_out is None and tee_out is None:\n            pass\n        elif last_out is None and tee_out is not None:\n            info['out'] = tee_out\n        elif last_out is not None and tee_out is None:\n            info['out'] = last_out\n        else:\n            info['out'] = tee_out + '\\n' + last_out\n        hist.append(info)\n        hist.last_cmd_rtn = hist.last_cmd_out = None\n\n    def format_color(self, string, **kwargs):\n        \"\"\"Formats the colors in a string. This base implmentation does not\n        actually do any coloring, but just returns the string directly.\n        \"\"\"\n        return string\n\n    def print_color(self, string, **kwargs):\n        \"\"\"Prints a string in color. This base implmentation does not actually\n        do any coloring, but just prints the string directly.\n        \"\"\"\n        if not isinstance(string, str):\n            string = ''.join([x for _, x in string])\n        print(string, **kwargs)\n\n    def color_style_names(self):\n        \"\"\"Returns an iterable of all available style names.\"\"\"\n        return ()\n\n    def color_style(self):\n        \"\"\"Returns the current color map.\"\"\"\n        return {}\n", "path": "xonsh/base_shell.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"The base class for xonsh shell\"\"\"\nimport io\nimport os\nimport sys\nimport time\nimport builtins\n\nfrom xonsh.tools import XonshError, escape_windows_cmd_string, ON_WINDOWS, \\\n    print_exception, HAVE_PYGMENTS\nfrom xonsh.codecache import (should_use_cache, code_cache_name,\n                             code_cache_check, get_cache_filename,\n                             update_cache, run_compiled_code)\nfrom xonsh.completer import Completer\nfrom xonsh.environ import multiline_prompt, format_prompt, partial_format_prompt\nif HAVE_PYGMENTS:\n    from xonsh.pyghooks import XonshStyle\n\n\nclass _TeeOut(object):\n    \"\"\"Tees stdout into the original sys.stdout and another buffer.\"\"\"\n\n    def __init__(self, buf):\n        self.buffer = buf\n        self.stdout = sys.stdout\n        self.encoding = self.stdout.encoding\n        sys.stdout = self\n\n    def __del__(self):\n        sys.stdout = self.stdout\n\n    def close(self):\n        \"\"\"Restores the original stdout.\"\"\"\n        sys.stdout = self.stdout\n\n    def write(self, data):\n        \"\"\"Writes data to the original stdout and the buffer.\"\"\"\n        #data = data.replace('\\001', '').replace('\\002', '')\n        self.stdout.write(data)\n        self.buffer.write(data)\n\n    def flush(self):\n        \"\"\"Flushes both the original stdout and the buffer.\"\"\"\n        self.stdout.flush()\n        self.buffer.flush()\n\n    def fileno(self):\n        \"\"\"Tunnel fileno() calls.\"\"\"\n        _ = self\n        return sys.stdout.fileno()\n\n\nclass _TeeErr(object):\n    \"\"\"Tees stderr into the original sys.stdout and another buffer.\"\"\"\n\n    def __init__(self, buf):\n        self.buffer = buf\n        self.stderr = sys.stderr\n        self.encoding = self.stderr.encoding\n        sys.stderr = self\n\n    def __del__(self):\n        sys.stderr = self.stderr\n\n    def close(self):\n        \"\"\"Restores the original stderr.\"\"\"\n        sys.stderr = self.stderr\n\n    def write(self, data):\n        \"\"\"Writes data to the original stderr and the buffer.\"\"\"\n        #data = data.replace('\\001', '').replace('\\002', '')\n        self.stderr.write(data)\n        self.buffer.write(data)\n\n    def flush(self):\n        \"\"\"Flushes both the original stderr and the buffer.\"\"\"\n        self.stderr.flush()\n        self.buffer.flush()\n\n    def fileno(self):\n        \"\"\"Tunnel fileno() calls.\"\"\"\n        _ = self\n        return sys.stderr.fileno()\n\n\nclass Tee(io.StringIO):\n    \"\"\"Class that merges tee'd stdout and stderr into a single buffer.\n\n    This represents what a user would actually see on the command line.\n    \"\"\"\n    # pylint is a stupid about counting public methods when using inheritance.\n    # pylint: disable=too-few-public-methods\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.stdout = _TeeOut(self)\n        self.stderr = _TeeErr(self)\n\n    def __del__(self):\n        del self.stdout, self.stderr\n        super().__del__()\n\n    def close(self):\n        \"\"\"Closes the buffer as well as the stdout and stderr tees.\"\"\"\n        self.stdout.close()\n        self.stderr.close()\n        super().close()\n\n\nclass BaseShell(object):\n    \"\"\"The xonsh shell.\"\"\"\n\n    def __init__(self, execer, ctx, **kwargs):\n        super().__init__()\n        self.execer = execer\n        self.ctx = ctx\n        if kwargs.get('completer', True):\n            self.completer = Completer()\n        self.buffer = []\n        self.need_more_lines = False\n        self.mlprompt = None\n        if HAVE_PYGMENTS:\n            env = builtins.__xonsh_env__\n            self.styler = XonshStyle(env.get('XONSH_COLOR_STYLE'))\n        else:\n            self.styler = None\n\n    def emptyline(self):\n        \"\"\"Called when an empty line has been entered.\"\"\"\n        self.need_more_lines = False\n        self.default('')\n\n    def singleline(self, **kwargs):\n        \"\"\"Reads a single line of input from the shell.\"\"\"\n        msg = '{0} has not implemented singleline().'\n        raise RuntimeError(msg.format(self.__class__.__name__))\n\n    def precmd(self, line):\n        \"\"\"Called just before execution of line.\"\"\"\n        return line if self.need_more_lines else line.lstrip()\n\n    def default(self, line):\n        \"\"\"Implements code execution.\"\"\"\n        line = line if line.endswith('\\n') else line + '\\n'\n        src, code = self.push(line)\n        if code is None:\n            return\n        hist = builtins.__xonsh_history__  # pylint: disable=no-member\n        ts1 = None\n        store_stdout = builtins.__xonsh_env__.get('XONSH_STORE_STDOUT')  # pylint: disable=no-member\n        tee = Tee() if store_stdout else io.StringIO()\n        try:\n            ts0 = time.time()\n            run_compiled_code(code, self.ctx, None, 'single')\n            ts1 = time.time()\n            if hist.last_cmd_rtn is None:\n                hist.last_cmd_rtn = 0  # returncode for success\n        except XonshError as e:\n            print(e.args[0], file=sys.stderr)\n            if hist.last_cmd_rtn is None:\n                hist.last_cmd_rtn = 1  # return code for failure\n        except Exception:  # pylint: disable=broad-except\n            print_exception()\n            if hist.last_cmd_rtn is None:\n                hist.last_cmd_rtn = 1  # return code for failure\n        finally:\n            ts1 = ts1 or time.time()\n            self._append_history(inp=src, ts=[ts0, ts1], tee_out=tee.getvalue())\n            tee.close()\n        if builtins.__xonsh_exit__:  # pylint: disable=no-member\n            return True\n\n    def push(self, line):\n        \"\"\"Pushes a line onto the buffer and compiles the code in a way that\n        enables multiline input.\n        \"\"\"\n        code = None\n        self.buffer.append(line)\n        if self.need_more_lines:\n            return None, code\n        src = ''.join(self.buffer)\n        _cache = should_use_cache(self.execer, 'single')\n        if _cache:\n            codefname = code_cache_name(src)\n            cachefname = get_cache_filename(codefname, code=True)\n            usecache, code = code_cache_check(cachefname)\n            if usecache:\n                self.reset_buffer()\n                return src, code\n        try:\n            code = self.execer.compile(src,\n                                       mode='single',\n                                       glbs=self.ctx,\n                                       locs=None)\n            if _cache:\n                update_cache(code, cachefname)\n            self.reset_buffer()\n        except SyntaxError:\n            if line == '\\n':\n                self.reset_buffer()\n                print_exception()\n                return src, None\n            self.need_more_lines = True\n        except Exception:  # pylint: disable=broad-except\n            self.reset_buffer()\n            print_exception()\n            return src, None\n        return src, code\n\n    def reset_buffer(self):\n        \"\"\"Resets the line buffer.\"\"\"\n        self.buffer.clear()\n        self.need_more_lines = False\n        self.mlprompt = None\n\n    def settitle(self):\n        \"\"\"Sets terminal title.\"\"\"\n        _ = self\n        env = builtins.__xonsh_env__  # pylint: disable=no-member\n        term = env.get('TERM', None)\n        # Shells running in emacs sets TERM to \"dumb\" or \"eterm-color\".\n        # Do not set title for these to avoid garbled prompt.\n        if term is None or term in ['dumb', 'eterm-color', 'linux']:\n            return\n        t = env.get('TITLE')\n        if t is None:\n            return\n        t = format_prompt(t)\n        if ON_WINDOWS and 'ANSICON' not in env:\n            t = escape_windows_cmd_string(t)\n            os.system('title {}'.format(t))\n        else:\n            os.write(1, \"\\x1b]2;{0}\\x07\".format(t).encode())\n\n    @property\n    def prompt(self):\n        \"\"\"Obtains the current prompt string.\"\"\"\n        if self.need_more_lines:\n            if self.mlprompt is None:\n                try:\n                    self.mlprompt = multiline_prompt()\n                except Exception:  # pylint: disable=broad-except\n                    print_exception()\n                    self.mlprompt = '<multiline prompt error> '\n            return self.mlprompt\n        env = builtins.__xonsh_env__  # pylint: disable=no-member\n        p = env.get('PROMPT')\n        try:\n            p = partial_format_prompt(p)\n        except Exception:  # pylint: disable=broad-except\n            print_exception()\n        self.settitle()\n        return p\n\n    def _append_history(self, tee_out=None, **info):\n        \"\"\"Append information about the command to the history.\"\"\"\n        _ = self\n        hist = builtins.__xonsh_history__  # pylint: disable=no-member\n        info['rtn'] = hist.last_cmd_rtn\n        tee_out = tee_out or None\n        last_out = hist.last_cmd_out or None\n        if last_out is None and tee_out is None:\n            pass\n        elif last_out is None and tee_out is not None:\n            info['out'] = tee_out\n        elif last_out is not None and tee_out is None:\n            info['out'] = last_out\n        else:\n            info['out'] = tee_out + '\\n' + last_out\n        hist.append(info)\n        hist.last_cmd_rtn = hist.last_cmd_out = None\n\n    def format_color(self, string, **kwargs):\n        \"\"\"Formats the colors in a string. This base implmentation does not\n        actually do any coloring, but just returns the string directly.\n        \"\"\"\n        return string\n\n    def print_color(self, string, **kwargs):\n        \"\"\"Prints a string in color. This base implmentation does not actually\n        do any coloring, but just prints the string directly.\n        \"\"\"\n        if not isinstance(string, str):\n            string = ''.join([x for _, x in string])\n        print(string, **kwargs)\n\n    def color_style_names(self):\n        \"\"\"Returns an iterable of all available style names.\"\"\"\n        return ()\n\n    def color_style(self):\n        \"\"\"Returns the current color map.\"\"\"\n        return {}\n", "path": "xonsh/base_shell.py"}]}