We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
BaseShell.settitle() uses os.system()
And [arguments are inserted without escaping](https://github.com/xonsh/xonsh/blob/2e5234da02b5b6590c21dd932bc50b8f614ade9f/xonsh/base_shell.py#L292). EDIT: It does escape, making them safe. Probably. Hopefully.

Additionally, this only works under CMD, not PowerShell.

My recommendation is to call [SetConsoleTitleW()](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686050%28v=vs.85%29.aspx) via [ctypes](https://docs.python.org/3/library/ctypes.html).


--- 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, print_exception,
10                          DefaultNotGiven, check_for_partial_string)
11 from xonsh.platform import HAS_PYGMENTS, ON_WINDOWS
12 from xonsh.codecache import (should_use_cache, code_cache_name,
13                              code_cache_check, get_cache_filename,
14                              update_cache, run_compiled_code)
15 from xonsh.completer import Completer
16 from xonsh.prompt.base import multiline_prompt, partial_format_prompt
17 from xonsh.events import events
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         self.errors = self.stdout.errors
28         sys.stdout = self
29 
30     def __del__(self):
31         sys.stdout = self.stdout
32 
33     def close(self):
34         """Restores the original stdout."""
35         sys.stdout = self.stdout
36 
37     def write(self, data):
38         """Writes data to the original stdout and the buffer."""
39         # data = data.replace('\001', '').replace('\002', '')
40         self.stdout.write(data)
41         self.buffer.write(data)
42 
43     def flush(self):
44         """Flushes both the original stdout and the buffer."""
45         self.stdout.flush()
46         self.buffer.flush()
47 
48     def fileno(self):
49         """Tunnel fileno() calls."""
50         return self.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         self.errors = self.stderr.errors
61         sys.stderr = self
62 
63     def __del__(self):
64         sys.stderr = self.stderr
65 
66     def close(self):
67         """Restores the original stderr."""
68         sys.stderr = self.stderr
69 
70     def write(self, data):
71         """Writes data to the original stderr and the buffer."""
72         # data = data.replace('\001', '').replace('\002', '')
73         self.stderr.write(data)
74         self.buffer.write(data)
75 
76     def flush(self):
77         """Flushes both the original stderr and the buffer."""
78         self.stderr.flush()
79         self.buffer.flush()
80 
81     def fileno(self):
82         """Tunnel fileno() calls."""
83         return self.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         self.completer = Completer() if kwargs.get('completer', True) else None
118         self.buffer = []
119         self.need_more_lines = False
120         self.mlprompt = None
121         self._styler = DefaultNotGiven
122 
123     @property
124     def styler(self):
125         if self._styler is DefaultNotGiven:
126             if HAS_PYGMENTS:
127                 from xonsh.pyghooks import XonshStyle
128                 env = builtins.__xonsh_env__
129                 self._styler = XonshStyle(env.get('XONSH_COLOR_STYLE'))
130             else:
131                 self._styler = None
132         return self._styler
133 
134     @styler.setter
135     def styler(self, value):
136         self._styler = value
137 
138     @styler.deleter
139     def styler(self):
140         self._styler = DefaultNotGiven
141 
142     def emptyline(self):
143         """Called when an empty line has been entered."""
144         self.need_more_lines = False
145         self.default('')
146 
147     def singleline(self, **kwargs):
148         """Reads a single line of input from the shell."""
149         msg = '{0} has not implemented singleline().'
150         raise RuntimeError(msg.format(self.__class__.__name__))
151 
152     def precmd(self, line):
153         """Called just before execution of line."""
154         return line if self.need_more_lines else line.lstrip()
155 
156     def default(self, line):
157         """Implements code execution."""
158         line = line if line.endswith('\n') else line + '\n'
159         src, code = self.push(line)
160         if code is None:
161             return
162 
163         events.on_precommand.fire(src)
164 
165         hist = builtins.__xonsh_history__  # pylint: disable=no-member
166         ts1 = None
167         store_stdout = builtins.__xonsh_env__.get('XONSH_STORE_STDOUT')  # pylint: disable=no-member
168         tee = Tee() if store_stdout else io.StringIO()
169         try:
170             ts0 = time.time()
171             run_compiled_code(code, self.ctx, None, 'single')
172             ts1 = time.time()
173             if hist.last_cmd_rtn is None:
174                 hist.last_cmd_rtn = 0  # returncode for success
175         except XonshError as e:
176             print(e.args[0], file=sys.stderr)
177             if hist.last_cmd_rtn is None:
178                 hist.last_cmd_rtn = 1  # return code for failure
179         except Exception:  # pylint: disable=broad-except
180             print_exception()
181             if hist.last_cmd_rtn is None:
182                 hist.last_cmd_rtn = 1  # return code for failure
183         finally:
184             ts1 = ts1 or time.time()
185             self._append_history(inp=src, ts=[ts0, ts1], tee_out=tee.getvalue())
186             tee.close()
187 
188             self._fix_cwd()
189         if builtins.__xonsh_exit__:  # pylint: disable=no-member
190             return True
191 
192     def _append_history(self, tee_out=None, **info):
193         """
194         Append information about the command to the history.
195 
196         (Also handles on_postcommand because this is the place where all the information is available)
197         """
198         hist = builtins.__xonsh_history__  # pylint: disable=no-member
199         info['rtn'] = hist.last_cmd_rtn
200         tee_out = tee_out or None
201         last_out = hist.last_cmd_out or None
202         if last_out is None and tee_out is None:
203             pass
204         elif last_out is None and tee_out is not None:
205             info['out'] = tee_out
206         elif last_out is not None and tee_out is None:
207             info['out'] = last_out
208         else:
209             info['out'] = tee_out + '\n' + last_out
210 
211         events.on_postcommand.fire(
212             info['inp'],
213             info['rtn'],
214             info.get('out', None),
215             info['ts']
216         )
217 
218         hist.append(info)
219         hist.last_cmd_rtn = hist.last_cmd_out = None
220 
221     def _fix_cwd(self):
222         """Check if the cwd changed out from under us"""
223         cwd = os.getcwd()
224         if cwd != builtins.__xonsh_env__.get('PWD'):
225             old = builtins.__xonsh_env__.get('PWD')             # working directory changed without updating $PWD
226             builtins.__xonsh_env__['PWD'] = cwd             # track it now
227             if old is not None:
228                 builtins.__xonsh_env__['OLDPWD'] = old      # and update $OLDPWD like dirstack.
229             events.on_chdir.fire(old, cwd)                  # fire event after cwd actually changed.
230 
231     def push(self, line):
232         """Pushes a line onto the buffer and compiles the code in a way that
233         enables multiline input.
234         """
235         code = None
236         self.buffer.append(line)
237         if self.need_more_lines:
238             return None, code
239         src = ''.join(self.buffer)
240         _cache = should_use_cache(self.execer, 'single')
241         if _cache:
242             codefname = code_cache_name(src)
243             cachefname = get_cache_filename(codefname, code=True)
244             usecache, code = code_cache_check(cachefname)
245             if usecache:
246                 self.reset_buffer()
247                 return src, code
248         try:
249             code = self.execer.compile(src,
250                                        mode='single',
251                                        glbs=self.ctx,
252                                        locs=None)
253             if _cache:
254                 update_cache(code, cachefname)
255             self.reset_buffer()
256         except SyntaxError:
257             partial_string_info = check_for_partial_string(src)
258             in_partial_string = (partial_string_info[0] is not None and
259                                  partial_string_info[1] is None)
260             if ((line == '\n' and not in_partial_string)):
261                 self.reset_buffer()
262                 print_exception()
263                 return src, None
264             self.need_more_lines = True
265         except Exception:  # pylint: disable=broad-except
266             self.reset_buffer()
267             print_exception()
268             return src, None
269         return src, code
270 
271     def reset_buffer(self):
272         """Resets the line buffer."""
273         self.buffer.clear()
274         self.need_more_lines = False
275         self.mlprompt = None
276 
277     def settitle(self):
278         """Sets terminal title."""
279         env = builtins.__xonsh_env__  # pylint: disable=no-member
280         term = env.get('TERM', None)
281         # Shells running in emacs sets TERM to "dumb" or "eterm-color".
282         # Do not set title for these to avoid garbled prompt.
283         if (term is None and not ON_WINDOWS) or term in ['dumb', 'eterm-color',
284                                                          'linux']:
285             return
286         t = env.get('TITLE')
287         if t is None:
288             return
289         t = partial_format_prompt(t)
290         if ON_WINDOWS and 'ANSICON' not in env:
291             t = escape_windows_cmd_string(t)
292             os.system('title {}'.format(t))
293         else:
294             with open(1, 'wb', closefd=False) as f:
295                 # prevent xonsh from answering interative questions
296                 # on the next command by writing the title
297                 f.write("\x1b]0;{0}\x07".format(t).encode())
298                 f.flush()
299 
300     @property
301     def prompt(self):
302         """Obtains the current prompt string."""
303         if self.need_more_lines:
304             if self.mlprompt is None:
305                 try:
306                     self.mlprompt = multiline_prompt()
307                 except Exception:  # pylint: disable=broad-except
308                     print_exception()
309                     self.mlprompt = '<multiline prompt error> '
310             return self.mlprompt
311         env = builtins.__xonsh_env__  # pylint: disable=no-member
312         p = env.get('PROMPT')
313         try:
314             p = partial_format_prompt(p)
315         except Exception:  # pylint: disable=broad-except
316             print_exception()
317         self.settitle()
318         return p
319 
320     def format_color(self, string, **kwargs):
321         """Formats the colors in a string. This base implmentation does not
322         actually do any coloring, but just returns the string directly.
323         """
324         return string
325 
326     def print_color(self, string, **kwargs):
327         """Prints a string in color. This base implmentation does not actually
328         do any coloring, but just prints the string directly.
329         """
330         if not isinstance(string, str):
331             string = ''.join([x for _, x in string])
332         print(string, **kwargs)
333 
334     def color_style_names(self):
335         """Returns an iterable of all available style names."""
336         return ()
337 
338     def color_style(self):
339         """Returns the current color map."""
340         return {}
341
```
--- 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
@@ -16,6 +16,11 @@
 from xonsh.prompt.base import multiline_prompt, partial_format_prompt
 from xonsh.events import events
 
+if ON_WINDOWS:
+    import ctypes
+    kernel32 = ctypes.windll.kernel32
+    kernel32.SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
+
 
 class _TeeOut(object):
     """Tees stdout into the original sys.stdout and another buffer."""
@@ -288,8 +293,7 @@
             return
         t = partial_format_prompt(t)
         if ON_WINDOWS and 'ANSICON' not in env:
-            t = escape_windows_cmd_string(t)
-            os.system('title {}'.format(t))
+            kernel32.SetConsoleTitleW(t)
         else:
             with open(1, 'wb', closefd=False) as f:
                 # prevent xonsh from answering interative questions

{"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@@ -16,6 +16,11 @@\n from xonsh.prompt.base import multiline_prompt, partial_format_prompt\n from xonsh.events import events\n \n+if ON_WINDOWS:\n+    import ctypes\n+    kernel32 = ctypes.windll.kernel32\n+    kernel32.SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]\n+\n \n class _TeeOut(object):\n     \"\"\"Tees stdout into the original sys.stdout and another buffer.\"\"\"\n@@ -288,8 +293,7 @@\n             return\n         t = partial_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+            kernel32.SetConsoleTitleW(t)\n         else:\n             with open(1, 'wb', closefd=False) as f:\n                 # prevent xonsh from answering interative questions\n", "issue": "BaseShell.settitle() uses os.system()\nAnd [arguments are inserted without escaping](https://github.com/xonsh/xonsh/blob/2e5234da02b5b6590c21dd932bc50b8f614ade9f/xonsh/base_shell.py#L292). EDIT: It does escape, making them safe. Probably. Hopefully.\n\nAdditionally, this only works under CMD, not PowerShell.\n\nMy recommendation is to call [SetConsoleTitleW()](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686050%28v=vs.85%29.aspx) via [ctypes](https://docs.python.org/3/library/ctypes.html).\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, print_exception,\n                         DefaultNotGiven, check_for_partial_string)\nfrom xonsh.platform import HAS_PYGMENTS, ON_WINDOWS\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.prompt.base import multiline_prompt, partial_format_prompt\nfrom xonsh.events import events\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        self.errors = self.stdout.errors\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        return self.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        self.errors = self.stderr.errors\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        return self.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        self.completer = Completer() if kwargs.get('completer', True) else None\n        self.buffer = []\n        self.need_more_lines = False\n        self.mlprompt = None\n        self._styler = DefaultNotGiven\n\n    @property\n    def styler(self):\n        if self._styler is DefaultNotGiven:\n            if HAS_PYGMENTS:\n                from xonsh.pyghooks import XonshStyle\n                env = builtins.__xonsh_env__\n                self._styler = XonshStyle(env.get('XONSH_COLOR_STYLE'))\n            else:\n                self._styler = None\n        return self._styler\n\n    @styler.setter\n    def styler(self, value):\n        self._styler = value\n\n    @styler.deleter\n    def styler(self):\n        self._styler = DefaultNotGiven\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\n        events.on_precommand.fire(src)\n\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\n            self._fix_cwd()\n        if builtins.__xonsh_exit__:  # pylint: disable=no-member\n            return True\n\n    def _append_history(self, tee_out=None, **info):\n        \"\"\"\n        Append information about the command to the history.\n\n        (Also handles on_postcommand because this is the place where all the information is available)\n        \"\"\"\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\n        events.on_postcommand.fire(\n            info['inp'],\n            info['rtn'],\n            info.get('out', None),\n            info['ts']\n        )\n\n        hist.append(info)\n        hist.last_cmd_rtn = hist.last_cmd_out = None\n\n    def _fix_cwd(self):\n        \"\"\"Check if the cwd changed out from under us\"\"\"\n        cwd = os.getcwd()\n        if cwd != builtins.__xonsh_env__.get('PWD'):\n            old = builtins.__xonsh_env__.get('PWD')             # working directory changed without updating $PWD\n            builtins.__xonsh_env__['PWD'] = cwd             # track it now\n            if old is not None:\n                builtins.__xonsh_env__['OLDPWD'] = old      # and update $OLDPWD like dirstack.\n            events.on_chdir.fire(old, cwd)                  # fire event after cwd actually changed.\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            partial_string_info = check_for_partial_string(src)\n            in_partial_string = (partial_string_info[0] is not None and\n                                 partial_string_info[1] is None)\n            if ((line == '\\n' and not in_partial_string)):\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        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 and not ON_WINDOWS) or term in ['dumb', 'eterm-color',\n                                                         'linux']:\n            return\n        t = env.get('TITLE')\n        if t is None:\n            return\n        t = partial_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            with open(1, 'wb', closefd=False) as f:\n                # prevent xonsh from answering interative questions\n                # on the next command by writing the title\n                f.write(\"\\x1b]0;{0}\\x07\".format(t).encode())\n                f.flush()\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 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, print_exception,\n                         DefaultNotGiven, check_for_partial_string)\nfrom xonsh.platform import HAS_PYGMENTS, ON_WINDOWS\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.prompt.base import multiline_prompt, partial_format_prompt\nfrom xonsh.events import events\n\nif ON_WINDOWS:\n    import ctypes\n    kernel32 = ctypes.windll.kernel32\n    kernel32.SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]\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        self.errors = self.stdout.errors\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        return self.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        self.errors = self.stderr.errors\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        return self.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        self.completer = Completer() if kwargs.get('completer', True) else None\n        self.buffer = []\n        self.need_more_lines = False\n        self.mlprompt = None\n        self._styler = DefaultNotGiven\n\n    @property\n    def styler(self):\n        if self._styler is DefaultNotGiven:\n            if HAS_PYGMENTS:\n                from xonsh.pyghooks import XonshStyle\n                env = builtins.__xonsh_env__\n                self._styler = XonshStyle(env.get('XONSH_COLOR_STYLE'))\n            else:\n                self._styler = None\n        return self._styler\n\n    @styler.setter\n    def styler(self, value):\n        self._styler = value\n\n    @styler.deleter\n    def styler(self):\n        self._styler = DefaultNotGiven\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\n        events.on_precommand.fire(src)\n\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\n            self._fix_cwd()\n        if builtins.__xonsh_exit__:  # pylint: disable=no-member\n            return True\n\n    def _append_history(self, tee_out=None, **info):\n        \"\"\"\n        Append information about the command to the history.\n\n        (Also handles on_postcommand because this is the place where all the information is available)\n        \"\"\"\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\n        events.on_postcommand.fire(\n            info['inp'],\n            info['rtn'],\n            info.get('out', None),\n            info['ts']\n        )\n\n        hist.append(info)\n        hist.last_cmd_rtn = hist.last_cmd_out = None\n\n    def _fix_cwd(self):\n        \"\"\"Check if the cwd changed out from under us\"\"\"\n        cwd = os.getcwd()\n        if cwd != builtins.__xonsh_env__.get('PWD'):\n            old = builtins.__xonsh_env__.get('PWD')             # working directory changed without updating $PWD\n            builtins.__xonsh_env__['PWD'] = cwd             # track it now\n            if old is not None:\n                builtins.__xonsh_env__['OLDPWD'] = old      # and update $OLDPWD like dirstack.\n            events.on_chdir.fire(old, cwd)                  # fire event after cwd actually changed.\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            partial_string_info = check_for_partial_string(src)\n            in_partial_string = (partial_string_info[0] is not None and\n                                 partial_string_info[1] is None)\n            if ((line == '\\n' and not in_partial_string)):\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        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 and not ON_WINDOWS) or term in ['dumb', 'eterm-color',\n                                                         'linux']:\n            return\n        t = env.get('TITLE')\n        if t is None:\n            return\n        t = partial_format_prompt(t)\n        if ON_WINDOWS and 'ANSICON' not in env:\n            kernel32.SetConsoleTitleW(t)\n        else:\n            with open(1, 'wb', closefd=False) as f:\n                # prevent xonsh from answering interative questions\n                # on the next command by writing the title\n                f.write(\"\\x1b]0;{0}\\x07\".format(t).encode())\n                f.flush()\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 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"}]}