Skip to content

Commit

Permalink
Simplify color definition. (#14291)
Browse files Browse the repository at this point in the history
Schemes either accept a dict, or as kwargs. Try to use a single way of
defining via a dict, so that we can later deprecate passing all as
kwargs.

Use the opportunity to fix some things linter complaints, and add type
annotations.
  • Loading branch information
Carreau committed Jan 15, 2024
2 parents 8889ec7 + 6b2687c commit b14df38
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 127 deletions.
24 changes: 15 additions & 9 deletions IPython/core/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,22 +190,28 @@ def __call__(self, rest=''):
#-----------------------------------------------------------------------------

class AliasManager(Configurable):

default_aliases = List(default_aliases()).tag(config=True)
user_aliases = List(default_value=[]).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
default_aliases: List = List(default_aliases()).tag(config=True)
user_aliases: List = List(default_value=[]).tag(config=True)
shell = Instance(
"IPython.core.interactiveshell.InteractiveShellABC", allow_none=True
)

def __init__(self, shell=None, **kwargs):
super(AliasManager, self).__init__(shell=shell, **kwargs)
# For convenient access
self.linemagics = self.shell.magics_manager.magics['line']
self.init_aliases()
if self.shell is not None:
self.linemagics = self.shell.magics_manager.magics["line"]
self.init_aliases()

def init_aliases(self):
# Load default & user aliases
for name, cmd in self.default_aliases + self.user_aliases:
if cmd.startswith('ls ') and self.shell.colors == 'NoColor':
cmd = cmd.replace(' --color', '')
if (
cmd.startswith("ls ")
and self.shell is not None
and self.shell.colors == "NoColor"
):
cmd = cmd.replace(" --color", "")
self.soft_define_alias(name, cmd)

@property
Expand Down Expand Up @@ -246,7 +252,7 @@ def undefine_alias(self, name):
raise ValueError('%s is not an alias' % name)

def clear_aliases(self):
for name, cmd in self.aliases:
for name, _ in self.aliases:
self.undefine_alias(name)

def retrieve_alias(self, name):
Expand Down
226 changes: 118 additions & 108 deletions IPython/core/excolors.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,118 +42,128 @@ def exception_colors():
ex_colors = ColorSchemeTable()

# Populate it with color schemes
C = TermColors # shorthand and local lookup
ex_colors.add_scheme(ColorScheme(
'NoColor',
# The color to be used for the top line
topline = C.NoColor,

# The colors to be used in the traceback
filename = C.NoColor,
lineno = C.NoColor,
name = C.NoColor,
vName = C.NoColor,
val = C.NoColor,
em = C.NoColor,

# Emphasized colors for the last frame of the traceback
normalEm = C.NoColor,
filenameEm = C.NoColor,
linenoEm = C.NoColor,
nameEm = C.NoColor,
valEm = C.NoColor,

# Colors for printing the exception
excName = C.NoColor,
line = C.NoColor,
caret = C.NoColor,
Normal = C.NoColor
))
C = TermColors # shorthand and local lookup
ex_colors.add_scheme(
ColorScheme(
"NoColor",
{
# The color to be used for the top line
"topline": C.NoColor,

# The colors to be used in the traceback
"filename": C.NoColor,
"lineno": C.NoColor,
"name": C.NoColor,
"vName": C.NoColor,
"val": C.NoColor,
"em": C.NoColor,

# Emphasized colors for the last frame of the traceback
"normalEm": C.NoColor,
"filenameEm": C.NoColor,
"linenoEm": C.NoColor,
"nameEm": C.NoColor,
"valEm": C.NoColor,

# Colors for printing the exception
"excName": C.NoColor,
"line": C.NoColor,
"caret": C.NoColor,
"Normal": C.NoColor,
},
)
)

# make some schemes as instances so we can copy them for modification easily
ex_colors.add_scheme(ColorScheme(
'Linux',
# The color to be used for the top line
topline = C.LightRed,

# The colors to be used in the traceback
filename = C.Green,
lineno = C.Green,
name = C.Purple,
vName = C.Cyan,
val = C.Green,
em = C.LightCyan,

# Emphasized colors for the last frame of the traceback
normalEm = C.LightCyan,
filenameEm = C.LightGreen,
linenoEm = C.LightGreen,
nameEm = C.LightPurple,
valEm = C.LightBlue,

# Colors for printing the exception
excName = C.LightRed,
line = C.Yellow,
caret = C.White,
Normal = C.Normal
))
ex_colors.add_scheme(
ColorScheme(
"Linux",
{
# The color to be used for the top line
"topline": C.LightRed,
# The colors to be used in the traceback
"filename": C.Green,
"lineno": C.Green,
"name": C.Purple,
"vName": C.Cyan,
"val": C.Green,
"em": C.LightCyan,
# Emphasized colors for the last frame of the traceback
"normalEm": C.LightCyan,
"filenameEm": C.LightGreen,
"linenoEm": C.LightGreen,
"nameEm": C.LightPurple,
"valEm": C.LightBlue,
# Colors for printing the exception
"excName": C.LightRed,
"line": C.Yellow,
"caret": C.White,
"Normal": C.Normal,
},
)
)

# For light backgrounds, swap dark/light colors
ex_colors.add_scheme(ColorScheme(
'LightBG',
# The color to be used for the top line
topline = C.Red,

# The colors to be used in the traceback
filename = C.LightGreen,
lineno = C.LightGreen,
name = C.LightPurple,
vName = C.Cyan,
val = C.LightGreen,
em = C.Cyan,

# Emphasized colors for the last frame of the traceback
normalEm = C.Cyan,
filenameEm = C.Green,
linenoEm = C.Green,
nameEm = C.Purple,
valEm = C.Blue,

# Colors for printing the exception
excName = C.Red,
#line = C.Brown, # brown often is displayed as yellow
line = C.Red,
caret = C.Normal,
Normal = C.Normal,
))

ex_colors.add_scheme(ColorScheme(
'Neutral',
# The color to be used for the top line
topline = C.Red,

# The colors to be used in the traceback
filename = C.LightGreen,
lineno = C.LightGreen,
name = C.LightPurple,
vName = C.Cyan,
val = C.LightGreen,
em = C.Cyan,

# Emphasized colors for the last frame of the traceback
normalEm = C.Cyan,
filenameEm = C.Green,
linenoEm = C.Green,
nameEm = C.Purple,
valEm = C.Blue,

# Colors for printing the exception
excName = C.Red,
#line = C.Brown, # brown often is displayed as yellow
line = C.Red,
caret = C.Normal,
Normal = C.Normal,
))
ex_colors.add_scheme(
ColorScheme(
"LightBG",
{
# The color to be used for the top line
"topline": C.Red,

# The colors to be used in the traceback
"filename": C.LightGreen,
"lineno": C.LightGreen,
"name": C.LightPurple,
"vName": C.Cyan,
"val": C.LightGreen,
"em": C.Cyan,

# Emphasized colors for the last frame of the traceback
"normalEm": C.Cyan,
"filenameEm": C.Green,
"linenoEm": C.Green,
"nameEm": C.Purple,
"valEm": C.Blue,

# Colors for printing the exception
"excName": C.Red,
# "line": C.Brown, # brown often is displayed as yellow
"line": C.Red,
"caret": C.Normal,
"Normal": C.Normal,
},
)
)

ex_colors.add_scheme(
ColorScheme(
"Neutral",
{
# The color to be used for the top line
"topline": C.Red,
# The colors to be used in the traceback
"filename": C.LightGreen,
"lineno": C.LightGreen,
"name": C.LightPurple,
"vName": C.Cyan,
"val": C.LightGreen,
"em": C.Cyan,
# Emphasized colors for the last frame of the traceback
"normalEm": C.Cyan,
"filenameEm": C.Green,
"linenoEm": C.Green,
"nameEm": C.Purple,
"valEm": C.Blue,
# Colors for printing the exception
"excName": C.Red,
# line = C.Brown, # brown often is displayed as yellow
"line": C.Red,
"caret": C.Normal,
"Normal": C.Normal,
},
)
)

# Hack: the 'neutral' colours are not very visible on a dark background on
# Windows. Since Windows command prompts have a dark background by default, and
Expand Down
5 changes: 2 additions & 3 deletions IPython/core/extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
from importlib import import_module, reload

from traitlets.config.configurable import Configurable
from IPython.utils.path import ensure_dir_exists, compress_user
from IPython.utils.decorators import undoc
from IPython.utils.path import ensure_dir_exists
from traitlets import Instance


Expand Down Expand Up @@ -84,7 +83,7 @@ def _load_extension(self, module_str: str):
if module_str in self.loaded:
return "already loaded"

from IPython.utils.syspathcontext import prepended_to_syspath
assert self.shell is not None

with self.shell.builtin_trap:
if module_str not in sys.modules:
Expand Down
3 changes: 1 addition & 2 deletions IPython/core/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@
#-----------------------------------------------------------------------------

class PayloadManager(Configurable):

_payload = List([])
_payload: List = List([])

def write_payload(self, data, single=True):
"""Include or update the specified `data` payload in the PayloadManager.
Expand Down
5 changes: 3 additions & 2 deletions IPython/terminal/prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ def write_output_prompt(self):

if self.do_full_cache:
tokens = self.shell.prompts.out_prompt_tokens()
prompt_txt = ''.join(s for t, s in tokens)
if prompt_txt and not prompt_txt.endswith('\n'):
prompt_txt = "".join(s for _, s in tokens)
if prompt_txt and not prompt_txt.endswith("\n"):
# Ask for a newline before multiline output
self.prompt_end_newline = False

Expand All @@ -116,6 +116,7 @@ def write_output_prompt(self):
sys.stdout.write(prompt_txt)

def write_format_data(self, format_dict, md_dict=None) -> None:
assert self.shell is not None
if self.shell.mime_renderers:

for mime, handler in self.shell.mime_renderers.items():
Expand Down
8 changes: 6 additions & 2 deletions IPython/utils/coloransi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Tools for coloring text in ANSI terminals.
"""

Expand All @@ -9,12 +8,13 @@
# the file COPYING, distributed as part of this software.
#*****************************************************************************

__all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable']

import os

from IPython.utils.ipstruct import Struct

__all__ = ["TermColors", "InputTermColors", "ColorScheme", "ColorSchemeTable"]

color_templates = (
# Dark colors
("Black" , "0;30"),
Expand Down Expand Up @@ -110,6 +110,10 @@ class NoColors:

class ColorScheme:
"""Generic color scheme class. Just a name and a Struct."""

name: str
colors: Struct

def __init__(self,__scheme_name_,colordict=None,**colormap):
self.name = __scheme_name_
if colordict is None:
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ requires = ["setuptools >= 51.0.0"]
build-backend = "setuptools.build_meta"

[tool.mypy]
python_version = 3.10
python_version = "3.10"
ignore_missing_imports = true
follow_imports = 'silent'
exclude = [
Expand Down Expand Up @@ -79,3 +79,6 @@ ipdoctest_optionflags = [
"ELLIPSIS"
]
asyncio_mode = "strict"

[tool.pyright]
pythonPlatform="All"

0 comments on commit b14df38

Please sign in to comment.