Merge branch 'master' of https://github.com/xonsh/xonsh into no_welcome_norc

This commit is contained in:
a 2020-10-06 22:43:36 +03:00
commit 81a03b39f8
29 changed files with 273 additions and 131 deletions

2
.gitattributes vendored
View file

@ -12,7 +12,7 @@
*.rst text
*.sh text
*.txt text
*.xsh text
*.xsh text linguist-language=Python
*.yaml text
*.yml text
CONTRIBUTING text

View file

@ -117,9 +117,9 @@ is open to interpretation.
* Test generators make more dots and the dots must flow!
You can easily check for style issues, including some outright bugs such
as mispelled variable names, using `flake8 <https://flake8.pycqa.org/>`_. If you're using Anaconda you'll
as misspelled variable names, using `flake8 <https://flake8.pycqa.org/>`_. If you're using Anaconda you'll
need to run "conda install flake8" once. You can easily run flake8 on
the edited files in your uncommited git change::
the edited files in your uncommitted git change::
$ git status -s | awk '/\.py$$/ { print $2 }' | xargs flake8

View file

@ -13,12 +13,12 @@ Why Unordered?
==============
Yes, handler call order is not guaranteed. Please don't file bugs about this.
This was chosen because the order of handler registration is dependant on load order, which is
This was chosen because the order of handler registration is dependent on load order, which is
stable in a release but not something generally reasoned about. In addition, xontribs mean that we
don't know what handlers could be registered. So even an "ordered" event system would be unable to
make guarantees about ordering because of the larger system.
Because of this, the event system is not ordered; this is a form of abstraction. Order-dependant
Because of this, the event system is not ordered; this is a form of abstraction. Order-dependent
semantics are not encouraged by the built-in methods.
So how do I handle results?

View file

@ -110,8 +110,8 @@ line is ``#!/usr/bin/env xonsh``.
- ``docker run -it xonsh/xonsh:slim``
- Xonsh publishes a handful of containers, primarily targeting CI and automation use cases.
All of them are published on `Docker Hub <https://hub.docker.com/u/xonsh>`_.
* - ``exit``
- ``sys.exit()``
* - ``exit 1``
- ``exit(1)``
- Exiting from the current script.
To understand how xonsh executes the subprocess commands try

View file

@ -53,5 +53,5 @@ editing, but you keep xonsh's impressive completion.
For this it is preferred to have xonsh installed with the
prompt-toolkit. Then you can leave ``$SHELL_TYPE`` at its default.
Emacs will prompt you for the path of the xonsh exeutable when you
Emacs will prompt you for the path of the xonsh executable when you
start up ``ansi-term``.

View file

@ -18,7 +18,7 @@ are ignored otherwise. Here are their specifications.
.........................................................
This event fires whenever a command with a give name (``<cmd-name>``)
has its ``SubprocSpec.run()`` method called. This is fired
prior to the run call executing anything at all. This recieves the
prior to the run call executing anything at all. This receives the
``SubprocSpec`` object as ``spec`` that triggered the event, allowing
the handler to modify the spec if needed. For example, if we wanted to
intercept an ``ls`` spec, we could write:

View file

@ -4,7 +4,19 @@ Wishlist & To-Dos
Here is what is targeted for future versions of xonsh. Any one wishing
to tackle any of these or add their own is encouraged to do so!
1. Tab completion from man pages
Add xsh syntax highlighting on Github
----------------------------------------
There is a way to `contribute to github/linguist <https://github.com/github/linguist/blob/master/CONTRIBUTING.md>`_
to add xsh syntax highlighting. It would be great for someone to add xonsh to linguist.
For now we use Python syntax by adding the ``language`` to ``.gitattributes``:
.. code-block::
*xonshrc text linguist-language=Python
*.xsh text linguist-language=Python
Tab completion from man pages
---------------------------------
One of the more genius ideas I first encountered from ``fish`` is the idea
that man pages can be used to supply matches to tab-completion. In principle
@ -12,18 +24,16 @@ this is not that hard. First, we just need to use ``man2html`` and then
parse the html.
2. urwid based command prompt
Support and testing for other platforms
-------------------------------------------
This includes:
* Support for future versions of Python
* Testing on Mac OSX
urwid based command prompt
-----------------------------
Moving to urwid would allow for a whole new depth of user interaction.
There could be syntax highlighting as you type, a real interface for
environment variables, and so on. The command prompt is only the start!
3. Support and testing for other platforms
-------------------------------------------
This includes:
* Support for Python 2.7
* Support for future versions of Python
* Testing on Mac OSX

View file

@ -902,9 +902,43 @@ to be evaluated in Python mode using the ``@()`` syntax:
>>> echo @("my home is $HOME")
my home is $HOME
.. note::
You can also disable environment variable expansion completely by setting
``$EXPAND_ENV_VARS`` to ``False``.
Advanced String Literals
========================
For the fine control of environment variables (envvar) substitutions, brace substitutions and backslash escapes
there are extended list of literals:
- ``""`` - regular string: backslash escapes. Envvar substitutions in subprocess-mode.
- ``r""`` - raw string: unmodified.
- ``f""`` - formatted string: brace substitutions, backslash escapes. Envvar substitutions in subprocess-mode.
- ``fr""`` - raw formatted string: brace substitutions.
- ``p""`` - path string: backslash escapes, envvar substitutions, returns Path.
- ``pr""`` - raw Path string: envvar substitutions, returns Path.
- ``pf""`` - formatted Path string: backslash escapes, brace and envvar substitutions, returns Path.
To complete understanding let's set environment variable ``$EVAR`` to ``1`` and local variable ``var`` to ``2``
and make a table that shows how literal changes the string in Python- and subprocess-mode:
.. table::
======================== ========================== ======================= =====================
String literal As python object print(<String literal>) echo <String literal>
======================== ========================== ======================= =====================
``"/$EVAR/\'{var}\'"`` ``"/$EVAR/'{var}'"`` ``/$EVAR/'{var}'`` ``/1/'{var}'``
``r"/$EVAR/\'{var}\'"`` ``"/$EVAR/\\'{var}\\'"`` ``/$EVAR/\'{var}\'`` ``/$EVAR/\'{var}\'``
``f"/$EVAR/\'{var}\'"`` ``"/$EVAR/'2'"`` ``/$EVAR/'2'`` ``/1/'2'``
``fr"/$EVAR/\'{var}\'"`` ``"/$EVAR/\\'2\\'"`` ``/$EVAR/\'2\'`` ``/$EVAR/\'2\'``
``p"/$EVAR/\'{var}\'"`` ``Path("/1/'{var}'")`` ``/1/'{var}'`` ``/1/'{var}'``
``pr"/$EVAR/\'{var}\'"`` ``Path("/1/\\'{var}\\'")`` ``/1/\'{var}\'`` ``/1/\'{var}\'``
``pf"/$EVAR/\'{var}\'"`` ``Path("/1/'2'")`` ``/1/'2'`` ``/1/'2'``
======================== ========================== ======================= =====================
Filename Globbing with ``*``
===============================
Filename globbing with the ``*`` character is also allowed in subprocess-mode.
@ -1528,10 +1562,10 @@ or ``{BOLD_BLUE}``. Colors have the form shown below:
and ``BACKGROUND_#123456`` can both be used.
* ``bg#HEX`` or ``BG#HEX`` are shortcuts for setting a background hex color.
Thus you can set ``bg#0012ab`` or the uppercase version.
* ``BOLD_`` is a prefix modifier that increases the intesnity of the font.
* ``BOLD_`` is a prefix modifier that increases the intensity of the font.
It may be used with any foreground color.
For example, ``BOLD_RED`` and ``BOLD_#112233`` are OK!
* ``FAINT_`` is a prefix modifier that decreases the intesnity of the font.
* ``FAINT_`` is a prefix modifier that decreases the intensity of the font.
For example, ``FAINT_YELLOW``.
* ``ITALIC_`` is a prefix modifier that switches to an italic font.
For example, ``ITALIC_BLUE``.
@ -1547,7 +1581,7 @@ or ``{BOLD_BLUE}``. Colors have the form shown below:
widely supported. For example, ``CONCEAL_BLACK``.
* ``STRIKETHROUGH_`` is a prefix modifier which draws a line through the text.
For example, ``STRIKETHROUGH_RED``.
* ``BOLDOFF_`` is a prefix modifier for removing the intesnity of the font.
* ``BOLDOFF_`` is a prefix modifier for removing the intensity of the font.
It may be used with any foreground color.
For example, ``BOLDOFF_RED`` and ``BOLD_#112233`` are OK!
* ``FAINTOFF_`` is a prefix modifier for removing the faintness of the font.
@ -1757,4 +1791,6 @@ On Windows, you can also type ``Ctrl-Z``.
>>> exit
To exit from the xonsh script just call the ``exit(code)`` function.
Now it is your turn.

View file

@ -23,7 +23,7 @@ Is this meta-programming? You betcha!
When and where are macros used?
===============================
Macros are a practicality-beats-purity feature of many programing
Macros are a practicality-beats-purity feature of many programming
languages. Because they allow you break out of the normal parsing
cycle, depending on the language, you can do some truly wild things with
them. However, macros are really there to reduce the amount of boiler plate

View file

@ -6,7 +6,7 @@ The control file usually contains:
* Assignment statements setting `environment variables <envvars.html>`_. This includes standard OS environment variables that affect other programs and many that Xonsh uses for itself.
* ``xonfig`` commands to load selected add-ins ("`xontribs<tutorial_xontrib.html#loading-xontribs>`")
* Xonsh function defintions
* Xonsh function definitions
* `Alias definitions <aliases.html>`_, many of which invoke the above functions with specified arguments.
The system-wide ``xonshrc`` file controls options that are applied to all users of Xonsh on a given system.

23
news/exit.rst Normal file
View file

@ -0,0 +1,23 @@
**Added:**
* Added ``exit(exit_code)`` function by default in not interactive mode. Now importing ``exit`` from ``sys`` is not needed.
**Changed:**
* <news item>
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* <news item>
**Security:**
* <news item>

23
news/fix_env_subst.rst Normal file
View file

@ -0,0 +1,23 @@
**Added:**
* <news item>
**Changed:**
* <news item>
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* Fixed environment variables substitution: unknown variables stay unreplaced now (#3818).
**Security:**
* <news item>

23
news/gh_xsh.rst Normal file
View file

@ -0,0 +1,23 @@
**Added:**
* Added Python syntax highlighting of xsh files on Github repo xonsh/xonsh
**Changed:**
* <news item>
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* <news item>
**Security:**
* <news item>

View file

@ -5,7 +5,7 @@
**Changed:**
* <news item>
* Moved interal uses of ``NO_COLOR`` to ``RESET``.
**Deprecated:**

23
news/tutorial_literal.rst Normal file
View file

@ -0,0 +1,23 @@
**Added:**
* Added "Advanced String Literals" to the "Tutorial".
**Changed:**
* <news item>
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* <news item>
**Security:**
* <news item>

View file

@ -860,7 +860,7 @@ def test_str_to_env_path(inp, exp):
def test_path_to_str(inp, exp):
obs = path_to_str(inp)
if ON_WINDOWS:
exp = exp.replace('/','\\')
exp = exp.replace("/", "\\")
assert exp == obs
@ -1510,22 +1510,32 @@ def test_expand_case_matching(inp, exp):
[
("foo", "foo"),
("$foo $bar", "bar $bar"),
("$unk $foo $bar", "$unk bar $bar"),
("$foobar", "$foobar"),
("$foo $spam", "bar eggs"),
("$unk $foo $spam", "$unk bar eggs"),
("$unk $foo $unk $spam $unk", "$unk bar $unk eggs $unk"),
("$an_int$spam$a_bool", "42eggsTrue"),
("$unk$an_int$spam$a_bool", "$unk42eggsTrue"),
("bar$foo$spam$foo $an_int $none", "barbareggsbar 42 None"),
("$unk bar$foo$spam$foo $an_int $none", "$unk barbareggsbar 42 None"),
("$foo/bar", "bar/bar"),
("$unk/$foo/bar", "$unk/bar/bar"),
("${'foo'} $spam", "bar eggs"),
("$unk ${'unk'} ${'foo'} $spam", "$unk ${'unk'} bar eggs"),
("${'foo'} ${'a_bool'}", "bar True"),
("${'foo'}bar", "barbar"),
("${'foo'}/bar", "bar/bar"),
("${'unk'}/${'foo'}/bar", "${'unk'}/bar/bar"),
("${\"foo'}", "${\"foo'}"),
("$?bar", "$?bar"),
("$foo}bar", "bar}bar"),
("${'foo", "${'foo"),
(b"foo", "foo"),
(b"$foo bar", "bar bar"),
(b"$unk $foo bar", "$unk bar bar"),
(b"${'foo'}bar", "barbar"),
(b"${'unk'}${'foo'}bar", "${'unk'}barbar"),
],
)
def test_expandvars(inp, exp, xonsh_builtins):

View file

@ -582,10 +582,10 @@ def source_alias(args, stdin=None):
except Exception:
print_color(
"{RED}You may be attempting to source non-xonsh file! "
"{NO_COLOR}If you are trying to source a file in "
"{RESET}If you are trying to source a file in "
"another language, then please use the appropriate "
"source command. For example, {GREEN}source-bash "
"script.sh{NO_COLOR}",
"script.sh{RESET}",
file=sys.stderr,
)
raise

View file

@ -432,7 +432,7 @@ class BaseShell(object):
# OK PWD is really gone.
msg = "{UNDERLINE_INTENSE_WHITE}{BACKGROUND_INTENSE_BLACK}"
msg += "xonsh: working directory does not exist: " + pwd
msg += "{NO_COLOR}"
msg += "{RESET}"
self.print_color(msg, file=sys.stderr)
elif "PWD" not in env:
# $PWD is missing from env, recreate it

View file

@ -8,7 +8,7 @@ import argparse
from xonsh.lazyjson import LazyJSON
from xonsh.tools import print_color
NO_COLOR_S = "{NO_COLOR}"
RESET_S = "{RESET}"
RED_S = "{RED}"
GREEN_S = "{GREEN}"
BOLD_RED_S = "{BOLD_RED}"
@ -40,17 +40,15 @@ def bold_str_diff(a, b, sm=None):
bline += b[j1:j2]
else:
raise RuntimeError("tag not understood")
return aline + NO_COLOR_S + "\n" + bline + NO_COLOR_S + "\n"
return aline + RESET_S + "\n" + bline + RESET_S + "\n"
def redline(line):
return "{red}- {line}{no_color}\n".format(red=RED_S, line=line, no_color=NO_COLOR_S)
return "{red}- {line}{reset}\n".format(red=RED_S, line=line, reset=RESET_S)
def greenline(line):
return "{green}+ {line}{no_color}\n".format(
green=GREEN_S, line=line, no_color=NO_COLOR_S
)
return "{green}+ {line}{reset}\n".format(green=GREEN_S, line=line, reset=RESET_S)
def highlighted_ndiff(a, b):
@ -126,13 +124,13 @@ class HistoryDiffer(object):
def header(self):
"""Computes a header string difference."""
s = "{red}--- {aline}{no_color}\n" "{green}+++ {bline}{no_color}"
s = "{red}--- {aline}{reset}\n" "{green}+++ {bline}{reset}"
s = s.format(
aline=self._header_line(self.a),
bline=self._header_line(self.b),
red=RED_S,
green=GREEN_S,
no_color=NO_COLOR_S,
reset=RESET_S,
)
return s
@ -159,8 +157,8 @@ class HistoryDiffer(object):
xstr = "\n" + xstr
else:
xstr = ", ".join(["{0!r}".format(key) for key in only_x])
in_x = "These vars are only in {color}{xid}{no_color}: {{{xstr}}}\n\n"
return in_x.format(xid=xid, color=color, no_color=NO_COLOR_S, xstr=xstr)
in_x = "These vars are only in {color}{xid}{reset}: {{{xstr}}}\n\n"
return in_x.format(xid=xid, color=color, reset=RESET_S, xstr=xstr)
def envdiff(self):
"""Computes the difference between the environments."""
@ -184,13 +182,13 @@ class HistoryDiffer(object):
return s
def _cmd_in_one_diff(self, inp, i, xlj, xid, color):
s = "cmd #{i} only in {color}{xid}{no_color}:\n"
s = s.format(i=i, color=color, xid=xid, no_color=NO_COLOR_S)
s = "cmd #{i} only in {color}{xid}{reset}:\n"
s = s.format(i=i, color=color, xid=xid, reset=RESET_S)
lines = inp.splitlines()
lt = "{color}{pre}{no_color} {line}\n"
s += lt.format(color=color, no_color=NO_COLOR_S, line=lines[0], pre=">>>")
lt = "{color}{pre}{reset} {line}\n"
s += lt.format(color=color, reset=RESET_S, line=lines[0], pre=">>>")
for line in lines[1:]:
s += lt.format(color=color, no_color=NO_COLOR_S, line=line, pre="...")
s += lt.format(color=color, reset=RESET_S, line=line, pre="...")
if not self.verbose:
return s + "\n"
out = xlj["cmds"][0].get("out", "Note: no output stored")
@ -206,13 +204,13 @@ class HistoryDiffer(object):
pass
elif bout is None:
aid = self.a["sessionid"]
s += "Note: only {red}{aid}{no_color} output stored\n".format(
red=RED_S, aid=aid, no_color=NO_COLOR_S
s += "Note: only {red}{aid}{reset} output stored\n".format(
red=RED_S, aid=aid, reset=RESET_S
)
elif aout is None:
bid = self.b["sessionid"]
s += "Note: only {green}{bid}{no_color} output stored\n".format(
green=GREEN_S, bid=bid, no_color=NO_COLOR_S
s += "Note: only {green}{bid}{reset} output stored\n".format(
green=GREEN_S, bid=bid, reset=RESET_S
)
elif aout != bout:
s += "Outputs differ\n"
@ -223,19 +221,17 @@ class HistoryDiffer(object):
brtn = self.b["cmds"][j]["rtn"]
if artn != brtn:
s += (
"Return vals {red}{artn}{no_color} & {green}{brtn}{no_color} differ\n"
).format(
red=RED_S, green=GREEN_S, no_color=NO_COLOR_S, artn=artn, brtn=brtn
)
"Return vals {red}{artn}{reset} & {green}{brtn}{reset} differ\n"
).format(red=RED_S, green=GREEN_S, reset=RESET_S, artn=artn, brtn=brtn)
return s
def _cmd_replace_diff(self, i, ainp, aid, j, binp, bid):
s = (
"cmd #{i} in {red}{aid}{no_color} is replaced by \n"
"cmd #{j} in {green}{bid}{no_color}:\n"
"cmd #{i} in {red}{aid}{reset} is replaced by \n"
"cmd #{j} in {green}{bid}{reset}:\n"
)
s = s.format(
i=i, aid=aid, j=j, bid=bid, red=RED_S, green=GREEN_S, no_color=NO_COLOR_S
i=i, aid=aid, j=j, bid=bid, red=RED_S, green=GREEN_S, reset=RESET_S
)
s += highlighted_ndiff(ainp.splitlines(), binp.splitlines())
if not self.verbose:
@ -275,8 +271,8 @@ class HistoryDiffer(object):
odiff = self._cmd_out_and_rtn_diff(i, j)
if len(odiff) > 0:
h = (
"cmd #{i} in {red}{aid}{no_color} input is the same as \n"
"cmd #{j} in {green}{bid}{no_color}, but output differs:\n"
"cmd #{i} in {red}{aid}{reset} input is the same as \n"
"cmd #{j} in {green}{bid}{reset}, but output differs:\n"
)
s += h.format(
i=i,
@ -285,7 +281,7 @@ class HistoryDiffer(object):
bid=bid,
red=RED_S,
green=GREEN_S,
no_color=NO_COLOR_S,
reset=RESET_S,
)
s += odiff + "\n"
else:

View file

@ -454,7 +454,7 @@ class Inspector(object):
title_width = max(len(title) + 2 for title, _ in fields)
for title, content in fields:
title_len = len(title)
title = "{BOLD_RED}" + title + ":{NO_COLOR}"
title = "{BOLD_RED}" + title + ":{RESET}"
if len(content.splitlines()) > 1:
title += "\n"
else:
@ -478,7 +478,7 @@ class Inspector(object):
title_width = max(len(title) + 2 for title, _ in fields)
for title, content in fields:
title_len = len(title)
title = "{BOLD_RED}" + title + ":{NO_COLOR}"
title = "{BOLD_RED}" + title + ":{RESET}"
if not isinstance(content, str) or len(content.splitlines()) > 1:
title += "\n"
else:

View file

@ -437,10 +437,17 @@ def main_xonsh(args):
shell = builtins.__xonsh__.shell
history = builtins.__xonsh__.history
exit_code = 0
if shell and not env["XONSH_INTERACTIVE"]:
shell.ctx.update({"exit": sys.exit})
try:
if args.mode == XonshMode.interactive:
# enter the shell
# Setted again here because it is possible to call main_xonsh() without calling premain(), namely in the tests.
env["XONSH_INTERACTIVE"] = True
ignore_sigtstp()
if env["XONSH_INTERACTIVE"] and not any(
os.path.isfile(i) for i in env["XONSHRC"]

View file

@ -206,15 +206,6 @@ def load_xonsh_bindings() -> KeyBindingsBase:
env = builtins.__xonsh__.env
event.cli.current_buffer.insert_text(env.get("INDENT"))
@handle(Keys.Tab, filter=~tab_insert_indent)
def start_complete(event):
"""If starting completions, automatically move to first option"""
buff = event.app.current_buffer
if buff.complete_state:
buff.complete_next()
else:
buff.start_completion(select_first=True)
@handle(Keys.ControlX, Keys.ControlE, filter=~has_selection)
def open_editor(event):
""" Open current buffer in editor """

View file

@ -394,7 +394,7 @@ class ReadlineShell(BaseShell, cmd.Cmd):
elif len(completions) <= builtins.__xonsh__.env.get("COMPLETION_QUERY_LIMIT"):
return 2
msg = "\nDisplay all {} possibilities? ".format(len(completions))
msg += "({GREEN}y{NO_COLOR} or {RED}n{NO_COLOR})"
msg += "({GREEN}y{RESET} or {RED}n{RESET})"
self.print_color(msg, end="", flush=True, file=sys.stderr)
yn = "x"
while yn not in "yn":
@ -407,9 +407,9 @@ class ReadlineShell(BaseShell, cmd.Cmd):
w, h = shutil.get_terminal_size()
lines = columnize(completions, width=w)
more_msg = self.format_color(
"{YELLOW}==={NO_COLOR} more or "
"{PURPLE}({NO_COLOR}q{PURPLE}){NO_COLOR}uit "
"{YELLOW}==={NO_COLOR}"
"{YELLOW}==={RESET} more or "
"{PURPLE}({RESET}q{PURPLE}){RESET}uit "
"{YELLOW}==={RESET}"
)
while len(lines) > h - 1:
print("".join(lines[: h - 1]), end="", flush=True, file=sys.stderr)

View file

@ -70,11 +70,11 @@ def partial_color_tokenize(template):
styles = DEFAULT_STYLE_DICT
else:
styles = None
color = Color.NO_COLOR
color = Color.RESET
try:
toks, color = _partial_color_tokenize_main(template, styles)
except Exception:
toks = [(Color.NO_COLOR, template)]
toks = [(Color.RESET, template)]
if styles is not None:
styles[color] # ensure color is available
return toks
@ -85,7 +85,7 @@ def _partial_color_tokenize_main(template, styles):
bclose = "}"
colon = ":"
expl = "!"
color = Color.NO_COLOR
color = Color.RESET
fg = bg = None
value = ""
toks = []
@ -142,8 +142,8 @@ def color_by_name(name, fg=None, bg=None):
New computed background color name.
"""
name = name.upper()
if name == "NO_COLOR":
return Color.NO_COLOR, None, None
if name == "RESET":
return Color.RESET, None, None
m = RE_BACKGROUND.search(name)
if m is None: # must be foreground color
fg = norm_name(name)
@ -151,7 +151,7 @@ def color_by_name(name, fg=None, bg=None):
bg = norm_name(name)
# assemble token
if fg is None and bg is None:
tokname = "NO_COLOR"
tokname = "RESET"
elif fg is None:
tokname = bg
elif bg is None:
@ -171,7 +171,7 @@ def style_as_faded(template: str) -> str:
"""Remove the colors from the template string and style as faded."""
tokens = partial_color_tokenize(template)
without_color = "".join([sect for _, sect in tokens])
return "{NO_COLOR}{#d3d3d3}" + without_color + "{NO_COLOR}"
return "{RESET}{#d3d3d3}" + without_color + "{RESET}"
DEFAULT_STYLE_DICT = LazyObject(
@ -241,7 +241,7 @@ DEFAULT_STYLE_DICT = LazyObject(
Token.Color.INTENSE_RED: "ansibrightred",
Token.Color.INTENSE_WHITE: "ansiwhite",
Token.Color.INTENSE_YELLOW: "ansibrightyellow",
Token.Color.NO_COLOR: "noinherit",
Token.Color.RESET: "noinherit",
Token.Color.PURPLE: "ansimagenta",
Token.Color.RED: "ansired",
Token.Color.UNDERLINE_BLACK: "underline ansiblack",

View file

@ -2190,6 +2190,7 @@ def expandvars(path):
# get the path's string representation
path = str(path)
if "$" in path:
shift = 0
for match in POSIX_ENVVAR_REGEX.finditer(path):
name = match.group("envvar")
if name in env:
@ -2197,7 +2198,10 @@ def expandvars(path):
val = env[name]
value = str(val) if detyper is None else detyper(val)
value = str(val) if value is None else value
path = POSIX_ENVVAR_REGEX.sub(value, path, count=1)
start_pos, end_pos = match.span()
path_len_before_replace = len(path)
path = path[: start_pos + shift] + value + path[end_pos + shift :]
shift = shift + len(path) - path_len_before_replace
return path

View file

@ -107,7 +107,7 @@ class TracerType(object):
tracer = LazyObject(TracerType, globals(), "tracer")
COLORLESS_LINE = "{fname}:{lineno}:{line}"
COLOR_LINE = "{{PURPLE}}{fname}{{BLUE}}:" "{{GREEN}}{lineno}{{BLUE}}:" "{{NO_COLOR}}"
COLOR_LINE = "{{PURPLE}}{fname}{{BLUE}}:" "{{GREEN}}{lineno}{{BLUE}}:" "{{RESET}}"
def tracer_format_line(fname, lineno, line, color=True, lexer=None, formatter=None):

View file

@ -688,11 +688,8 @@ class StateVisitor(Visitor):
return flat
YN = "{GREEN}yes{NO_COLOR} or {RED}no{NO_COLOR} [default: no]? "
YNB = (
"{GREEN}yes{NO_COLOR}, {RED}no{NO_COLOR}, or "
"{YELLOW}break{NO_COLOR} [default: no]? "
)
YN = "{GREEN}yes{RESET} or {RED}no{RESET} [default: no]? "
YNB = "{GREEN}yes{RESET}, {RED}no{RESET}, or " "{YELLOW}break{RESET} [default: no]? "
class PromptVisitor(StateVisitor):
@ -746,15 +743,14 @@ class PromptVisitor(StateVisitor):
except Exception:
if node.retry:
msg = (
"{{BOLD_RED}}Invalid{{NO_COLOR}} input {0!r}, "
"please retry."
"{{BOLD_RED}}Invalid{{RESET}} input {0!r}, " "please retry."
)
print_color(msg.format(raw))
continue
else:
raise
if node.show_conversion and x is not Unstorable and str(x) != raw:
msg = "{{BOLD_PURPLE}}Converted{{NO_COLOR}} input {0!r} to {1!r}."
msg = "{{BOLD_PURPLE}}Converted{{RESET}} input {0!r} to {1!r}."
print_color(msg.format(raw, x))
else:
x = raw
@ -825,10 +821,10 @@ class PromptVisitor(StateVisitor):
if os.path.isfile(fname):
with open(fname, "r") as f:
self.state = json.load(f)
print_color("{{GREEN}}{0!r} loaded.{{NO_COLOR}}".format(fname))
print_color("{{GREEN}}{0!r} loaded.{{RESET}}".format(fname))
else:
print_color(
("{{RED}}{0!r} could not be found, " "continuing.{{NO_COLOR}}").format(
("{{RED}}{0!r} could not be found, " "continuing.{{RESET}}").format(
fname
)
)

View file

@ -52,8 +52,8 @@ from xonsh.lazyasd import lazyobject
HR = "'`-.,_,.-*'`-.,_,.-*'`-.,_,.-*'`-.,_,.-*'`-.,_,.-*'`-.,_,.-*'`-.,_,.-*'"
WIZARD_HEAD = """
{{BOLD_WHITE}}Welcome to the xonsh configuration wizard!{{NO_COLOR}}
{{YELLOW}}------------------------------------------{{NO_COLOR}}
{{BOLD_WHITE}}Welcome to the xonsh configuration wizard!{{RESET}}
{{YELLOW}}------------------------------------------{{RESET}}
This will present a guided tour through setting up the xonsh static
config file. Xonsh will automatically ask you if you want to run this
wizard if the configuration file does not exist. However, you can
@ -78,8 +78,8 @@ For the configuration to take effect, you will need to restart xonsh.
WIZARD_FS = """
{hr}
{{BOLD_WHITE}}Foreign Shell Setup{{NO_COLOR}}
{{YELLOW}}-------------------{{NO_COLOR}}
{{BOLD_WHITE}}Foreign Shell Setup{{RESET}}
{{YELLOW}}-------------------{{RESET}}
The xonsh shell has the ability to interface with foreign shells such
as Bash, or zsh (fish not yet implemented).
@ -95,8 +95,8 @@ makes it easier to transition to and from xonsh.
WIZARD_ENV = """
{hr}
{{BOLD_WHITE}}Environment Variable Setup{{NO_COLOR}}
{{YELLOW}}--------------------------{{NO_COLOR}}
{{BOLD_WHITE}}Environment Variable Setup{{RESET}}
{{YELLOW}}--------------------------{{RESET}}
The xonsh shell also allows you to setup environment variables from
the static configuration file. Any variables set in this way are
superseded by the definitions in the xonshrc or on the command line.
@ -107,7 +107,7 @@ The following lists the environment variable name, its documentation,
the default value, and the current value. The default and current
values are presented as pretty repr strings of their Python types.
{{BOLD_GREEN}}Note:{{NO_COLOR}} Simply hitting enter for any environment variable
{{BOLD_GREEN}}Note:{{RESET}} Simply hitting enter for any environment variable
will accept the default value for that entry.
""".format(
hr=HR
@ -118,10 +118,10 @@ WIZARD_ENV_QUESTION = "Would you like to set env vars now, " + wiz.YN
WIZARD_XONTRIB = """
{hr}
{{BOLD_WHITE}}Xontribs{{NO_COLOR}}
{{YELLOW}}--------{{NO_COLOR}}
{{BOLD_WHITE}}Xontribs{{RESET}}
{{YELLOW}}--------{{RESET}}
No shell is complete without extensions, and xonsh is no exception. Xonsh
extensions are called {{BOLD_GREEN}}xontribs{{NO_COLOR}}, or xonsh contributions.
extensions are called {{BOLD_GREEN}}xontribs{{RESET}}, or xonsh contributions.
Xontribs are dynamically loadable, either by importing them directly or by
using the 'xontrib' command. However, you can also configure xonsh to load
xontribs automatically on startup prior to loading the run control files.
@ -278,12 +278,12 @@ def _wrap_paragraphs(text, width=70, **kwargs):
ENVVAR_MESSAGE = """
{{BOLD_CYAN}}${name}{{NO_COLOR}}
{{BOLD_CYAN}}${name}{{RESET}}
{docstr}
{{RED}}default value:{{NO_COLOR}} {default}
{{RED}}current value:{{NO_COLOR}} {current}"""
{{RED}}default value:{{RESET}} {default}
{{RED}}current value:{{RESET}} {current}"""
ENVVAR_PROMPT = "{BOLD_GREEN}>>>{NO_COLOR} "
ENVVAR_PROMPT = "{BOLD_GREEN}>>>{RESET} "
def make_exit_message():
@ -291,7 +291,7 @@ def make_exit_message():
shell_type = builtins.__xonsh__.shell.shell_type
keyseq = "Ctrl-D" if shell_type == "readline" else "Ctrl-C"
msg = "To exit the wizard at any time, press {BOLD_UNDERLINE_CYAN}"
msg += keyseq + "{NO_COLOR}.\n"
msg += keyseq + "{RESET}.\n"
m = wiz.Message(message=msg)
return m
@ -348,7 +348,7 @@ def make_env_wiz():
return w
XONTRIB_PROMPT = "{BOLD_GREEN}Add this xontrib{NO_COLOR}, " + wiz.YN
XONTRIB_PROMPT = "{BOLD_GREEN}Add this xontrib{RESET}, " + wiz.YN
def _xontrib_path(visitor=None, node=None, val=None):
@ -359,17 +359,17 @@ def _xontrib_path(visitor=None, node=None, val=None):
def make_xontrib(xontrib, package):
"""Makes a message and StoreNonEmpty node for a xontrib."""
name = xontrib.get("name", "<unknown-xontrib-name>")
msg = "\n{BOLD_CYAN}" + name + "{NO_COLOR}\n"
msg = "\n{BOLD_CYAN}" + name + "{RESET}\n"
if "url" in xontrib:
msg += "{RED}url:{NO_COLOR} " + xontrib["url"] + "\n"
msg += "{RED}url:{RESET} " + xontrib["url"] + "\n"
if "package" in xontrib:
msg += "{RED}package:{NO_COLOR} " + xontrib["package"] + "\n"
msg += "{RED}package:{RESET} " + xontrib["package"] + "\n"
if "url" in package:
if "url" in xontrib and package["url"] != xontrib["url"]:
msg += "{RED}package-url:{NO_COLOR} " + package["url"] + "\n"
msg += "{RED}package-url:{RESET} " + package["url"] + "\n"
if "license" in package:
msg += "{RED}license:{NO_COLOR} " + package["license"] + "\n"
msg += "{PURPLE}installed?{NO_COLOR} "
msg += "{RED}license:{RESET} " + package["license"] + "\n"
msg += "{PURPLE}installed?{RESET} "
msg += ("no" if find_xontrib(name) is None else "yes") + "\n"
desc = xontrib.get("description", "")
if not isinstance(desc, str):
@ -553,7 +553,7 @@ def _styles(ns):
lines = []
for style in styles:
if style == curr:
lines.append("* {GREEN}" + style + "{NO_COLOR}")
lines.append("* {GREEN}" + style + "{RESET}")
else:
lines.append(" " + style)
s = "\n".join(lines)
@ -569,7 +569,7 @@ def _str_colors(cmap, cols):
line = ""
for i, name in enumerate(group):
buf = " " * (width - len(name))
line += "{" + name + "}" + name + "{NO_COLOR}" + buf
line += "{" + name + "}" + name + "{RESET}" + buf
if (i + 1) % n == 0:
lines.append(line)
line = ""
@ -581,7 +581,7 @@ def _str_colors(cmap, cols):
def _tok_colors(cmap, cols):
from xonsh.style_tools import Color
nc = Color.NO_COLOR
nc = Color.RESET
names_toks = {}
for t in cmap.keys():
name = str(t)
@ -846,15 +846,15 @@ def TAGLINES():
# list of strings or tuples (string, align, fill)
WELCOME_MSG = [
"",
("{{INTENSE_WHITE}}Welcome to the xonsh shell ({version}){{NO_COLOR}}", "^", " "),
("{{INTENSE_WHITE}}Welcome to the xonsh shell ({version}){{RESET}}", "^", " "),
"",
("{{INTENSE_RED}}~{{NO_COLOR}} {tagline} {{INTENSE_RED}}~{{NO_COLOR}}", "^", " "),
("{{INTENSE_RED}}~{{RESET}} {tagline} {{INTENSE_RED}}~{{RESET}}", "^", " "),
"",
("{{INTENSE_BLACK}}", "<", "-"),
"{{GREEN}}xonfig{{NO_COLOR}} tutorial {{INTENSE_WHITE}}-> Launch the tutorial in "
"the browser{{NO_COLOR}}",
"{{GREEN}}xonfig{{NO_COLOR}} web {{INTENSE_WHITE}}-> Run the configuration "
"tool in the browser and claim your shell {{NO_COLOR}}",
"{{GREEN}}xonfig{{RESET}} tutorial {{INTENSE_WHITE}}-> Launch the tutorial in "
"the browser{{RESET}}",
"{{GREEN}}xonfig{{RESET}} web {{INTENSE_WHITE}}-> Run the configuration "
"tool in the browser and claim your shell {{RESET}}",
"{{INTENSE_BLACK}}(Note: Run the configuration tool or create a "
"{{RED}}~/.xonshrc{{INTENSE_BLACK}} file to suppress the welcome screen)",
"",

View file

@ -165,15 +165,15 @@ def _list(ns):
for d in data:
name = d["name"]
lname = len(name)
s += "{PURPLE}" + name + "{NO_COLOR} " + " " * (nname - lname)
s += "{PURPLE}" + name + "{RESET} " + " " * (nname - lname)
if d["installed"]:
s += "{GREEN}installed{NO_COLOR} "
s += "{GREEN}installed{RESET} "
else:
s += "{RED}not-installed{NO_COLOR} "
s += "{RED}not-installed{RESET} "
if d["loaded"]:
s += "{GREEN}loaded{NO_COLOR}"
s += "{GREEN}loaded{RESET}"
else:
s += "{RED}not-loaded{NO_COLOR}"
s += "{RED}not-loaded{RESET }"
s += "\n"
print_color(s[:-1])