aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/prompt-toolkit/py3
diff options
context:
space:
mode:
authorarcadia-devtools <arcadia-devtools@yandex-team.ru>2022-02-12 14:35:15 +0300
committerarcadia-devtools <arcadia-devtools@yandex-team.ru>2022-02-12 14:35:15 +0300
commit46a8b83899dd321edf511c0483f9c479ce2c1bc4 (patch)
treee5debc03beecbd10e7d1bf78c889c8d54e8c4523 /contrib/python/prompt-toolkit/py3
parentb56bbcc9f63bf31991a8aa118555ce0c12875a74 (diff)
downloadydb-46a8b83899dd321edf511c0483f9c479ce2c1bc4.tar.gz
intermediate changes
ref:7c971b97c72bbbcbf889118d39017bd14f99365a
Diffstat (limited to 'contrib/python/prompt-toolkit/py3')
-rw-r--r--contrib/python/prompt-toolkit/py3/.dist-info/METADATA4
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/__init__.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py11
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py8
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py18
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/fuzzy_completer.py10
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/nested.py8
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py19
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/completion.py3
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/regex_parser.py14
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/server.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/data_structures.py10
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/document.py4
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py35
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/base.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/html.py23
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/history.py7
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_pipe.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_utils.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py9
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/completion.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/digraphs.py1
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py6
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py11
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py8
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py16
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py18
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py10
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/screen.py4
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/mouse_events.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/output/flush_stdout.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/output/win32.py4
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py3
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/selection.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/dialogs.py12
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/progress_bar/formatters.py6
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/base.py25
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style.py11
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style_transformation.py6
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/validation.py4
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/base.py45
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/menus.py4
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/toolbars.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/prompt_toolkit/win32_types.py4
-rw-r--r--contrib/python/prompt-toolkit/py3/tests/test_cli.py1
-rw-r--r--contrib/python/prompt-toolkit/py3/tests/test_completion.py8
-rw-r--r--contrib/python/prompt-toolkit/py3/tests/test_formatted_text.py84
-rw-r--r--contrib/python/prompt-toolkit/py3/tests/test_inputstream.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/tests/test_key_binding.py2
-rw-r--r--contrib/python/prompt-toolkit/py3/ya.make2
57 files changed, 302 insertions, 212 deletions
diff --git a/contrib/python/prompt-toolkit/py3/.dist-info/METADATA b/contrib/python/prompt-toolkit/py3/.dist-info/METADATA
index 76d00294018..cdf27c97ff4 100644
--- a/contrib/python/prompt-toolkit/py3/.dist-info/METADATA
+++ b/contrib/python/prompt-toolkit/py3/.dist-info/METADATA
@@ -1,6 +1,6 @@
Metadata-Version: 2.1
Name: prompt-toolkit
-Version: 3.0.27
+Version: 3.0.28
Summary: Library for building powerful interactive command lines in Python
Home-page: https://github.com/prompt-toolkit/python-prompt-toolkit
Author: Jonathan Slenders
@@ -21,8 +21,6 @@ Classifier: Programming Language :: Python
Classifier: Topic :: Software Development
Requires-Python: >=3.6.2
Description-Content-Type: text/x-rst
-License-File: LICENSE
-License-File: AUTHORS.rst
Requires-Dist: wcwidth
Python Prompt Toolkit
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/__init__.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/__init__.py
index 554ca2238cf..f3423df38c2 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/__init__.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/__init__.py
@@ -18,7 +18,7 @@ from .formatted_text import ANSI, HTML
from .shortcuts import PromptSession, print_formatted_text, prompt
# Don't forget to update in `docs/conf.py`!
-__version__ = "3.0.27"
+__version__ = "3.0.28"
# Version tuple.
VERSION = tuple(__version__.split("."))
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py
index 5426ebfdfec..07b81d5ec14 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/application.py
@@ -583,8 +583,7 @@ class Application(Generic[_AppResult]):
# (All controls are able to invalidate themselves.)
def gather_events() -> Iterable[Event[object]]:
for c in self.layout.find_all_controls():
- for ev in c.get_invalidate_events():
- yield ev
+ yield from c.get_invalidate_events()
self._invalidate_events = list(gather_events())
@@ -959,7 +958,7 @@ class Application(Generic[_AppResult]):
# but don't use logger. (This works better on Python 2.)
print("\nUnhandled exception in event loop:")
print(formatted_tb)
- print("Exception %s" % (context.get("exception"),))
+ print("Exception {}".format(context.get("exception")))
await _do_wait_for_enter("Press ENTER to continue...")
@@ -1256,10 +1255,8 @@ class Application(Generic[_AppResult]):
if attrs_for_style:
return sorted(
- [
- re.sub(r"\s+", " ", style_str).strip()
- for style_str in attrs_for_style.keys()
- ]
+ re.sub(r"\s+", " ", style_str).strip()
+ for style_str in attrs_for_style.keys()
)
return []
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py
index 14eb7922c89..ae69bfd51c7 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/application/current.py
@@ -53,7 +53,7 @@ class AppSession:
self.app: Optional["Application[Any]"] = None
def __repr__(self) -> str:
- return "AppSession(app=%r)" % (self.app,)
+ return f"AppSession(app={self.app!r})"
@property
def input(self) -> "Input":
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py
index 105d3cc07d9..ec2d3ba91cb 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py
@@ -95,7 +95,7 @@ class CompletionState:
self.complete_index = complete_index # Position in the `_completions` array.
def __repr__(self) -> str:
- return "%s(%r, <%r> completions, index=%r)" % (
+ return "{}({!r}, <{!r}> completions, index={!r})".format(
self.__class__.__name__,
self.original_document,
len(self.completions),
@@ -160,7 +160,7 @@ class YankNthArgState:
self.n = n
def __repr__(self) -> str:
- return "%s(history_position=%r, n=%r, previous_inserted_word=%r)" % (
+ return "{}(history_position={!r}, n={!r}, previous_inserted_word={!r})".format(
self.__class__.__name__,
self.history_position,
self.n,
@@ -317,7 +317,7 @@ class Buffer:
else:
text = self.text[:12] + "..."
- return "<Buffer(name=%r, text=%r) at %r>" % (self.name, text, id(self))
+ return f"<Buffer(name={self.name!r}, text={text!r}) at {id(self)!r}>"
def reset(
self, document: Optional[Document] = None, append_to_history: bool = False
@@ -967,7 +967,7 @@ class Buffer:
if i == self.working_index:
display_meta = "Current, line %s" % (j + 1)
else:
- display_meta = "History %s, line %s" % (i + 1, j + 1)
+ display_meta = f"History {i + 1}, line {j + 1}"
completions.append(
Completion(
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py
index 3bfde97d10d..371c0ea6e5c 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/base.py
@@ -65,13 +65,13 @@ class Completion:
def __repr__(self) -> str:
if isinstance(self.display, str) and self.display == self.text:
- return "%s(text=%r, start_position=%r)" % (
+ return "{}(text={!r}, start_position={!r})".format(
self.__class__.__name__,
self.text,
self.start_position,
)
else:
- return "%s(text=%r, start_position=%r, display=%r)" % (
+ return "{}(text={!r}, start_position={!r}, display={!r})".format(
self.__class__.__name__,
self.text,
self.start_position,
@@ -155,7 +155,7 @@ class CompleteEvent:
self.completion_requested = completion_requested
def __repr__(self) -> str:
- return "%s(text_inserted=%r, completion_requested=%r)" % (
+ return "{}(text_inserted={!r}, completion_requested={!r})".format(
self.__class__.__name__,
self.text_inserted,
self.completion_requested,
@@ -230,7 +230,7 @@ class ThreadedCompleter(Completer):
yield completion
def __repr__(self) -> str:
- return "ThreadedCompleter(%r)" % (self.completer,)
+ return f"ThreadedCompleter({self.completer!r})"
class DummyCompleter(Completer):
@@ -274,7 +274,7 @@ class DynamicCompleter(Completer):
yield completion
def __repr__(self) -> str:
- return "DynamicCompleter(%r -> %r)" % (self.get_completer, self.get_completer())
+ return f"DynamicCompleter({self.get_completer!r} -> {self.get_completer()!r})"
class ConditionalCompleter(Completer):
@@ -291,15 +291,14 @@ class ConditionalCompleter(Completer):
self.filter = to_filter(filter)
def __repr__(self) -> str:
- return "ConditionalCompleter(%r, filter=%r)" % (self.completer, self.filter)
+ return f"ConditionalCompleter({self.completer!r}, filter={self.filter!r})"
def get_completions(
self, document: Document, complete_event: CompleteEvent
) -> Iterable[Completion]:
# Get all completions in a blocking way.
if self.filter():
- for c in self.completer.get_completions(document, complete_event):
- yield c
+ yield from self.completer.get_completions(document, complete_event)
async def get_completions_async(
self, document: Document, complete_event: CompleteEvent
@@ -326,8 +325,7 @@ class _MergedCompleter(Completer):
) -> Iterable[Completion]:
# Get all completions from the other completers in a blocking way.
for completer in self.completers:
- for c in completer.get_completions(document, complete_event):
- yield c
+ yield from completer.get_completions(document, complete_event)
async def get_completions_async(
self, document: Document, complete_event: CompleteEvent
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/fuzzy_completer.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/fuzzy_completer.py
index 4f7c3ab5d68..627adc8738a 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/fuzzy_completer.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/fuzzy_completer.py
@@ -93,7 +93,7 @@ class FuzzyCompleter(Completer):
fuzzy_matches: List[_FuzzyMatch] = []
pat = ".*?".join(map(re.escape, word_before_cursor))
- pat = "(?=({0}))".format(pat) # lookahead regex to manage overlapping matches
+ pat = f"(?=({pat}))" # lookahead regex to manage overlapping matches
regex = re.compile(pat, re.IGNORECASE)
for compl in completions:
matches = list(regex.finditer(compl.text))
@@ -195,7 +195,7 @@ class FuzzyWordCompleter(Completer):
return self.fuzzy_completer.get_completions(document, complete_event)
-_FuzzyMatch = NamedTuple(
- "_FuzzyMatch",
- [("match_length", int), ("start_pos", int), ("completion", Completion)],
-)
+class _FuzzyMatch(NamedTuple):
+ match_length: int
+ start_pos: int
+ completion: Completion
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/nested.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/nested.py
index 8b0978ca32e..f8656b217ad 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/nested.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/completion/nested.py
@@ -33,7 +33,7 @@ class NestedCompleter(Completer):
self.ignore_case = ignore_case
def __repr__(self) -> str:
- return "NestedCompleter(%r, ignore_case=%r)" % (self.options, self.ignore_case)
+ return f"NestedCompleter({self.options!r}, ignore_case={self.ignore_case!r})"
@classmethod
def from_nested_dict(cls, data: NestedDict) -> "NestedCompleter":
@@ -97,13 +97,11 @@ class NestedCompleter(Completer):
cursor_position=document.cursor_position - move_cursor,
)
- for c in completer.get_completions(new_document, complete_event):
- yield c
+ yield from completer.get_completions(new_document, complete_event)
# No space in the input: behave exactly like `WordCompleter`.
else:
completer = WordCompleter(
list(self.options.keys()), ignore_case=self.ignore_case
)
- for c in completer.get_completions(document, complete_event):
- yield c
+ yield from completer.get_completions(document, complete_event)
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py
index a6eb77127a2..fed78498c0c 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py
@@ -118,7 +118,8 @@ class _CompiledGrammar:
# input contains some additional characters at the end that don't match the grammar.)
self._re_prefix_with_trailing_input = [
re.compile(
- r"(?:%s)(?P<%s>.*?)$" % (t.rstrip("$"), _INVALID_TRAILING_INPUT), flags
+ r"(?:{})(?P<{}>.*?)$".format(t.rstrip("$"), _INVALID_TRAILING_INPUT),
+ flags,
)
for t in self._re_prefix_patterns
]
@@ -168,7 +169,7 @@ class _CompiledGrammar:
# A `Variable` wraps the children into a named group.
elif isinstance(node, Variable):
- return "(?P<%s>%s)" % (
+ return "(?P<{}>{})".format(
create_group_func(node),
transform(node.childnode),
)
@@ -186,13 +187,13 @@ class _CompiledGrammar:
("" if node.max_repeat is None else str(node.max_repeat)),
)
- return "(?:%s)%s%s" % (
+ return "(?:{}){}{}".format(
transform(node.childnode),
repeat_sign,
("" if node.greedy else "?"),
)
else:
- raise TypeError("Got %r" % (node,))
+ raise TypeError(f"Got {node!r}")
return transform(root_node)
@@ -327,7 +328,7 @@ class _CompiledGrammar:
# (Note that we should not append a '?' here. the 'transform'
# method will already recursively do that.)
for c_str in transform(node.childnode):
- yield "(?P<%s>%s)" % (create_group_func(node), c_str)
+ yield f"(?P<{create_group_func(node)}>{c_str})"
elif isinstance(node, Repeat):
# If we have a repetition of 8 times. That would mean that the
@@ -343,7 +344,7 @@ class _CompiledGrammar:
repeat_sign = "{,%i}" % (node.max_repeat - 1)
else:
repeat_sign = "*"
- yield "(?:%s)%s%s%s" % (
+ yield "(?:{}){}{}{}".format(
prefix,
repeat_sign,
("" if node.greedy else "?"),
@@ -498,9 +499,9 @@ class Variables:
self._tuples = tuples
def __repr__(self) -> str:
- return "%s(%s)" % (
+ return "{}({})".format(
self.__class__.__name__,
- ", ".join("%s=%r" % (k, v) for k, v, _ in self._tuples),
+ ", ".join(f"{k}={v!r}" for k, v, _ in self._tuples),
)
def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
@@ -540,7 +541,7 @@ class MatchVariable:
self.stop = self.slice[1]
def __repr__(self) -> str:
- return "%s(%r, %r)" % (self.__class__.__name__, self.varname, self.value)
+ return f"{self.__class__.__name__}({self.varname!r}, {self.value!r})"
def compile(
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/completion.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/completion.py
index 7aaad71f188..3cebcc03f69 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/completion.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/completion.py
@@ -40,8 +40,7 @@ class GrammarCompleter(Completer):
self._get_completions_for_match(m, complete_event)
)
- for c in completions:
- yield c
+ yield from completions
def _get_completions_for_match(
self, match: Match, complete_event: CompleteEvent
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/regex_parser.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/regex_parser.py
index 61d2f17a231..87e39d498c1 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/regex_parser.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/regex_parser.py
@@ -54,7 +54,7 @@ class AnyNode(Node):
return AnyNode(self.children + [other_node])
def __repr__(self) -> str:
- return "%s(%r)" % (self.__class__.__name__, self.children)
+ return f"{self.__class__.__name__}({self.children!r})"
class NodeSequence(Node):
@@ -70,7 +70,7 @@ class NodeSequence(Node):
return NodeSequence(self.children + [other_node])
def __repr__(self) -> str:
- return "%s(%r)" % (self.__class__.__name__, self.children)
+ return f"{self.__class__.__name__}({self.children!r})"
class Regex(Node):
@@ -84,7 +84,7 @@ class Regex(Node):
self.regex = regex
def __repr__(self) -> str:
- return "%s(/%s/)" % (self.__class__.__name__, self.regex)
+ return f"{self.__class__.__name__}(/{self.regex}/)"
class Lookahead(Node):
@@ -97,7 +97,7 @@ class Lookahead(Node):
self.negative = negative
def __repr__(self) -> str:
- return "%s(%r)" % (self.__class__.__name__, self.childnode)
+ return f"{self.__class__.__name__}({self.childnode!r})"
class Variable(Node):
@@ -114,7 +114,7 @@ class Variable(Node):
self.varname = varname
def __repr__(self) -> str:
- return "%s(childnode=%r, varname=%r)" % (
+ return "{}(childnode={!r}, varname={!r})".format(
self.__class__.__name__,
self.childnode,
self.varname,
@@ -135,7 +135,7 @@ class Repeat(Node):
self.greedy = greedy
def __repr__(self) -> str:
- return "%s(childnode=%r)" % (self.__class__.__name__, self.childnode)
+ return f"{self.__class__.__name__}(childnode={self.childnode!r})"
def tokenize_regex(input: str) -> List[str]:
@@ -261,7 +261,7 @@ def parse_regex(regex_tokens: List[str]) -> Node:
elif t.startswith("{"):
# TODO: implement!
- raise Exception("{}-style repetition not yet supported".format(t))
+ raise Exception(f"{t}-style repetition not yet supported")
elif t.startswith("(?"):
raise Exception("%r not supported" % t)
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py
index 7b6df8319fc..68f3639880d 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py
@@ -122,7 +122,7 @@ class TelnetProtocolParser:
# NOTE: the first parameter of struct.unpack should be
# a 'str' object. Both on Py2/py3. This crashes on OSX
# otherwise.
- columns, rows = struct.unpack(str("!HH"), data)
+ columns, rows = struct.unpack("!HH", data)
self.size_received_callback(rows, columns)
else:
logger.warning("Wrong number of NAWS bytes")
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/server.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/server.py
index b6e4b140654..2e042c95d16 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/server.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/server.py
@@ -99,7 +99,7 @@ class _ConnectionStdout:
def flush(self) -> None:
try:
self._connection.send(b"".join(self._buffer))
- except socket.error as e:
+ except OSError as e:
logger.warning("Couldn't send data over socket: %s" % e)
self._buffer = []
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/data_structures.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/data_structures.py
index 454bb964ec3..d031acffd2a 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/data_structures.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/data_structures.py
@@ -6,5 +6,11 @@ __all__ = [
]
-Point = NamedTuple("Point", [("x", int), ("y", int)])
-Size = NamedTuple("Size", [("rows", int), ("columns", int)])
+class Point(NamedTuple):
+ x: int
+ y: int
+
+
+class Size(NamedTuple):
+ rows: int
+ columns: int
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/document.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/document.py
index f5f24b37b58..19841552054 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/document.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/document.py
@@ -106,7 +106,7 @@ class Document:
# Check cursor position. It can also be right after the end. (Where we
# insert text.)
assert cursor_position is None or cursor_position <= len(text), AssertionError(
- "cursor_position=%r, len_text=%r" % (cursor_position, len(text))
+ f"cursor_position={cursor_position!r}, len_text={len(text)!r}"
)
# By default, if no cursor position was given, make sure to put the
@@ -137,7 +137,7 @@ class Document:
# assert self._cache
def __repr__(self) -> str:
- return "%s(%r, %r)" % (self.__class__.__name__, self.text, self.cursor_position)
+ return f"{self.__class__.__name__}({self.text!r}, {self.cursor_position!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Document):
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py
index 3d570633570..2a30b09c218 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/ansi.py
@@ -1,4 +1,5 @@
-from typing import Generator, List, Optional
+from string import Formatter
+from typing import Generator, List, Optional, Tuple, Union
from prompt_toolkit.output.vt100 import BG_ANSI_COLORS, FG_ANSI_COLORS
from prompt_toolkit.output.vt100 import _256_colors as _256_colors_table
@@ -207,7 +208,7 @@ class ANSI:
# True colors.
if n == 2 and len(attrs) >= 3:
try:
- color_str = "#%02x%02x%02x" % (
+ color_str = "#{:02x}{:02x}{:02x}".format(
attrs.pop(),
attrs.pop(),
attrs.pop(),
@@ -247,7 +248,7 @@ class ANSI:
return " ".join(result)
def __repr__(self) -> str:
- return "ANSI(%r)" % (self.value,)
+ return f"ANSI({self.value!r})"
def __pt_formatted_text__(self) -> StyleAndTextTuples:
return self._formatted_text
@@ -257,11 +258,17 @@ class ANSI:
Like `str.format`, but make sure that the arguments are properly
escaped. (No ANSI escapes can be injected.)
"""
- # Escape all the arguments.
- args = tuple(ansi_escape(a) for a in args)
- kwargs = {k: ansi_escape(v) for k, v in kwargs.items()}
+ return ANSI(FORMATTER.vformat(self.value, args, kwargs))
- return ANSI(self.value.format(*args, **kwargs))
+ def __mod__(self, value: object) -> "ANSI":
+ """
+ ANSI('<b>%s</b>') % value
+ """
+ if not isinstance(value, tuple):
+ value = (value,)
+
+ value = tuple(ansi_escape(i) for i in value)
+ return ANSI(self.value % value)
# Mapping of the ANSI color codes to their names.
@@ -272,11 +279,19 @@ _bg_colors = {v: k for k, v in BG_ANSI_COLORS.items()}
_256_colors = {}
for i, (r, g, b) in enumerate(_256_colors_table.colors):
- _256_colors[i] = "#%02x%02x%02x" % (r, g, b)
+ _256_colors[i] = f"#{r:02x}{g:02x}{b:02x}"
-def ansi_escape(text: str) -> str:
+def ansi_escape(text: object) -> str:
"""
Replace characters with a special meaning.
"""
- return text.replace("\x1b", "?").replace("\b", "?")
+ return str(text).replace("\x1b", "?").replace("\b", "?")
+
+
+class ANSIFormatter(Formatter):
+ def format_field(self, value: object, format_spec: str) -> str:
+ return ansi_escape(format(value, format_spec))
+
+
+FORMATTER = ANSIFormatter()
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/base.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/base.py
index c1761f26402..e88c5935a5f 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/base.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/base.py
@@ -78,7 +78,7 @@ def to_formatted_text(
elif callable(value):
return to_formatted_text(value(), style=style)
elif auto_convert:
- result = [("", "{}".format(value))]
+ result = [("", f"{value}")]
else:
raise ValueError(
"No formatted text. Expecting a unicode object, "
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/html.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/html.py
index 06c6020f543..0af2b18b57a 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/html.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/formatted_text/html.py
@@ -1,4 +1,5 @@
import xml.dom.minidom as minidom
+from string import Formatter
from typing import Any, List, Tuple, Union
from .base import FormattedText, StyleAndTextTuples
@@ -29,7 +30,7 @@ class HTML:
def __init__(self, value: str) -> None:
self.value = value
- document = minidom.parseString("<html-root>%s</html-root>" % (value,))
+ document = minidom.parseString(f"<html-root>{value}</html-root>")
result: StyleAndTextTuples = []
name_stack: List[str] = []
@@ -97,7 +98,7 @@ class HTML:
self.formatted_text = FormattedText(result)
def __repr__(self) -> str:
- return "HTML(%r)" % (self.value,)
+ return f"HTML({self.value!r})"
def __pt_formatted_text__(self) -> StyleAndTextTuples:
return self.formatted_text
@@ -107,13 +108,9 @@ class HTML:
Like `str.format`, but make sure that the arguments are properly
escaped.
"""
- # Escape all the arguments.
- escaped_args = [html_escape(a) for a in args]
- escaped_kwargs = {k: html_escape(v) for k, v in kwargs.items()}
+ return HTML(FORMATTER.vformat(self.value, args, kwargs))
- return HTML(self.value.format(*escaped_args, **escaped_kwargs))
-
- def __mod__(self, value: Union[object, Tuple[object, ...]]) -> "HTML":
+ def __mod__(self, value: object) -> "HTML":
"""
HTML('<b>%s</b>') % value
"""
@@ -124,11 +121,16 @@ class HTML:
return HTML(self.value % value)
+class HTMLFormatter(Formatter):
+ def format_field(self, value: object, format_spec: str) -> str:
+ return html_escape(format(value, format_spec))
+
+
def html_escape(text: object) -> str:
# The string interpolation functions also take integers and other types.
# Convert to string first.
if not isinstance(text, str):
- text = "{}".format(text)
+ text = f"{text}"
return (
text.replace("&", "&amp;")
@@ -136,3 +138,6 @@ def html_escape(text: object) -> str:
.replace(">", "&gt;")
.replace('"', "&quot;")
)
+
+
+FORMATTER = HTMLFormatter()
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/history.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/history.py
index d6bc3e67797..987d7175de1 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/history.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/history.py
@@ -211,7 +211,7 @@ class ThreadedHistory(History):
self.history.store_string(string)
def __repr__(self) -> str:
- return "ThreadedHistory(%r)" % (self.history,)
+ return f"ThreadedHistory({self.history!r})"
class InMemoryHistory(History):
@@ -231,8 +231,7 @@ class InMemoryHistory(History):
self._storage = list(history_strings)
def load_history_strings(self) -> Iterable[str]:
- for item in self._storage[::-1]:
- yield item
+ yield from self._storage[::-1]
def store_string(self, string: str) -> None:
self._storage.append(string)
@@ -261,7 +260,7 @@ class FileHistory(History):
def __init__(self, filename: str) -> None:
self.filename = filename
- super(FileHistory, self).__init__()
+ super().__init__()
def load_history_strings(self) -> Iterable[str]:
strings: List[str] = []
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_pipe.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_pipe.py
index de47c649330..22dd7be6b5d 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_pipe.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_pipe.py
@@ -69,4 +69,4 @@ class PosixPipeInput(Vt100Input, PipeInput):
"""
This needs to be unique for every `PipeInput`.
"""
- return "pipe-input-%s" % (self._id,)
+ return f"pipe-input-{self._id}"
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_utils.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_utils.py
index f32f683f735..7cf31eebe6d 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_utils.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_utils.py
@@ -71,7 +71,7 @@ class PosixStdinReader:
try:
if not select.select([self.stdin_fd], [], [], 0)[0]:
return ""
- except IOError:
+ except OSError:
# Happens for instance when the file descriptor was closed.
# (We had this in ptterm, where the FD became ready, a callback was
# scheduled, but in the meantime another callback closed it already.)
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100.py
index 455cf8efd1f..639d372609b 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/vt100.py
@@ -137,7 +137,7 @@ class Vt100Input(Input):
return self.stdin.fileno()
def typeahead_hash(self) -> str:
- return "fd-%s" % (self._fileno,)
+ return f"fd-{self._fileno}"
_current_callbacks: Dict[
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py
index 97699e19b24..c59375b3d46 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32.py
@@ -286,8 +286,7 @@ class ConsoleInputReader:
if k is not None:
yield k
else:
- for k2 in all_keys:
- yield k2
+ yield from all_keys
def _insert_key_data(self, key_press: KeyPress) -> KeyPress:
"""
@@ -322,12 +321,10 @@ class ConsoleInputReader:
# Process if this is a key event. (We also have mouse, menu and
# focus events.)
if type(ev) == KEY_EVENT_RECORD and ev.KeyDown:
- for key_press in self._event_to_key_presses(ev):
- yield key_press
+ yield from self._event_to_key_presses(ev)
elif type(ev) == MOUSE_EVENT_RECORD:
- for key_press in self._handle_mouse(ev):
- yield key_press
+ yield from self._handle_mouse(ev)
@staticmethod
def _merge_paired_surrogates(key_presses: List[KeyPress]) -> Iterator[KeyPress]:
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py
index cdcf084de11..fdbcb8ee83b 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/win32_pipe.py
@@ -132,4 +132,4 @@ class Win32PipeInput(_Win32InputBase, PipeInput):
"""
This needs to be unique for every `PipeInput`.
"""
- return "pipe-input-%s" % (self._id,)
+ return f"pipe-input-{self._id}"
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/completion.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/completion.py
index e52edf87ffe..a30b54e632d 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/completion.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/bindings/completion.py
@@ -146,7 +146,7 @@ def _display_completions_like_readline(
if len(completions) > completions_per_page:
# Ask confirmation if it doesn't fit on the screen.
confirm = await create_confirm_session(
- "Display all {} possibilities?".format(len(completions)),
+ f"Display all {len(completions)} possibilities?",
).prompt_async()
if confirm:
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/digraphs.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/digraphs.py
index 70606086aa3..ad3d288a8a3 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/digraphs.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/digraphs.py
@@ -1,4 +1,3 @@
-# encoding: utf-8
"""
Vi Digraphs.
This is a list of special characters that can be inserted in Vi insert mode by
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py
index 06ca376b094..03bc79ef01d 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_bindings.py
@@ -138,7 +138,7 @@ class Binding:
event.app.invalidate()
def __repr__(self) -> str:
- return "%s(keys=%r, handler=%r)" % (
+ return "{}(keys={!r}, handler={!r})".format(
self.__class__.__name__,
self.keys,
self.handler,
@@ -359,7 +359,7 @@ class KeyBindings(KeyBindingsBase):
self._clear_cache()
else:
# No key binding found for this function. Raise ValueError.
- raise ValueError("Binding not found: %r" % (function,))
+ raise ValueError(f"Binding not found: {function!r}")
# For backwards-compatibility.
add_binding = add
@@ -449,7 +449,7 @@ def _parse_key(key: Union[Keys, str]) -> Union[str, Keys]:
# Final validation.
if len(key) != 1:
- raise ValueError("Invalid key: %s" % (key,))
+ raise ValueError(f"Invalid key: {key}")
return key
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py
index 476393c1eee..6fdd5191791 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py
@@ -1,4 +1,3 @@
-# *** encoding: utf-8 ***
"""
An :class:`~.KeyProcessor` receives callbacks for the keystrokes parsed from
the input in the :class:`~prompt_toolkit.inputstream.InputStream` instance.
@@ -50,7 +49,7 @@ class KeyPress:
self.data = data
def __repr__(self) -> str:
- return "%s(key=%r, data=%r)" % (self.__class__.__name__, self.key, self.data)
+ return f"{self.__class__.__name__}(key={self.key!r}, data={self.data!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, KeyPress):
@@ -137,9 +136,9 @@ class KeyProcessor:
# Note that we transform it into a `set`, because we don't care about
# the actual bindings and executing it more than once doesn't make
# sense. (Many key bindings share the same filter.)
- filters = set(
+ filters = {
b.filter for b in self._bindings.get_bindings_starting_with_keys(keys)
- )
+ }
# When any key binding is active, return True.
return any(f() for f in filters)
@@ -450,7 +449,7 @@ class KeyPressEvent:
self._app = get_app()
def __repr__(self) -> str:
- return "KeyPressEvent(arg=%r, key_sequence=%r, is_repeat=%r)" % (
+ return "KeyPressEvent(arg={!r}, key_sequence={!r}, is_repeat={!r})".format(
self.arg,
self.key_sequence,
self.is_repeat,
@@ -519,7 +518,7 @@ class KeyPressEvent:
elif current is None:
result = data
else:
- result = "%s%s" % (current, data)
+ result = f"{current}{data}"
self.key_processor.arg = result
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py
index 2c845a76aa0..03f9e7d2485 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/containers.py
@@ -1365,7 +1365,7 @@ class ScrollOffsets:
return to_int(self._right)
def __repr__(self) -> str:
- return "ScrollOffsets(top=%r, bottom=%r, left=%r, right=%r)" % (
+ return "ScrollOffsets(top={!r}, bottom={!r}, left={!r}, right={!r})".format(
self._top,
self._bottom,
self._left,
@@ -2627,7 +2627,7 @@ class ConditionalContainer(Container):
self.filter = to_filter(filter)
def __repr__(self) -> str:
- return "ConditionalContainer(%r, filter=%r)" % (self.content, self.filter)
+ return f"ConditionalContainer({self.content!r}, filter={self.filter!r})"
def reset(self) -> None:
self.content.reset()
@@ -2730,7 +2730,7 @@ def to_container(container: AnyContainer) -> Container:
elif hasattr(container, "__pt_container__"):
return to_container(container.__pt_container__())
else:
- raise ValueError("Not a container object: %r" % (container,))
+ raise ValueError(f"Not a container object: {container!r}")
def to_window(container: AnyContainer) -> Window:
@@ -2742,7 +2742,7 @@ def to_window(container: AnyContainer) -> Window:
elif hasattr(container, "__pt_container__"):
return to_window(cast("MagicContainer", container).__pt_container__())
else:
- raise ValueError("Not a Window object: %r." % (container,))
+ raise ValueError(f"Not a Window object: {container!r}.")
def is_container(value: object) -> "TypeGuard[AnyContainer]":
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py
index 45b50e68f83..016d2894665 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/controls.py
@@ -336,7 +336,7 @@ class FormattedTextControl(UIControl):
return self.focusable()
def __repr__(self) -> str:
- return "%s(%r)" % (self.__class__.__name__, self.text)
+ return f"{self.__class__.__name__}({self.text!r})"
def _get_formatted_text_cached(self) -> StyleAndTextTuples:
"""
@@ -495,14 +495,10 @@ class DummyControl(UIControl):
return False
-_ProcessedLine = NamedTuple(
- "_ProcessedLine",
- [
- ("fragments", StyleAndTextTuples),
- ("source_to_display", Callable[[int], int]),
- ("display_to_source", Callable[[int], int]),
- ],
-)
+class _ProcessedLine(NamedTuple):
+ fragments: StyleAndTextTuples
+ source_to_display: Callable[[int], int]
+ display_to_source: Callable[[int], int]
class BufferControl(UIControl):
@@ -573,7 +569,7 @@ class BufferControl(UIControl):
self._last_get_processed_line: Optional[Callable[[int], _ProcessedLine]] = None
def __repr__(self) -> str:
- return "<%s buffer=%r at %r>" % (self.__class__.__name__, self.buffer, id(self))
+ return f"<{self.__class__.__name__} buffer={self.buffer!r} at {id(self)!r}>"
@property
def search_buffer_control(self) -> Optional["SearchBufferControl"]:
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py
index 28bfcb3cac9..62a3184ee22 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py
@@ -70,7 +70,7 @@ class Layout:
self.visible_windows: List[Window] = [] # List of `Window` objects.
def __repr__(self) -> str:
- return "Layout(%r, current_window=%r)" % (self.container, self.current_window)
+ return f"Layout({self.container!r}, current_window={self.current_window!r})"
def find_all_windows(self) -> Generator[Window, None, None]:
"""
@@ -103,9 +103,7 @@ class Layout:
if isinstance(control, BufferControl) and control.buffer.name == value:
self.focus(control)
return
- raise ValueError(
- "Couldn't find Buffer in the current layout: %r." % (value,)
- )
+ raise ValueError(f"Couldn't find Buffer in the current layout: {value!r}.")
# BufferControl by buffer object.
elif isinstance(value, Buffer):
@@ -113,9 +111,7 @@ class Layout:
if isinstance(control, BufferControl) and control.buffer == value:
self.focus(control)
return
- raise ValueError(
- "Couldn't find Buffer in the current layout: %r." % (value,)
- )
+ raise ValueError(f"Couldn't find Buffer in the current layout: {value!r}.")
# Focus UIControl.
elif isinstance(value, UIControl):
@@ -164,7 +160,7 @@ class Layout:
return
raise ValueError(
- "Invalid value. Container cannot be focused: %r" % (value,)
+ f"Invalid value. Container cannot be focused: {value!r}"
)
def has_focus(self, value: FocusableElement) -> bool:
@@ -342,8 +338,7 @@ class Layout:
"""
Walk through all the layout nodes (and their children) and yield them.
"""
- for i in walk(self.container):
- yield i
+ yield from walk(self.container)
def walk_through_modal_area(self) -> Iterable[Container]:
"""
@@ -356,8 +351,7 @@ class Layout:
while not root.is_modal() and root in self._child_to_parent:
root = self._child_to_parent[root]
- for container in walk(root):
- yield container
+ yield from walk(root)
def update_parents_relations(self) -> None:
"""
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py
index 557450c0005..8218f741079 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/menus.py
@@ -218,7 +218,7 @@ def _get_menu_item_fragments(
width.
"""
if is_current_completion:
- style_str = "class:completion-menu.completion.current %s %s" % (
+ style_str = "class:completion-menu.completion.current {} {}".format(
completion.style,
completion.selected_style,
)
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py
index 571e952971b..722658a846b 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py
@@ -201,8 +201,8 @@ class HighlightSearchProcessor(Processor):
) = transformation_input.unpack()
search_text = self._get_search_text(buffer_control)
- searchmatch_fragment = " class:%s " % (self._classname,)
- searchmatch_current_fragment = " class:%s " % (self._classname_current,)
+ searchmatch_fragment = f" class:{self._classname} "
+ searchmatch_current_fragment = f" class:{self._classname_current} "
if search_text and not get_app().is_done:
# For each search match, replace the style string.
@@ -526,7 +526,7 @@ class BeforeInput(Processor):
)
def __repr__(self) -> str:
- return "BeforeInput(%r, %r)" % (self.text, self.style)
+ return f"BeforeInput({self.text!r}, {self.style!r})"
class ShowArg(BeforeInput):
@@ -580,7 +580,7 @@ class AfterInput(Processor):
return Transformation(fragments=ti.fragments)
def __repr__(self) -> str:
- return "%s(%r, style=%r)" % (self.__class__.__name__, self.text, self.style)
+ return f"{self.__class__.__name__}({self.text!r}, style={self.style!r})"
class AppendAutoSuggestion(Processor):
@@ -940,7 +940,7 @@ class ConditionalProcessor(Processor):
return Transformation(transformation_input.fragments)
def __repr__(self) -> str:
- return "%s(processor=%r, filter=%r)" % (
+ return "{}(processor={!r}, filter={!r})".format(
self.__class__.__name__,
self.processor,
self.filter,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/screen.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/screen.py
index deb2f432227..5d27ab26c9f 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/screen.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/screen.py
@@ -135,7 +135,7 @@ class Char:
__ne__ = _not_equal
def __repr__(self) -> str:
- return "%s(%r, %r)" % (self.__class__.__name__, self.char, self.style)
+ return f"{self.__class__.__name__}({self.char!r}, {self.style!r})"
_CHAR_CACHE: FastDictCache[Tuple[str, str], Char] = FastDictCache(
@@ -318,7 +318,7 @@ class WritePosition:
self.height = height
def __repr__(self) -> str:
- return "%s(x=%r, y=%r, width=%r, height=%r)" % (
+ return "{}(x={!r}, y={!r}, width={!r}, height={!r})".format(
self.__class__.__name__,
self.xpos,
self.ypos,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/mouse_events.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/mouse_events.py
index 26f4312043b..e10ff0322ab 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/mouse_events.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/mouse_events.py
@@ -80,7 +80,7 @@ class MouseEvent:
self.modifiers = modifiers
def __repr__(self) -> str:
- return "MouseEvent(%r,%r,%r,%r)" % (
+ return "MouseEvent({!r},{!r},{!r},{!r})".format(
self.position,
self.event_type,
self.button,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/flush_stdout.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/flush_stdout.py
index 4adcbd109d0..05a342312d3 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/flush_stdout.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/flush_stdout.py
@@ -32,7 +32,7 @@ def flush_stdout(stdout: TextIO, data: str, write_binary: bool) -> None:
stdout.write(data)
stdout.flush()
- except IOError as e:
+ except OSError as e:
if e.args and e.args[0] == errno.EINTR:
# Interrupted system call. Can happen in case of a window
# resize signal. (Just ignore. The resize handler will render
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/win32.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/win32.py
index abfd61774be..a73978c3ef2 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/win32.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/output/win32.py
@@ -173,9 +173,7 @@ class Win32Output(Output):
return func(*a, **kw)
except ArgumentError as e:
if _DEBUG_RENDER_OUTPUT:
- self.LOG.write(
- (" Error in %r %r %s\n" % (func.__name__, e, e)).encode("utf-8")
- )
+ self.LOG.write((f" Error in {func.__name__!r} {e!r} {e}\n").encode())
raise
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py
index d670c3c57bb..e40fc9e875f 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/renderer.py
@@ -416,6 +416,8 @@ class Renderer:
self.output.disable_bracketed_paste()
self._bracketed_paste_enabled = False
+ self.output.reset_cursor_shape()
+
# NOTE: No need to set/reset cursor key mode here.
# Flush output. `disable_mouse_support` needs to write to stdout.
@@ -740,7 +742,6 @@ class Renderer:
output.erase_down()
output.reset_attributes()
output.enable_autowrap()
- output.reset_cursor_shape()
output.flush()
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py
index 6f94afe9241..413cc6ad9c7 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py
@@ -58,7 +58,7 @@ class SearchState:
self.ignore_case = to_filter(ignore_case)
def __repr__(self) -> str:
- return "%s(%r, direction=%r, ignore_case=%r)" % (
+ return "{}({!r}, direction={!r}, ignore_case={!r})".format(
self.__class__.__name__,
self.text,
self.direction,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/selection.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/selection.py
index 5d2545bd116..a02aa8708cb 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/selection.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/selection.py
@@ -53,7 +53,7 @@ class SelectionState:
self.shift_mode = True
def __repr__(self) -> str:
- return "%s(original_cursor_position=%r, type=%r)" % (
+ return "{}(original_cursor_position={!r}, type={!r})".format(
self.__class__.__name__,
self.original_cursor_position,
self.type,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/dialogs.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/dialogs.py
index a91bb3142cd..9140f86ab32 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/dialogs.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/dialogs.py
@@ -1,5 +1,5 @@
import functools
-from typing import Any, Callable, List, Optional, Tuple, TypeVar
+from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar
from prompt_toolkit.application import Application
from prompt_toolkit.application.current import get_app
@@ -174,7 +174,8 @@ def radiolist_dialog(
text: AnyFormattedText = "",
ok_text: str = "Ok",
cancel_text: str = "Cancel",
- values: Optional[List[Tuple[_T, AnyFormattedText]]] = None,
+ values: Optional[Sequence[Tuple[_T, AnyFormattedText]]] = None,
+ default: Optional[_T] = None,
style: Optional[BaseStyle] = None,
) -> Application[_T]:
"""
@@ -189,7 +190,7 @@ def radiolist_dialog(
def ok_handler() -> None:
get_app().exit(result=radio_list.current_value)
- radio_list = RadioList(values)
+ radio_list = RadioList(values=values, default=default)
dialog = Dialog(
title=title,
@@ -212,7 +213,8 @@ def checkboxlist_dialog(
text: AnyFormattedText = "",
ok_text: str = "Ok",
cancel_text: str = "Cancel",
- values: Optional[List[Tuple[_T, AnyFormattedText]]] = None,
+ values: Optional[Sequence[Tuple[_T, AnyFormattedText]]] = None,
+ default_values: Optional[Sequence[_T]] = None,
style: Optional[BaseStyle] = None,
) -> Application[List[_T]]:
"""
@@ -227,7 +229,7 @@ def checkboxlist_dialog(
def ok_handler() -> None:
get_app().exit(result=cb_list.current_values)
- cb_list = CheckboxList(values)
+ cb_list = CheckboxList(values=values, default_values=default_values)
dialog = Dialog(
title=title,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/progress_bar/formatters.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/progress_bar/formatters.py
index ad3a932d3fd..1383d7a6b5b 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/progress_bar/formatters.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/progress_bar/formatters.py
@@ -231,7 +231,7 @@ class Progress(Formatter):
def get_width(self, progress_bar: "ProgressBar") -> AnyDimension:
all_lengths = [
- len("{0:>3}".format(c.total or "?")) for c in progress_bar.counters
+ len("{:>3}".format(c.total or "?")) for c in progress_bar.counters
]
all_lengths.append(1)
return D.exact(max(all_lengths) * 2 + 1)
@@ -241,7 +241,7 @@ def _format_timedelta(timedelta: datetime.timedelta) -> str:
"""
Return hh:mm:ss, or mm:ss if the amount of hours is zero.
"""
- result = "{0}".format(timedelta).split(".")[0]
+ result = f"{timedelta}".split(".")[0]
if result.startswith("0:"):
result = result[2:]
return result
@@ -327,7 +327,7 @@ class IterationsPerSecond(Formatter):
def get_width(self, progress_bar: "ProgressBar") -> AnyDimension:
all_values = [
- len("{0:.2f}".format(c.items_completed / c.time_elapsed.total_seconds()))
+ len(f"{c.items_completed / c.time_elapsed.total_seconds():.2f}")
for c in progress_bar.counters
]
if all_values:
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py
index 4e2a532b346..c7ce74e6271 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/shortcuts/utils.py
@@ -119,7 +119,7 @@ def print_formatted_text(
# Normal lists which are not instances of `FormattedText` are
# considered plain text.
if isinstance(val, list) and not isinstance(val, FormattedText):
- return to_formatted_text("{0}".format(val))
+ return to_formatted_text(f"{val}")
return to_formatted_text(val, auto_convert=True)
fragments = []
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/base.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/base.py
index 609283b7c6b..aa77b9ad086 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/base.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/base.py
@@ -16,20 +16,17 @@ __all__ = [
#: Style attributes.
-Attrs = NamedTuple(
- "Attrs",
- [
- ("color", Optional[str]),
- ("bgcolor", Optional[str]),
- ("bold", Optional[bool]),
- ("underline", Optional[bool]),
- ("strike", Optional[bool]),
- ("italic", Optional[bool]),
- ("blink", Optional[bool]),
- ("reverse", Optional[bool]),
- ("hidden", Optional[bool]),
- ],
-)
+class Attrs(NamedTuple):
+ color: Optional[str]
+ bgcolor: Optional[str]
+ bold: Optional[bool]
+ underline: Optional[bool]
+ strike: Optional[bool]
+ italic: Optional[bool]
+ blink: Optional[bool]
+ reverse: Optional[bool]
+ hidden: Optional[bool]
+
"""
:param color: Hexadecimal string. E.g. '000000' or Ansi color name: e.g. 'ansiblue'
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style.py
index 1474360fd22..6e4bd1f43c3 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style.py
@@ -196,14 +196,9 @@ class Priority(Enum):
MOST_PRECISE = "MOST_PRECISE"
-# In the latest python verions, we take the dictionary ordering like it is,
-# In older versions, we sort by by precision. If you need to write code that
-# runs on all Python versions, it's best to sort them manually, with the most
-# precise rules at the bottom.
-if sys.version_info >= (3, 6):
- default_priority = Priority.DICT_KEY_ORDER
-else:
- default_priority = Priority.MOST_PRECISE
+# We don't support Python versions older than 3.6 anymore, so we can always
+# depend on dictionary ordering. This is the default.
+default_priority = Priority.DICT_KEY_ORDER
class Style(BaseStyle):
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style_transformation.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style_transformation.py
index 15b858aa9f7..91308f91274 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style_transformation.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/styles/style_transformation.py
@@ -51,7 +51,7 @@ class StyleTransformation(metaclass=ABCMeta):
"""
When this changes, the cache should be invalidated.
"""
- return "%s-%s" % (self.__class__.__name__, id(self))
+ return f"{self.__class__.__name__}-{id(self)}"
class SwapLightAndDarkStyleTransformation(StyleTransformation):
@@ -182,7 +182,7 @@ class AdjustBrightnessStyleTransformation(StyleTransformation):
brightness, min_brightness, max_brightness
)
r, g, b = hls_to_rgb(hue, brightness, saturation)
- new_color = "%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255))
+ new_color = f"{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
attrs = attrs._replace(color=new_color)
@@ -372,4 +372,4 @@ def get_opposite_color(colorname: Optional[str]) -> Optional[str]:
g = int(g * 255)
b = int(b * 255)
- return "%02x%02x%02x" % (r, g, b)
+ return f"{r:02x}{g:02x}{b:02x}"
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/validation.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/validation.py
index db2f3fd1c61..8bdffff524d 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/validation.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/validation.py
@@ -34,7 +34,7 @@ class ValidationError(Exception):
self.message = message
def __repr__(self) -> str:
- return "%s(cursor_position=%r, message=%r)" % (
+ return "{}(cursor_position={!r}, message={!r})".format(
self.__class__.__name__,
self.cursor_position,
self.message,
@@ -114,7 +114,7 @@ class _ValidatorFromCallable(Validator):
self.move_cursor_to_end = move_cursor_to_end
def __repr__(self) -> str:
- return "Validator.from_callable(%r)" % (self.func,)
+ return f"Validator.from_callable({self.func!r})"
def validate(self, document: Document) -> None:
if not self.func(document.text):
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/base.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/base.py
index 728190b54c2..885d23a8891 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/base.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/base.py
@@ -433,7 +433,7 @@ class Button:
width = self.width - (
get_cwidth(self.left_symbol) + get_cwidth(self.right_symbol)
)
- text = ("{{:^{}}}".format(width)).format(self.text)
+ text = (f"{{:^{width}}}").format(self.text)
def handler(mouse_event: MouseEvent) -> None:
if (
@@ -686,15 +686,32 @@ class _DialogList(Generic[_T]):
multiple_selection: bool = False
show_scrollbar: bool = True
- def __init__(self, values: Sequence[Tuple[_T, AnyFormattedText]]) -> None:
+ def __init__(
+ self,
+ values: Sequence[Tuple[_T, AnyFormattedText]],
+ default_values: Optional[Sequence[_T]] = None,
+ ) -> None:
assert len(values) > 0
+ default_values = default_values or []
self.values = values
# current_values will be used in multiple_selection,
# current_value will be used otherwise.
- self.current_values: List[_T] = []
- self.current_value: _T = values[0][0]
- self._selected_index = 0
+ keys: List[_T] = [value for (value, _) in values]
+ self.current_values: List[_T] = [
+ value for value in default_values if value in keys
+ ]
+ self.current_value: _T = (
+ default_values[0]
+ if len(default_values) and default_values[0] in keys
+ else values[0][0]
+ )
+
+ # Cursor index: take first selected item or first item otherwise.
+ if len(self.current_values) > 0:
+ self._selected_index = keys.index(self.current_values[0])
+ else:
+ self._selected_index = 0
# Key bindings.
kb = KeyBindings()
@@ -832,6 +849,18 @@ class RadioList(_DialogList[_T]):
checked_style = "class:radio-checked"
multiple_selection = False
+ def __init__(
+ self,
+ values: Sequence[Tuple[_T, AnyFormattedText]],
+ default: Optional[_T] = None,
+ ) -> None:
+ if default is None:
+ default_values = None
+ else:
+ default_values = [default]
+
+ super().__init__(values, default_values=default_values)
+
class CheckboxList(_DialogList[_T]):
"""
@@ -859,7 +888,7 @@ class Checkbox(CheckboxList[str]):
def __init__(self, text: AnyFormattedText = "", checked: bool = False) -> None:
values = [("value", text)]
- CheckboxList.__init__(self, values)
+ CheckboxList.__init__(self, values=values)
self.checked = checked
@property
@@ -874,7 +903,7 @@ class Checkbox(CheckboxList[str]):
self.current_values = []
-class VerticalLine(object):
+class VerticalLine:
"""
A simple vertical line with a width of 1.
"""
@@ -943,7 +972,7 @@ class ProgressBar:
@percentage.setter
def percentage(self, value: int) -> None:
self._percentage = value
- self.label.text = "{0}%".format(value)
+ self.label.text = f"{value}%"
def __pt_container__(self) -> Container:
return self.container
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/menus.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/menus.py
index 7203aae1181..6827ebecc7c 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/menus.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/menus.py
@@ -310,13 +310,13 @@ class MenuContainer:
if item.text == "-":
yield (
style + "class:menu-border",
- "{}".format(Border.HORIZONTAL * (menu.width + 3)),
+ f"{Border.HORIZONTAL * (menu.width + 3)}",
mouse_handler,
)
else:
yield (
style,
- " {}".format(item.text).ljust(menu.width + 3),
+ f" {item.text}".ljust(menu.width + 3),
mouse_handler,
)
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/toolbars.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/toolbars.py
index c3559c2b83c..e464be04ac1 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/toolbars.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/widgets/toolbars.py
@@ -352,7 +352,7 @@ class ValidationToolbar:
)
if show_position:
- text = "%s (line=%s column=%s)" % (
+ text = "{} (line={} column={})".format(
buff.validation_error.message,
row + 1,
column + 1,
diff --git a/contrib/python/prompt-toolkit/py3/prompt_toolkit/win32_types.py b/contrib/python/prompt-toolkit/py3/prompt_toolkit/win32_types.py
index e721e5ef7cc..4ae2e393f48 100644
--- a/contrib/python/prompt-toolkit/py3/prompt_toolkit/win32_types.py
+++ b/contrib/python/prompt-toolkit/py3/prompt_toolkit/win32_types.py
@@ -26,7 +26,7 @@ class COORD(Structure):
]
def __repr__(self) -> str:
- return "%s(X=%r, Y=%r, type_x=%r, type_y=%r)" % (
+ return "{}(X={!r}, Y={!r}, type_x={!r}, type_y={!r})".format(
self.__class__.__name__,
self.X,
self.Y,
@@ -195,7 +195,7 @@ class CONSOLE_SCREEN_BUFFER_INFO(Structure):
]
def __repr__(self) -> str:
- return "CONSOLE_SCREEN_BUFFER_INFO(%r,%r,%r,%r,%r,%r,%r,%r,%r,%r,%r)" % (
+ return "CONSOLE_SCREEN_BUFFER_INFO({!r},{!r},{!r},{!r},{!r},{!r},{!r},{!r},{!r},{!r},{!r})".format(
self.dwSize.Y,
self.dwSize.X,
self.dwCursorPosition.Y,
diff --git a/contrib/python/prompt-toolkit/py3/tests/test_cli.py b/contrib/python/prompt-toolkit/py3/tests/test_cli.py
index 9c623f1c0c5..678bc526365 100644
--- a/contrib/python/prompt-toolkit/py3/tests/test_cli.py
+++ b/contrib/python/prompt-toolkit/py3/tests/test_cli.py
@@ -1,4 +1,3 @@
-# encoding: utf-8
"""
These are almost end-to-end tests. They create a Prompt, feed it with some
input and check the result.
diff --git a/contrib/python/prompt-toolkit/py3/tests/test_completion.py b/contrib/python/prompt-toolkit/py3/tests/test_completion.py
index f5c2a582a17..6c71620d113 100644
--- a/contrib/python/prompt-toolkit/py3/tests/test_completion.py
+++ b/contrib/python/prompt-toolkit/py3/tests/test_completion.py
@@ -33,7 +33,7 @@ def write_test_files(test_dir, names=None):
names = names or range(10)
for i in names:
with open(os.path.join(test_dir, str(i)), "wb") as out:
- out.write("".encode("UTF-8"))
+ out.write(b"")
def test_pathcompleter_completes_in_current_directory():
@@ -50,7 +50,7 @@ def test_pathcompleter_completes_files_in_current_directory():
test_dir = tempfile.mkdtemp()
write_test_files(test_dir)
- expected = sorted([str(i) for i in range(10)])
+ expected = sorted(str(i) for i in range(10))
if not test_dir.endswith(os.path.sep):
test_dir += os.path.sep
@@ -74,7 +74,7 @@ def test_pathcompleter_completes_files_in_absolute_directory():
test_dir = tempfile.mkdtemp()
write_test_files(test_dir)
- expected = sorted([str(i) for i in range(10)])
+ expected = sorted(str(i) for i in range(10))
test_dir = os.path.abspath(test_dir)
if not test_dir.endswith(os.path.sep):
@@ -86,7 +86,7 @@ def test_pathcompleter_completes_files_in_absolute_directory():
doc = Document(doc_text, len(doc_text))
event = CompleteEvent()
completions = list(completer.get_completions(doc, event))
- result = sorted([c.text for c in completions])
+ result = sorted(c.text for c in completions)
assert expected == result
# cleanup
diff --git a/contrib/python/prompt-toolkit/py3/tests/test_formatted_text.py b/contrib/python/prompt-toolkit/py3/tests/test_formatted_text.py
index 23f5ccfd57f..8b4924f968a 100644
--- a/contrib/python/prompt-toolkit/py3/tests/test_formatted_text.py
+++ b/contrib/python/prompt-toolkit/py3/tests/test_formatted_text.py
@@ -103,6 +103,71 @@ def test_ansi_true_color():
]
+def test_ansi_interpolation():
+ # %-style interpolation.
+ value = ANSI("\x1b[1m%s\x1b[0m") % "hello\x1b"
+ assert to_formatted_text(value) == [
+ ("bold", "h"),
+ ("bold", "e"),
+ ("bold", "l"),
+ ("bold", "l"),
+ ("bold", "o"),
+ ("bold", "?"),
+ ]
+
+ value = ANSI("\x1b[1m%s\x1b[0m") % ("\x1bhello",)
+ assert to_formatted_text(value) == [
+ ("bold", "?"),
+ ("bold", "h"),
+ ("bold", "e"),
+ ("bold", "l"),
+ ("bold", "l"),
+ ("bold", "o"),
+ ]
+
+ value = ANSI("\x1b[32m%s\x1b[45m%s") % ("He", "\x1bllo")
+ assert to_formatted_text(value) == [
+ ("ansigreen", "H"),
+ ("ansigreen", "e"),
+ ("ansigreen bg:ansimagenta", "?"),
+ ("ansigreen bg:ansimagenta", "l"),
+ ("ansigreen bg:ansimagenta", "l"),
+ ("ansigreen bg:ansimagenta", "o"),
+ ]
+
+ # Format function.
+ value = ANSI("\x1b[32m{0}\x1b[45m{1}").format("He\x1b", "llo")
+ assert to_formatted_text(value) == [
+ ("ansigreen", "H"),
+ ("ansigreen", "e"),
+ ("ansigreen", "?"),
+ ("ansigreen bg:ansimagenta", "l"),
+ ("ansigreen bg:ansimagenta", "l"),
+ ("ansigreen bg:ansimagenta", "o"),
+ ]
+
+ value = ANSI("\x1b[32m{a}\x1b[45m{b}").format(a="\x1bHe", b="llo")
+ assert to_formatted_text(value) == [
+ ("ansigreen", "?"),
+ ("ansigreen", "H"),
+ ("ansigreen", "e"),
+ ("ansigreen bg:ansimagenta", "l"),
+ ("ansigreen bg:ansimagenta", "l"),
+ ("ansigreen bg:ansimagenta", "o"),
+ ]
+
+ value = ANSI("\x1b[32m{:02d}\x1b[45m{:.3f}").format(3, 3.14159)
+ assert to_formatted_text(value) == [
+ ("ansigreen", "0"),
+ ("ansigreen", "3"),
+ ("ansigreen bg:ansimagenta", "3"),
+ ("ansigreen bg:ansimagenta", "."),
+ ("ansigreen bg:ansimagenta", "1"),
+ ("ansigreen bg:ansimagenta", "4"),
+ ("ansigreen bg:ansimagenta", "2"),
+ ]
+
+
def test_interpolation():
value = Template(" {} ").format(HTML("<b>hello</b>"))
@@ -125,22 +190,25 @@ def test_interpolation():
def test_html_interpolation():
# %-style interpolation.
- value = HTML("<b>%s</b>") % "hello"
- assert to_formatted_text(value) == [("class:b", "hello")]
+ value = HTML("<b>%s</b>") % "&hello"
+ assert to_formatted_text(value) == [("class:b", "&hello")]
- value = HTML("<b>%s</b>") % ("hello",)
- assert to_formatted_text(value) == [("class:b", "hello")]
+ value = HTML("<b>%s</b>") % ("<hello>",)
+ assert to_formatted_text(value) == [("class:b", "<hello>")]
- value = HTML("<b>%s</b><u>%s</u>") % ("hello", "world")
- assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")]
+ value = HTML("<b>%s</b><u>%s</u>") % ("<hello>", "</world>")
+ assert to_formatted_text(value) == [("class:b", "<hello>"), ("class:u", "</world>")]
# Format function.
- value = HTML("<b>{0}</b><u>{1}</u>").format("hello", "world")
- assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")]
+ value = HTML("<b>{0}</b><u>{1}</u>").format("'hello'", '"world"')
+ assert to_formatted_text(value) == [("class:b", "'hello'"), ("class:u", '"world"')]
value = HTML("<b>{a}</b><u>{b}</u>").format(a="hello", b="world")
assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")]
+ value = HTML("<b>{:02d}</b><u>{:.3f}</u>").format(3, 3.14159)
+ assert to_formatted_text(value) == [("class:b", "03"), ("class:u", "3.142")]
+
def test_merge_formatted_text():
html1 = HTML("<u>hello</u>")
diff --git a/contrib/python/prompt-toolkit/py3/tests/test_inputstream.py b/contrib/python/prompt-toolkit/py3/tests/test_inputstream.py
index f5ae1e39656..8c3d8fd7c45 100644
--- a/contrib/python/prompt-toolkit/py3/tests/test_inputstream.py
+++ b/contrib/python/prompt-toolkit/py3/tests/test_inputstream.py
@@ -4,7 +4,7 @@ from prompt_toolkit.input.vt100_parser import Vt100Parser
from prompt_toolkit.keys import Keys
-class _ProcessorMock(object):
+class _ProcessorMock:
def __init__(self):
self.keys = []
diff --git a/contrib/python/prompt-toolkit/py3/tests/test_key_binding.py b/contrib/python/prompt-toolkit/py3/tests/test_key_binding.py
index f1ec5af36dd..617e71c1e1d 100644
--- a/contrib/python/prompt-toolkit/py3/tests/test_key_binding.py
+++ b/contrib/python/prompt-toolkit/py3/tests/test_key_binding.py
@@ -10,7 +10,7 @@ from prompt_toolkit.layout import Layout, Window
from prompt_toolkit.output import DummyOutput
-class Handlers(object):
+class Handlers:
def __init__(self):
self.called = []
diff --git a/contrib/python/prompt-toolkit/py3/ya.make b/contrib/python/prompt-toolkit/py3/ya.make
index d53f98a7c37..005ffcd1762 100644
--- a/contrib/python/prompt-toolkit/py3/ya.make
+++ b/contrib/python/prompt-toolkit/py3/ya.make
@@ -4,7 +4,7 @@ PY3_LIBRARY()
OWNER(g:python-contrib)
-VERSION(3.0.27)
+VERSION(3.0.28)
LICENSE(BSD-3-Clause)