From 8f7d422ddcdeb97cf0743db04cfc6ee2b68b5bf3 Mon Sep 17 00:00:00 2001 From: Jonathan Slenders Date: Wed, 15 May 2024 10:34:24 +0000 Subject: [PATCH 1/2] Code style fixes for compatibility with latest Ruff. --- examples/dialogs/button_dialog.py | 1 + examples/dialogs/checkbox_dialog.py | 3 +- examples/dialogs/input_dialog.py | 1 + examples/dialogs/messagebox.py | 1 + examples/dialogs/password_dialog.py | 1 + examples/dialogs/progress_dialog.py | 1 + examples/dialogs/radio_dialog.py | 1 + examples/dialogs/styled_messagebox.py | 1 + examples/dialogs/yes_no_dialog.py | 1 + examples/full-screen/buttons.py | 1 + examples/full-screen/calculator.py | 1 + examples/full-screen/dummy-app.py | 1 + examples/full-screen/full-screen-demo.py | 6 ++-- examples/full-screen/hello-world.py | 1 + examples/full-screen/no-layout.py | 1 + examples/full-screen/pager.py | 6 ++-- .../scrollable-panes/simple-example.py | 1 + .../scrollable-panes/with-completion-menu.py | 1 + .../full-screen/simple-demos/alignment.py | 1 + .../simple-demos/autocompletion.py | 1 + .../full-screen/simple-demos/colorcolumn.py | 1 + .../simple-demos/cursorcolumn-cursorline.py | 1 + .../simple-demos/float-transparency.py | 1 + examples/full-screen/simple-demos/floats.py | 1 + examples/full-screen/simple-demos/focus.py | 1 + .../simple-demos/horizontal-align.py | 1 + .../simple-demos/horizontal-split.py | 1 + .../full-screen/simple-demos/line-prefixes.py | 1 + examples/full-screen/simple-demos/margins.py | 1 + .../simple-demos/vertical-align.py | 1 + .../simple-demos/vertical-split.py | 1 + examples/full-screen/split-screen.py | 1 + examples/full-screen/text-editor.py | 6 ++-- examples/gevent-get-input.py | 3 +- examples/print-text/ansi-colors.py | 1 + examples/print-text/ansi.py | 1 + examples/print-text/html.py | 1 + examples/print-text/named-colors.py | 1 + examples/print-text/print-formatted-text.py | 1 + examples/print-text/print-frame.py | 1 + .../prompt-toolkit-logo-ansi-art.py | 1 + examples/print-text/pygments-tokens.py | 1 + examples/print-text/true-color-demo.py | 1 + .../progress-bar/a-lot-of-parallel-tasks.py | 1 + .../progress-bar/colored-title-and-label.py | 1 + examples/progress-bar/custom-key-bindings.py | 1 + examples/progress-bar/many-parallel-tasks.py | 1 + examples/progress-bar/nested-progress-bars.py | 1 + examples/progress-bar/scrolling-task-name.py | 1 + examples/progress-bar/simple-progress-bar.py | 1 + examples/progress-bar/styled-1.py | 1 + examples/progress-bar/styled-2.py | 1 + .../progress-bar/styled-apt-get-install.py | 1 + examples/progress-bar/styled-rainbow.py | 1 + examples/progress-bar/styled-tqdm-1.py | 1 + examples/progress-bar/styled-tqdm-2.py | 1 + examples/progress-bar/two-tasks.py | 1 + examples/progress-bar/unknown-length.py | 1 + examples/prompts/accept-default.py | 3 +- .../autocomplete-with-control-space.py | 3 +- .../autocompletion-like-readline.py | 3 +- .../prompts/auto-completion/autocompletion.py | 3 +- ...colored-completions-with-formatted-text.py | 1 + .../auto-completion/colored-completions.py | 1 + .../combine-multiple-completers.py | 3 +- .../auto-completion/fuzzy-custom-completer.py | 1 + .../auto-completion/fuzzy-word-completer.py | 3 +- .../multi-column-autocompletion-with-meta.py | 3 +- .../multi-column-autocompletion.py | 3 +- .../auto-completion/nested-autocompletion.py | 3 +- .../auto-completion/slow-completions.py | 3 +- examples/prompts/auto-suggestion.py | 3 +- examples/prompts/autocorrection.py | 3 +- examples/prompts/bottom-toolbar.py | 17 +++++----- examples/prompts/clock-input.py | 3 +- examples/prompts/colored-prompt.py | 7 ++-- examples/prompts/confirmation-prompt.py | 3 +- examples/prompts/cursor-shapes.py | 1 + examples/prompts/custom-key-binding.py | 3 +- examples/prompts/custom-lexer.py | 3 +- .../custom-vi-operator-and-text-object.py | 3 +- examples/prompts/enforce-tty-input-output.py | 1 + examples/prompts/fancy-zsh-prompt.py | 3 +- .../prompts/finalterm-shell-integration.py | 3 +- examples/prompts/get-input-vi-mode.py | 2 +- examples/prompts/get-input-with-default.py | 5 +-- examples/prompts/get-input.py | 3 +- examples/prompts/get-multiline-input.py | 2 +- ...t-password-with-toggle-display-shortcut.py | 3 +- examples/prompts/get-password.py | 2 +- .../prompts/history/persistent-history.py | 3 +- examples/prompts/history/slow-history.py | 3 +- examples/prompts/html-input.py | 3 +- examples/prompts/input-validation.py | 5 +-- examples/prompts/inputhook.py | 3 +- examples/prompts/mouse-support.py | 2 +- examples/prompts/multiline-prompt.py | 3 +- examples/prompts/no-wrapping.py | 2 +- examples/prompts/operate-and-get-next.py | 1 + examples/prompts/patch-stdout.py | 3 +- examples/prompts/placeholder-text.py | 3 +- examples/prompts/regular-language.py | 3 +- examples/prompts/rprompt.py | 9 ++--- .../prompts/swap-light-and-dark-colors.py | 3 +- examples/prompts/switch-between-vi-emacs.py | 1 + .../prompts/system-clipboard-integration.py | 3 +- examples/prompts/system-prompt.py | 6 ++-- examples/prompts/terminal-title.py | 2 +- .../up-arrow-partial-string-matching.py | 3 +- examples/ssh/asyncssh-server.py | 1 + examples/telnet/chat-app.py | 5 +-- examples/telnet/dialog.py | 1 + examples/telnet/hello-world.py | 1 + examples/telnet/toolbar.py | 1 + pyproject.toml | 1 + src/prompt_toolkit/__init__.py | 1 + .../application/run_in_terminal.py | 1 + src/prompt_toolkit/auto_suggest.py | 3 +- src/prompt_toolkit/buffer.py | 15 ++------- src/prompt_toolkit/clipboard/base.py | 1 + src/prompt_toolkit/completion/base.py | 23 +++---------- src/prompt_toolkit/completion/nested.py | 1 + .../contrib/regular_languages/__init__.py | 1 + .../contrib/regular_languages/compiler.py | 15 +++++---- .../contrib/regular_languages/completion.py | 1 + .../contrib/regular_languages/lexer.py | 1 + .../contrib/regular_languages/regex_parser.py | 9 ++--- .../contrib/regular_languages/validation.py | 1 + src/prompt_toolkit/contrib/ssh/server.py | 1 + src/prompt_toolkit/contrib/telnet/log.py | 1 + src/prompt_toolkit/contrib/telnet/protocol.py | 1 + src/prompt_toolkit/contrib/telnet/server.py | 5 +-- src/prompt_toolkit/document.py | 1 + .../eventloop/async_generator.py | 1 + src/prompt_toolkit/eventloop/inputhook.py | 1 + src/prompt_toolkit/filters/__init__.py | 1 + src/prompt_toolkit/filters/app.py | 1 + src/prompt_toolkit/filters/base.py | 8 ++--- src/prompt_toolkit/filters/cli.py | 1 + src/prompt_toolkit/filters/utils.py | 2 +- src/prompt_toolkit/formatted_text/__init__.py | 1 + src/prompt_toolkit/formatted_text/ansi.py | 6 ++-- src/prompt_toolkit/formatted_text/base.py | 5 ++- src/prompt_toolkit/formatted_text/utils.py | 1 + src/prompt_toolkit/history.py | 5 +-- .../input/ansi_escape_sequences.py | 1 + src/prompt_toolkit/input/base.py | 3 +- src/prompt_toolkit/input/typeahead.py | 1 + src/prompt_toolkit/input/vt100_parser.py | 1 + src/prompt_toolkit/input/win32.py | 4 +-- .../key_binding/bindings/auto_suggest.py | 1 + .../key_binding/bindings/completion.py | 1 + .../key_binding/bindings/named_commands.py | 3 +- .../key_binding/bindings/open_in_editor.py | 1 + .../key_binding/bindings/page_navigation.py | 1 + .../key_binding/bindings/scroll.py | 1 + .../key_binding/bindings/search.py | 1 + src/prompt_toolkit/key_binding/defaults.py | 1 + src/prompt_toolkit/key_binding/digraphs.py | 1 + .../key_binding/key_bindings.py | 13 ++++---- .../key_binding/key_processor.py | 7 ++-- src/prompt_toolkit/layout/__init__.py | 1 + src/prompt_toolkit/layout/containers.py | 33 ++++++++----------- src/prompt_toolkit/layout/controls.py | 1 + src/prompt_toolkit/layout/dimension.py | 11 ++++--- src/prompt_toolkit/layout/dummy.py | 1 + src/prompt_toolkit/layout/layout.py | 1 + src/prompt_toolkit/layout/margins.py | 3 +- src/prompt_toolkit/layout/menus.py | 5 +-- src/prompt_toolkit/layout/mouse_handlers.py | 6 ++-- src/prompt_toolkit/layout/processors.py | 13 +++----- src/prompt_toolkit/layout/screen.py | 8 +---- src/prompt_toolkit/layout/utils.py | 6 ++-- src/prompt_toolkit/lexers/__init__.py | 1 + src/prompt_toolkit/lexers/base.py | 1 + src/prompt_toolkit/lexers/pygments.py | 1 + src/prompt_toolkit/log.py | 1 + src/prompt_toolkit/mouse_events.py | 8 ++--- src/prompt_toolkit/output/base.py | 1 + src/prompt_toolkit/output/vt100.py | 3 +- src/prompt_toolkit/output/win32.py | 12 +++---- src/prompt_toolkit/patch_stdout.py | 1 + src/prompt_toolkit/renderer.py | 1 + src/prompt_toolkit/search.py | 8 ++--- src/prompt_toolkit/selection.py | 7 ++-- .../shortcuts/progress_bar/base.py | 1 + .../shortcuts/progress_bar/formatters.py | 13 ++++---- src/prompt_toolkit/shortcuts/prompt.py | 1 + src/prompt_toolkit/styles/__init__.py | 1 + src/prompt_toolkit/styles/base.py | 1 + src/prompt_toolkit/styles/defaults.py | 1 + src/prompt_toolkit/styles/named_colors.py | 1 + src/prompt_toolkit/styles/pygments.py | 1 + src/prompt_toolkit/styles/style.py | 3 +- .../styles/style_transformation.py | 1 + src/prompt_toolkit/token.py | 3 +- src/prompt_toolkit/validation.py | 7 ++-- src/prompt_toolkit/widgets/__init__.py | 1 + src/prompt_toolkit/widgets/base.py | 1 + src/prompt_toolkit/widgets/dialogs.py | 1 + src/prompt_toolkit/widgets/toolbars.py | 6 +--- tests/test_cli.py | 1 + tests/test_print_formatted_text.py | 1 + tests/test_regular_languages.py | 8 ++--- tools/debug_input_cross_platform.py | 1 + tools/debug_vt100_input.py | 1 + 206 files changed, 346 insertions(+), 250 deletions(-) diff --git a/examples/dialogs/button_dialog.py b/examples/dialogs/button_dialog.py index 7a99b9ad0b..24e1a479ce 100755 --- a/examples/dialogs/button_dialog.py +++ b/examples/dialogs/button_dialog.py @@ -2,6 +2,7 @@ """ Example of button dialog window. """ + from prompt_toolkit.shortcuts import button_dialog diff --git a/examples/dialogs/checkbox_dialog.py b/examples/dialogs/checkbox_dialog.py index 90be2636ab..70df166741 100755 --- a/examples/dialogs/checkbox_dialog.py +++ b/examples/dialogs/checkbox_dialog.py @@ -2,6 +2,7 @@ """ Example of a checkbox-list-based dialog. """ + from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import checkboxlist_dialog, message_dialog from prompt_toolkit.styles import Style @@ -30,7 +31,7 @@ if results: message_dialog( title="Room service", - text="You selected: %s\nGreat choice sir !" % ",".join(results), + text="You selected: {}\nGreat choice sir !".format(",".join(results)), ).run() else: message_dialog("*starves*").run() diff --git a/examples/dialogs/input_dialog.py b/examples/dialogs/input_dialog.py index 6235265817..057bc37f37 100755 --- a/examples/dialogs/input_dialog.py +++ b/examples/dialogs/input_dialog.py @@ -2,6 +2,7 @@ """ Example of an input box dialog. """ + from prompt_toolkit.shortcuts import input_dialog diff --git a/examples/dialogs/messagebox.py b/examples/dialogs/messagebox.py index 4642b84514..7b11580d02 100755 --- a/examples/dialogs/messagebox.py +++ b/examples/dialogs/messagebox.py @@ -2,6 +2,7 @@ """ Example of a message box window. """ + from prompt_toolkit.shortcuts import message_dialog diff --git a/examples/dialogs/password_dialog.py b/examples/dialogs/password_dialog.py index 39d7b9c1bc..d3752ba10d 100755 --- a/examples/dialogs/password_dialog.py +++ b/examples/dialogs/password_dialog.py @@ -2,6 +2,7 @@ """ Example of an password input dialog. """ + from prompt_toolkit.shortcuts import input_dialog diff --git a/examples/dialogs/progress_dialog.py b/examples/dialogs/progress_dialog.py index 1fd3ffbadb..7a29f1bb90 100755 --- a/examples/dialogs/progress_dialog.py +++ b/examples/dialogs/progress_dialog.py @@ -2,6 +2,7 @@ """ Example of a progress bar dialog. """ + import os import time diff --git a/examples/dialogs/radio_dialog.py b/examples/dialogs/radio_dialog.py index 94d80e266b..aed9d6663e 100755 --- a/examples/dialogs/radio_dialog.py +++ b/examples/dialogs/radio_dialog.py @@ -2,6 +2,7 @@ """ Example of a radio list box dialog. """ + from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import radiolist_dialog diff --git a/examples/dialogs/styled_messagebox.py b/examples/dialogs/styled_messagebox.py index 3f6fc53a04..5ca197f5c8 100755 --- a/examples/dialogs/styled_messagebox.py +++ b/examples/dialogs/styled_messagebox.py @@ -7,6 +7,7 @@ This also demonstrates that the `title` argument can be any kind of formatted text. """ + from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import message_dialog from prompt_toolkit.styles import Style diff --git a/examples/dialogs/yes_no_dialog.py b/examples/dialogs/yes_no_dialog.py index 4b08dd6756..6463a380c3 100755 --- a/examples/dialogs/yes_no_dialog.py +++ b/examples/dialogs/yes_no_dialog.py @@ -2,6 +2,7 @@ """ Example of confirmation (yes/no) dialog window. """ + from prompt_toolkit.shortcuts import yes_no_dialog diff --git a/examples/full-screen/buttons.py b/examples/full-screen/buttons.py index 540194de75..f741b26279 100755 --- a/examples/full-screen/buttons.py +++ b/examples/full-screen/buttons.py @@ -2,6 +2,7 @@ """ A simple example of a few buttons and click handlers. """ + from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/calculator.py b/examples/full-screen/calculator.py index 1cb513fc6a..1f2b32979e 100755 --- a/examples/full-screen/calculator.py +++ b/examples/full-screen/calculator.py @@ -3,6 +3,7 @@ A simple example of a calculator program. This could be used as inspiration for a REPL. """ + from prompt_toolkit.application import Application from prompt_toolkit.document import Document from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/dummy-app.py b/examples/full-screen/dummy-app.py index 7ea7506262..b9e246b619 100755 --- a/examples/full-screen/dummy-app.py +++ b/examples/full-screen/dummy-app.py @@ -2,6 +2,7 @@ """ This is the most simple example possible. """ + from prompt_toolkit import Application app = Application(full_screen=False) diff --git a/examples/full-screen/full-screen-demo.py b/examples/full-screen/full-screen-demo.py index de7379a016..af3ef5fb64 100755 --- a/examples/full-screen/full-screen-demo.py +++ b/examples/full-screen/full-screen-demo.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -""" -""" +""" """ + from pygments.lexers.html import HtmlLexer from prompt_toolkit.application import Application @@ -218,7 +218,7 @@ def do_exit(): def run(): result = application.run() - print("You said: %r" % result) + print(f"You said: {result!r}") if __name__ == "__main__": diff --git a/examples/full-screen/hello-world.py b/examples/full-screen/hello-world.py index b818018955..86102d60ee 100755 --- a/examples/full-screen/hello-world.py +++ b/examples/full-screen/hello-world.py @@ -2,6 +2,7 @@ """ A simple example of a a text area displaying "Hello World!". """ + from prompt_toolkit.application import Application from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout import Layout diff --git a/examples/full-screen/no-layout.py b/examples/full-screen/no-layout.py index be5c6f8944..a9961c03d3 100644 --- a/examples/full-screen/no-layout.py +++ b/examples/full-screen/no-layout.py @@ -2,6 +2,7 @@ """ An empty full screen application without layout. """ + from prompt_toolkit import Application Application(full_screen=True).run() diff --git a/examples/full-screen/pager.py b/examples/full-screen/pager.py index 799c834377..61336a551e 100755 --- a/examples/full-screen/pager.py +++ b/examples/full-screen/pager.py @@ -2,6 +2,7 @@ """ A simple application that shows a Pager application. """ + from pygments.lexers.python import PythonLexer from prompt_toolkit.application import Application @@ -28,10 +29,7 @@ def get_statusbar_text(): ("class:status", _pager_py_path + " - "), ( "class:status.position", - "{}:{}".format( - text_area.document.cursor_position_row + 1, - text_area.document.cursor_position_col + 1, - ), + f"{text_area.document.cursor_position_row + 1}:{text_area.document.cursor_position_col + 1}", ), ("class:status", " - Press "), ("class:status.key", "Ctrl-C"), diff --git a/examples/full-screen/scrollable-panes/simple-example.py b/examples/full-screen/scrollable-panes/simple-example.py index a94274fd88..cdf26744bf 100644 --- a/examples/full-screen/scrollable-panes/simple-example.py +++ b/examples/full-screen/scrollable-panes/simple-example.py @@ -2,6 +2,7 @@ """ A simple example of a scrollable pane. """ + from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/scrollable-panes/with-completion-menu.py b/examples/full-screen/scrollable-panes/with-completion-menu.py index fba8d1758a..e08609d9f9 100644 --- a/examples/full-screen/scrollable-panes/with-completion-menu.py +++ b/examples/full-screen/scrollable-panes/with-completion-menu.py @@ -2,6 +2,7 @@ """ A simple example of a scrollable pane. """ + from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app from prompt_toolkit.completion import WordCompleter diff --git a/examples/full-screen/simple-demos/alignment.py b/examples/full-screen/simple-demos/alignment.py index b20b43d82a..10a8044c50 100755 --- a/examples/full-screen/simple-demos/alignment.py +++ b/examples/full-screen/simple-demos/alignment.py @@ -2,6 +2,7 @@ """ Demo of the different Window alignment options. """ + from prompt_toolkit.application import Application from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, Window, WindowAlign diff --git a/examples/full-screen/simple-demos/autocompletion.py b/examples/full-screen/simple-demos/autocompletion.py index bcbb594462..f041637651 100755 --- a/examples/full-screen/simple-demos/autocompletion.py +++ b/examples/full-screen/simple-demos/autocompletion.py @@ -6,6 +6,7 @@ Important is to make sure that there is a `CompletionsMenu` in the layout, otherwise the completions won't be visible. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.completion import WordCompleter diff --git a/examples/full-screen/simple-demos/colorcolumn.py b/examples/full-screen/simple-demos/colorcolumn.py index 054aa4439a..184b997390 100755 --- a/examples/full-screen/simple-demos/colorcolumn.py +++ b/examples/full-screen/simple-demos/colorcolumn.py @@ -2,6 +2,7 @@ """ Colorcolumn example. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/simple-demos/cursorcolumn-cursorline.py b/examples/full-screen/simple-demos/cursorcolumn-cursorline.py index 505b3eee49..a6eb5e6618 100755 --- a/examples/full-screen/simple-demos/cursorcolumn-cursorline.py +++ b/examples/full-screen/simple-demos/cursorcolumn-cursorline.py @@ -2,6 +2,7 @@ """ Cursorcolumn / cursorline example. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/simple-demos/float-transparency.py b/examples/full-screen/simple-demos/float-transparency.py index 4dc38fc4b6..a7a88c2d3e 100755 --- a/examples/full-screen/simple-demos/float-transparency.py +++ b/examples/full-screen/simple-demos/float-transparency.py @@ -2,6 +2,7 @@ """ Example of the 'transparency' attribute of `Window' when used in a Float. """ + from prompt_toolkit.application import Application from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/simple-demos/floats.py b/examples/full-screen/simple-demos/floats.py index 0d45be9e5e..4d79c2b806 100755 --- a/examples/full-screen/simple-demos/floats.py +++ b/examples/full-screen/simple-demos/floats.py @@ -2,6 +2,7 @@ """ Horizontal split example. """ + from prompt_toolkit.application import Application from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import Float, FloatContainer, Window diff --git a/examples/full-screen/simple-demos/focus.py b/examples/full-screen/simple-demos/focus.py index 9fe9b8f5ab..fbf965edd3 100755 --- a/examples/full-screen/simple-demos/focus.py +++ b/examples/full-screen/simple-demos/focus.py @@ -2,6 +2,7 @@ """ Demonstration of how to programmatically focus a certain widget. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.document import Document diff --git a/examples/full-screen/simple-demos/horizontal-align.py b/examples/full-screen/simple-demos/horizontal-align.py index bb0de121b8..038823a5c7 100755 --- a/examples/full-screen/simple-demos/horizontal-align.py +++ b/examples/full-screen/simple-demos/horizontal-align.py @@ -2,6 +2,7 @@ """ Horizontal align demo with HSplit. """ + from prompt_toolkit.application import Application from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/simple-demos/horizontal-split.py b/examples/full-screen/simple-demos/horizontal-split.py index 0427e67afc..660cd579de 100755 --- a/examples/full-screen/simple-demos/horizontal-split.py +++ b/examples/full-screen/simple-demos/horizontal-split.py @@ -2,6 +2,7 @@ """ Horizontal split example. """ + from prompt_toolkit.application import Application from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import HSplit, Window diff --git a/examples/full-screen/simple-demos/line-prefixes.py b/examples/full-screen/simple-demos/line-prefixes.py index b52cb48312..687d436733 100755 --- a/examples/full-screen/simple-demos/line-prefixes.py +++ b/examples/full-screen/simple-demos/line-prefixes.py @@ -6,6 +6,7 @@ Important is to make sure that there is a `CompletionsMenu` in the layout, otherwise the completions won't be visible. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition diff --git a/examples/full-screen/simple-demos/margins.py b/examples/full-screen/simple-demos/margins.py index 467492d6f7..b60ce0cacb 100755 --- a/examples/full-screen/simple-demos/margins.py +++ b/examples/full-screen/simple-demos/margins.py @@ -5,6 +5,7 @@ This is mainly used for displaying line numbers and scroll bars, but it could be used to display any other kind of information as well. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/simple-demos/vertical-align.py b/examples/full-screen/simple-demos/vertical-align.py index 1475d71228..13b85048e5 100755 --- a/examples/full-screen/simple-demos/vertical-align.py +++ b/examples/full-screen/simple-demos/vertical-align.py @@ -2,6 +2,7 @@ """ Vertical align demo with VSplit. """ + from prompt_toolkit.application import Application from prompt_toolkit.formatted_text import HTML from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/simple-demos/vertical-split.py b/examples/full-screen/simple-demos/vertical-split.py index b48d1063eb..2f4b66f399 100755 --- a/examples/full-screen/simple-demos/vertical-split.py +++ b/examples/full-screen/simple-demos/vertical-split.py @@ -2,6 +2,7 @@ """ Vertical split example. """ + from prompt_toolkit.application import Application from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.layout.containers import VSplit, Window diff --git a/examples/full-screen/split-screen.py b/examples/full-screen/split-screen.py index af5403ec60..17e69c9e64 100755 --- a/examples/full-screen/split-screen.py +++ b/examples/full-screen/split-screen.py @@ -5,6 +5,7 @@ This will show a window on the left for user input. When the user types, the reversed input is shown on the right. Pressing Ctrl-Q will quit the application. """ + from prompt_toolkit.application import Application from prompt_toolkit.buffer import Buffer from prompt_toolkit.key_binding import KeyBindings diff --git a/examples/full-screen/text-editor.py b/examples/full-screen/text-editor.py index 9c0a414201..7fb6b0b39b 100755 --- a/examples/full-screen/text-editor.py +++ b/examples/full-screen/text-editor.py @@ -2,6 +2,7 @@ """ A simple example of a Notepad-like text editor. """ + import datetime from asyncio import Future, ensure_future @@ -53,10 +54,7 @@ def get_statusbar_text(): def get_statusbar_right_text(): - return " {}:{} ".format( - text_field.document.cursor_position_row + 1, - text_field.document.cursor_position_col + 1, - ) + return f" {text_field.document.cursor_position_row + 1}:{text_field.document.cursor_position_col + 1} " search_toolbar = SearchToolbar() diff --git a/examples/gevent-get-input.py b/examples/gevent-get-input.py index ecb89b43ea..0a0f016ffc 100755 --- a/examples/gevent-get-input.py +++ b/examples/gevent-get-input.py @@ -3,6 +3,7 @@ For testing: test to make sure that everything still works when gevent monkey patches are applied. """ + from gevent.monkey import patch_all from prompt_toolkit.eventloop.defaults import create_event_loop @@ -21,4 +22,4 @@ def dummy_inputhook(*a): # Ask for input. session = PromptSession("Give me some input: ", loop=eventloop) answer = session.prompt() - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/print-text/ansi-colors.py b/examples/print-text/ansi-colors.py index 7bd3831d85..9e223a528e 100755 --- a/examples/print-text/ansi-colors.py +++ b/examples/print-text/ansi-colors.py @@ -2,6 +2,7 @@ """ Demonstration of all the ANSI colors. """ + from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import HTML, FormattedText diff --git a/examples/print-text/ansi.py b/examples/print-text/ansi.py index 618775c00e..e7a20e4c2e 100755 --- a/examples/print-text/ansi.py +++ b/examples/print-text/ansi.py @@ -5,6 +5,7 @@ The advantage here is that this is cross platform. The escape sequences will be parsed and turned into appropriate Win32 API calls on Windows. """ + from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import ANSI, HTML diff --git a/examples/print-text/html.py b/examples/print-text/html.py index 5276fe3b77..4edb74d6cf 100755 --- a/examples/print-text/html.py +++ b/examples/print-text/html.py @@ -2,6 +2,7 @@ """ Demonstration of how to print using the HTML class. """ + from prompt_toolkit import HTML, print_formatted_text print = print_formatted_text diff --git a/examples/print-text/named-colors.py b/examples/print-text/named-colors.py index ea3f0ba0d6..632b3e4854 100755 --- a/examples/print-text/named-colors.py +++ b/examples/print-text/named-colors.py @@ -2,6 +2,7 @@ """ Demonstration of all the ANSI colors. """ + from prompt_toolkit import HTML, print_formatted_text from prompt_toolkit.formatted_text import FormattedText from prompt_toolkit.output import ColorDepth diff --git a/examples/print-text/print-formatted-text.py b/examples/print-text/print-formatted-text.py index 4b09ae2afd..e2efca9950 100755 --- a/examples/print-text/print-formatted-text.py +++ b/examples/print-text/print-formatted-text.py @@ -2,6 +2,7 @@ """ Example of printing colored text to the output. """ + from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import ANSI, HTML, FormattedText from prompt_toolkit.styles import Style diff --git a/examples/print-text/print-frame.py b/examples/print-text/print-frame.py index fb703c5eec..8dec82bfa5 100755 --- a/examples/print-text/print-frame.py +++ b/examples/print-text/print-frame.py @@ -3,6 +3,7 @@ Example usage of 'print_container', a tool to print any layout in a non-interactive way. """ + from prompt_toolkit.shortcuts import print_container from prompt_toolkit.widgets import Frame, TextArea diff --git a/examples/print-text/prompt-toolkit-logo-ansi-art.py b/examples/print-text/prompt-toolkit-logo-ansi-art.py index 617a506244..e34fb03036 100755 --- a/examples/print-text/prompt-toolkit-logo-ansi-art.py +++ b/examples/print-text/prompt-toolkit-logo-ansi-art.py @@ -4,6 +4,7 @@ The ANSI output was generated using "pngtoansi": https://github.com/crgimenes/pngtoansi (ESC still had to be replaced with \x1b """ + from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import ANSI diff --git a/examples/print-text/pygments-tokens.py b/examples/print-text/pygments-tokens.py index 3470e8ee00..a79788a510 100755 --- a/examples/print-text/pygments-tokens.py +++ b/examples/print-text/pygments-tokens.py @@ -3,6 +3,7 @@ Printing a list of Pygments (Token, text) tuples, or an output of a Pygments lexer. """ + import pygments from pygments.lexers.python import PythonLexer from pygments.token import Token diff --git a/examples/print-text/true-color-demo.py b/examples/print-text/true-color-demo.py index a241006065..4debd27ce9 100755 --- a/examples/print-text/true-color-demo.py +++ b/examples/print-text/true-color-demo.py @@ -2,6 +2,7 @@ """ Demonstration of all the ANSI colors. """ + from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import HTML, FormattedText from prompt_toolkit.output import ColorDepth diff --git a/examples/progress-bar/a-lot-of-parallel-tasks.py b/examples/progress-bar/a-lot-of-parallel-tasks.py index 31110ac096..a20982789c 100755 --- a/examples/progress-bar/a-lot-of-parallel-tasks.py +++ b/examples/progress-bar/a-lot-of-parallel-tasks.py @@ -2,6 +2,7 @@ """ More complex demonstration of what's possible with the progress bar. """ + import random import threading import time diff --git a/examples/progress-bar/colored-title-and-label.py b/examples/progress-bar/colored-title-and-label.py index 0b5e73a225..bdea5b9302 100755 --- a/examples/progress-bar/colored-title-and-label.py +++ b/examples/progress-bar/colored-title-and-label.py @@ -3,6 +3,7 @@ A progress bar that displays a formatted title above the progress bar and has a colored label. """ + import time from prompt_toolkit.formatted_text import HTML diff --git a/examples/progress-bar/custom-key-bindings.py b/examples/progress-bar/custom-key-bindings.py index f7008119db..f276a1eb1a 100755 --- a/examples/progress-bar/custom-key-bindings.py +++ b/examples/progress-bar/custom-key-bindings.py @@ -3,6 +3,7 @@ A very simple progress bar which keep track of the progress as we consume an iterator. """ + import os import signal import time diff --git a/examples/progress-bar/many-parallel-tasks.py b/examples/progress-bar/many-parallel-tasks.py index dc34ef2eb2..f3af4fece2 100755 --- a/examples/progress-bar/many-parallel-tasks.py +++ b/examples/progress-bar/many-parallel-tasks.py @@ -2,6 +2,7 @@ """ More complex demonstration of what's possible with the progress bar. """ + import threading import time diff --git a/examples/progress-bar/nested-progress-bars.py b/examples/progress-bar/nested-progress-bars.py index 1a1e70615a..cfbf5f2125 100755 --- a/examples/progress-bar/nested-progress-bars.py +++ b/examples/progress-bar/nested-progress-bars.py @@ -2,6 +2,7 @@ """ Example of nested progress bars. """ + import time from prompt_toolkit import HTML diff --git a/examples/progress-bar/scrolling-task-name.py b/examples/progress-bar/scrolling-task-name.py index bce155f0c5..5531ace4d5 100755 --- a/examples/progress-bar/scrolling-task-name.py +++ b/examples/progress-bar/scrolling-task-name.py @@ -3,6 +3,7 @@ A very simple progress bar where the name of the task scrolls, because it's too long. iterator. """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/progress-bar/simple-progress-bar.py b/examples/progress-bar/simple-progress-bar.py index c8776e5036..672e10301b 100755 --- a/examples/progress-bar/simple-progress-bar.py +++ b/examples/progress-bar/simple-progress-bar.py @@ -3,6 +3,7 @@ A very simple progress bar which keep track of the progress as we consume an iterator. """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/progress-bar/styled-1.py b/examples/progress-bar/styled-1.py index d972e55e91..1f395cf435 100755 --- a/examples/progress-bar/styled-1.py +++ b/examples/progress-bar/styled-1.py @@ -3,6 +3,7 @@ A very simple progress bar which keep track of the progress as we consume an iterator. """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/progress-bar/styled-2.py b/examples/progress-bar/styled-2.py index 15c57d4355..f5979b9524 100755 --- a/examples/progress-bar/styled-2.py +++ b/examples/progress-bar/styled-2.py @@ -3,6 +3,7 @@ A very simple progress bar which keep track of the progress as we consume an iterator. """ + import time from prompt_toolkit.formatted_text import HTML diff --git a/examples/progress-bar/styled-apt-get-install.py b/examples/progress-bar/styled-apt-get-install.py index bafe70ba43..50b69359cc 100755 --- a/examples/progress-bar/styled-apt-get-install.py +++ b/examples/progress-bar/styled-apt-get-install.py @@ -2,6 +2,7 @@ """ Styled just like an apt-get installation. """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/progress-bar/styled-rainbow.py b/examples/progress-bar/styled-rainbow.py index b46e949b2b..e14e2f0292 100755 --- a/examples/progress-bar/styled-rainbow.py +++ b/examples/progress-bar/styled-rainbow.py @@ -2,6 +2,7 @@ """ A simple progress bar, visualized with rainbow colors (for fun). """ + import time from prompt_toolkit.output import ColorDepth diff --git a/examples/progress-bar/styled-tqdm-1.py b/examples/progress-bar/styled-tqdm-1.py index 9484ac051b..a24f887f17 100755 --- a/examples/progress-bar/styled-tqdm-1.py +++ b/examples/progress-bar/styled-tqdm-1.py @@ -4,6 +4,7 @@ See: https://github.com/noamraph/tqdm """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/progress-bar/styled-tqdm-2.py b/examples/progress-bar/styled-tqdm-2.py index 0e66e90073..bcdac677f9 100755 --- a/examples/progress-bar/styled-tqdm-2.py +++ b/examples/progress-bar/styled-tqdm-2.py @@ -4,6 +4,7 @@ See: https://github.com/noamraph/tqdm """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/progress-bar/two-tasks.py b/examples/progress-bar/two-tasks.py index c78604ef4d..36bdf6a14d 100755 --- a/examples/progress-bar/two-tasks.py +++ b/examples/progress-bar/two-tasks.py @@ -2,6 +2,7 @@ """ Two progress bars that run in parallel. """ + import threading import time diff --git a/examples/progress-bar/unknown-length.py b/examples/progress-bar/unknown-length.py index e39ac399dc..5d2d06fdc0 100755 --- a/examples/progress-bar/unknown-length.py +++ b/examples/progress-bar/unknown-length.py @@ -3,6 +3,7 @@ A very simple progress bar which keep track of the progress as we consume an iterator. """ + import time from prompt_toolkit.shortcuts import ProgressBar diff --git a/examples/prompts/accept-default.py b/examples/prompts/accept-default.py index 311ef46c96..0ef45d986d 100644 --- a/examples/prompts/accept-default.py +++ b/examples/prompts/accept-default.py @@ -6,6 +6,7 @@ This should display the prompt with all the formatting like usual, but not allow any editing. """ + from prompt_toolkit import HTML, prompt if __name__ == "__main__": @@ -13,4 +14,4 @@ HTML("Type some input: "), accept_default=True, default="test" ) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/auto-completion/autocomplete-with-control-space.py b/examples/prompts/auto-completion/autocomplete-with-control-space.py index 61160a3626..238f9084be 100755 --- a/examples/prompts/auto-completion/autocomplete-with-control-space.py +++ b/examples/prompts/auto-completion/autocomplete-with-control-space.py @@ -2,6 +2,7 @@ """ Example of using the control-space key binding for auto completion. """ + from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter from prompt_toolkit.key_binding import KeyBindings @@ -68,7 +69,7 @@ def main(): complete_while_typing=False, key_bindings=kb, ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/autocompletion-like-readline.py b/examples/prompts/auto-completion/autocompletion-like-readline.py index 613d3e7408..eac0edd9d2 100755 --- a/examples/prompts/auto-completion/autocompletion-like-readline.py +++ b/examples/prompts/auto-completion/autocompletion-like-readline.py @@ -3,6 +3,7 @@ Autocompletion example that displays the autocompletions like readline does by binding a custom handler to the Tab key. """ + from prompt_toolkit.completion import WordCompleter from prompt_toolkit.shortcuts import CompleteStyle, prompt @@ -51,7 +52,7 @@ def main(): completer=animal_completer, complete_style=CompleteStyle.READLINE_LIKE, ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/autocompletion.py b/examples/prompts/auto-completion/autocompletion.py index fc9dda0589..ea5727f81c 100755 --- a/examples/prompts/auto-completion/autocompletion.py +++ b/examples/prompts/auto-completion/autocompletion.py @@ -7,6 +7,7 @@ and shows all the completions. (In the menu) - Any following tab press cycles through all the possible completions. """ + from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter @@ -53,7 +54,7 @@ def main(): text = prompt( "Give some animals: ", completer=animal_completer, complete_while_typing=False ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/colored-completions-with-formatted-text.py b/examples/prompts/auto-completion/colored-completions-with-formatted-text.py index 8a89c7a3b7..eeff259df3 100755 --- a/examples/prompts/auto-completion/colored-completions-with-formatted-text.py +++ b/examples/prompts/auto-completion/colored-completions-with-formatted-text.py @@ -4,6 +4,7 @@ completions independently by passing formatted text objects to the "display" and "display_meta" arguments of "Completion". """ + from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import CompleteStyle, prompt diff --git a/examples/prompts/auto-completion/colored-completions.py b/examples/prompts/auto-completion/colored-completions.py index 9c5cba365b..1295e7d44d 100755 --- a/examples/prompts/auto-completion/colored-completions.py +++ b/examples/prompts/auto-completion/colored-completions.py @@ -3,6 +3,7 @@ Demonstration of a custom completer class and the possibility of styling completions independently. """ + from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.output.color_depth import ColorDepth from prompt_toolkit.shortcuts import CompleteStyle, prompt diff --git a/examples/prompts/auto-completion/combine-multiple-completers.py b/examples/prompts/auto-completion/combine-multiple-completers.py index 511988b8ee..7c21078e62 100755 --- a/examples/prompts/auto-completion/combine-multiple-completers.py +++ b/examples/prompts/auto-completion/combine-multiple-completers.py @@ -2,6 +2,7 @@ """ Example of multiple individual completers that are combined into one. """ + from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter, merge_completers @@ -69,7 +70,7 @@ def main(): text = prompt( "Give some animals: ", completer=completer, complete_while_typing=False ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/fuzzy-custom-completer.py b/examples/prompts/auto-completion/fuzzy-custom-completer.py index fd9a7d79b4..ca763c7d18 100755 --- a/examples/prompts/auto-completion/fuzzy-custom-completer.py +++ b/examples/prompts/auto-completion/fuzzy-custom-completer.py @@ -3,6 +3,7 @@ Demonstration of a custom completer wrapped in a `FuzzyCompleter` for fuzzy matching. """ + from prompt_toolkit.completion import Completer, Completion, FuzzyCompleter from prompt_toolkit.shortcuts import CompleteStyle, prompt diff --git a/examples/prompts/auto-completion/fuzzy-word-completer.py b/examples/prompts/auto-completion/fuzzy-word-completer.py index 329c0c1e36..0ea059ebec 100755 --- a/examples/prompts/auto-completion/fuzzy-word-completer.py +++ b/examples/prompts/auto-completion/fuzzy-word-completer.py @@ -7,6 +7,7 @@ and shows all the completions. (In the menu) - Any following tab press cycles through all the possible completions. """ + from prompt_toolkit.completion import FuzzyWordCompleter from prompt_toolkit.shortcuts import prompt @@ -52,7 +53,7 @@ def main(): text = prompt( "Give some animals: ", completer=animal_completer, complete_while_typing=True ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/multi-column-autocompletion-with-meta.py b/examples/prompts/auto-completion/multi-column-autocompletion-with-meta.py index 5ba3ab5088..c748837c54 100755 --- a/examples/prompts/auto-completion/multi-column-autocompletion-with-meta.py +++ b/examples/prompts/auto-completion/multi-column-autocompletion-with-meta.py @@ -2,6 +2,7 @@ """ Autocompletion example that shows meta-information alongside the completions. """ + from prompt_toolkit.completion import WordCompleter from prompt_toolkit.shortcuts import CompleteStyle, prompt @@ -43,7 +44,7 @@ def main(): completer=animal_completer, complete_style=CompleteStyle.MULTI_COLUMN, ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/multi-column-autocompletion.py b/examples/prompts/auto-completion/multi-column-autocompletion.py index 7fcfc52cbc..9b246223c9 100755 --- a/examples/prompts/auto-completion/multi-column-autocompletion.py +++ b/examples/prompts/auto-completion/multi-column-autocompletion.py @@ -2,6 +2,7 @@ """ Similar to the autocompletion example. But display all the completions in multiple columns. """ + from prompt_toolkit.completion import WordCompleter from prompt_toolkit.shortcuts import CompleteStyle, prompt @@ -50,7 +51,7 @@ def main(): completer=animal_completer, complete_style=CompleteStyle.MULTI_COLUMN, ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/nested-autocompletion.py b/examples/prompts/auto-completion/nested-autocompletion.py index cd85b8cb49..e56e82ed80 100755 --- a/examples/prompts/auto-completion/nested-autocompletion.py +++ b/examples/prompts/auto-completion/nested-autocompletion.py @@ -2,6 +2,7 @@ """ Example of nested autocompletion. """ + from prompt_toolkit import prompt from prompt_toolkit.completion import NestedCompleter @@ -15,7 +16,7 @@ def main(): text = prompt("Type a command: ", completer=completer) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-completion/slow-completions.py b/examples/prompts/auto-completion/slow-completions.py index cce9d599cf..0c9cc11bb3 100755 --- a/examples/prompts/auto-completion/slow-completions.py +++ b/examples/prompts/auto-completion/slow-completions.py @@ -12,6 +12,7 @@ - We also set a `loading` boolean in the completer function to keep track of when the completer is running, and display this in the toolbar. """ + import time from prompt_toolkit.completion import Completer, Completion @@ -96,7 +97,7 @@ def bottom_toolbar(): bottom_toolbar=bottom_toolbar, complete_style=CompleteStyle.MULTI_COLUMN, ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/auto-suggestion.py b/examples/prompts/auto-suggestion.py index 6660777804..56a9dc69b3 100755 --- a/examples/prompts/auto-suggestion.py +++ b/examples/prompts/auto-suggestion.py @@ -7,6 +7,7 @@ remaining part as a suggestion. Pressing the right arrow will insert this suggestion. """ + from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.history import InMemoryHistory @@ -41,7 +42,7 @@ def main(): else: break - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/autocorrection.py b/examples/prompts/autocorrection.py index 63781326af..2699554d01 100755 --- a/examples/prompts/autocorrection.py +++ b/examples/prompts/autocorrection.py @@ -4,6 +4,7 @@ The word "impotr" will be corrected when the user types a space afterwards. """ + from prompt_toolkit import prompt from prompt_toolkit.key_binding import KeyBindings @@ -37,7 +38,7 @@ def _(event): # Read input. text = prompt("Say something: ", key_bindings=bindings) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/bottom-toolbar.py b/examples/prompts/bottom-toolbar.py index 4980e5bd34..937a961020 100755 --- a/examples/prompts/bottom-toolbar.py +++ b/examples/prompts/bottom-toolbar.py @@ -10,6 +10,7 @@ inside will get 'bottom-toolbar.text'. These can be used to change the default style. """ + import time from prompt_toolkit import prompt @@ -20,14 +21,14 @@ def main(): # Example 1: fixed text. text = prompt("Say something: ", bottom_toolbar="This is a toolbar") - print("You said: %s" % text) + print(f"You said: {text}") # Example 2: fixed text from a callable: def get_toolbar(): - return "Bottom toolbar: time=%r" % time.time() + return f"Bottom toolbar: time={time.time()!r}" text = prompt("Say something: ", bottom_toolbar=get_toolbar, refresh_interval=0.5) - print("You said: %s" % text) + print(f"You said: {text}") # Example 3: Using HTML: text = prompt( @@ -36,7 +37,7 @@ def get_toolbar(): '(html) This is a ' ), ) - print("You said: %s" % text) + print(f"You said: {text}") # Example 4: Using ANSI: text = prompt( @@ -45,7 +46,7 @@ def get_toolbar(): "(ansi): \x1b[1mThis\x1b[0m \x1b[4mis\x1b[0m a \x1b[91mtoolbar" ), ) - print("You said: %s" % text) + print(f"You said: {text}") # Example 5: styling differently. style = Style.from_dict( @@ -56,7 +57,7 @@ def get_toolbar(): ) text = prompt("Say something: ", bottom_toolbar="This is a toolbar", style=style) - print("You said: %s" % text) + print(f"You said: {text}") # Example 6: Using a list of tokens. def get_bottom_toolbar(): @@ -69,11 +70,11 @@ def get_bottom_toolbar(): ] text = prompt("Say something: ", bottom_toolbar=get_bottom_toolbar) - print("You said: %s" % text) + print(f"You said: {text}") # Example 7: multiline fixed text. text = prompt("Say something: ", bottom_toolbar="This is\na multiline toolbar") - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/clock-input.py b/examples/prompts/clock-input.py index e43abd8915..80bfa513ee 100755 --- a/examples/prompts/clock-input.py +++ b/examples/prompts/clock-input.py @@ -2,6 +2,7 @@ """ Example of a 'dynamic' prompt. On that shows the current time in the prompt. """ + import datetime from prompt_toolkit.shortcuts import prompt @@ -18,7 +19,7 @@ def get_prompt(): def main(): result = prompt(get_prompt, refresh_interval=0.5) - print("You said: %s" % result) + print(f"You said: {result}") if __name__ == "__main__": diff --git a/examples/prompts/colored-prompt.py b/examples/prompts/colored-prompt.py index 1e63e296b1..428ff1dd0c 100755 --- a/examples/prompts/colored-prompt.py +++ b/examples/prompts/colored-prompt.py @@ -2,6 +2,7 @@ """ Example of a colored prompt. """ + from prompt_toolkit import prompt from prompt_toolkit.formatted_text import ANSI, HTML from prompt_toolkit.styles import Style @@ -40,7 +41,7 @@ def example_1(): ] answer = prompt(prompt_fragments, style=style) - print("You said: %s" % answer) + print(f"You said: {answer}") def example_2(): @@ -57,7 +58,7 @@ def example_2(): ), style=style, ) - print("You said: %s" % answer) + print(f"You said: {answer}") def example_3(): @@ -72,7 +73,7 @@ def example_3(): "# " ) ) - print("You said: %s" % answer) + print(f"You said: {answer}") if __name__ == "__main__": diff --git a/examples/prompts/confirmation-prompt.py b/examples/prompts/confirmation-prompt.py index bd52b9e96a..18687fe6c4 100755 --- a/examples/prompts/confirmation-prompt.py +++ b/examples/prompts/confirmation-prompt.py @@ -2,8 +2,9 @@ """ Example of a confirmation prompt. """ + from prompt_toolkit.shortcuts import confirm if __name__ == "__main__": answer = confirm("Should we do that?") - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/cursor-shapes.py b/examples/prompts/cursor-shapes.py index e668243a42..62b2d951bc 100755 --- a/examples/prompts/cursor-shapes.py +++ b/examples/prompts/cursor-shapes.py @@ -2,6 +2,7 @@ """ Example of cursor shape configurations. """ + from prompt_toolkit import prompt from prompt_toolkit.cursor_shapes import CursorShape, ModalCursorShapeConfig diff --git a/examples/prompts/custom-key-binding.py b/examples/prompts/custom-key-binding.py index 32d889ede0..b918ab39e6 100755 --- a/examples/prompts/custom-key-binding.py +++ b/examples/prompts/custom-key-binding.py @@ -2,6 +2,7 @@ """ Example of adding a custom key binding to a prompt. """ + import asyncio from prompt_toolkit import prompt @@ -70,7 +71,7 @@ async def _(event): # Read input. print('Press F4 to insert "hello world", type "xy" to insert "z":') text = prompt("> ", key_bindings=bindings) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/custom-lexer.py b/examples/prompts/custom-lexer.py index c4c9fbed2f..75ad2d33c0 100755 --- a/examples/prompts/custom-lexer.py +++ b/examples/prompts/custom-lexer.py @@ -2,6 +2,7 @@ """ An example of a custom lexer that prints the input text in random colors. """ + from prompt_toolkit.lexers import Lexer from prompt_toolkit.shortcuts import prompt from prompt_toolkit.styles.named_colors import NAMED_COLORS @@ -22,7 +23,7 @@ def get_line(lineno): def main(): answer = prompt("Give me some input: ", lexer=RainbowLexer()) - print("You said: %s" % answer) + print(f"You said: {answer}") if __name__ == "__main__": diff --git a/examples/prompts/custom-vi-operator-and-text-object.py b/examples/prompts/custom-vi-operator-and-text-object.py index 7478afc87d..74bac23682 100755 --- a/examples/prompts/custom-vi-operator-and-text-object.py +++ b/examples/prompts/custom-vi-operator-and-text-object.py @@ -3,6 +3,7 @@ Example of adding a custom Vi operator and text object. (Note that this API is not guaranteed to remain stable.) """ + from prompt_toolkit import prompt from prompt_toolkit.enums import EditingMode from prompt_toolkit.key_binding import KeyBindings @@ -63,7 +64,7 @@ def _(event): text = prompt( "> ", default="hello world", key_bindings=bindings, editing_mode=EditingMode.VI ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/enforce-tty-input-output.py b/examples/prompts/enforce-tty-input-output.py index 93b43ee989..08bb76287d 100755 --- a/examples/prompts/enforce-tty-input-output.py +++ b/examples/prompts/enforce-tty-input-output.py @@ -6,6 +6,7 @@ For testing, run as: cat /dev/null | python ./enforce-tty-input-output.py > /dev/null """ + from prompt_toolkit.application import create_app_session_from_tty from prompt_toolkit.shortcuts import prompt diff --git a/examples/prompts/fancy-zsh-prompt.py b/examples/prompts/fancy-zsh-prompt.py index 4761c08ad0..cc31c1f342 100755 --- a/examples/prompts/fancy-zsh-prompt.py +++ b/examples/prompts/fancy-zsh-prompt.py @@ -9,6 +9,7 @@ - https://github.com/xonsh/xonsh/issues/3356 - https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1111 """ + import datetime from prompt_toolkit import prompt @@ -72,7 +73,7 @@ def get_prompt() -> HTML: def main() -> None: while True: answer = prompt(get_prompt, style=style, refresh_interval=1) - print("You said: %s" % answer) + print(f"You said: {answer}") if __name__ == "__main__": diff --git a/examples/prompts/finalterm-shell-integration.py b/examples/prompts/finalterm-shell-integration.py index 30c7a7fb33..254d226d9d 100755 --- a/examples/prompts/finalterm-shell-integration.py +++ b/examples/prompts/finalterm-shell-integration.py @@ -3,6 +3,7 @@ Mark the start and end of the prompt with Final term (iterm2) escape sequences. See: https://iterm2.com/finalterm.html """ + import sys from prompt_toolkit import prompt @@ -39,5 +40,5 @@ def get_prompt_text(): # Output. sys.stdout.write(BEFORE_OUTPUT) - print("You said: %s" % answer) + print(f"You said: {answer}") sys.stdout.write(AFTER_OUTPUT.format(command_status=0)) diff --git a/examples/prompts/get-input-vi-mode.py b/examples/prompts/get-input-vi-mode.py index 566ffd5ed5..4073bcdd2b 100755 --- a/examples/prompts/get-input-vi-mode.py +++ b/examples/prompts/get-input-vi-mode.py @@ -4,4 +4,4 @@ if __name__ == "__main__": print("You have Vi keybindings here. Press [Esc] to go to navigation mode.") answer = prompt("Give me some input: ", multiline=False, vi_mode=True) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/get-input-with-default.py b/examples/prompts/get-input-with-default.py index 67446d57f9..974888f951 100755 --- a/examples/prompts/get-input-with-default.py +++ b/examples/prompts/get-input-with-default.py @@ -3,10 +3,11 @@ Example of a call to `prompt` with a default value. The input is pre-filled, but the user can still edit the default. """ + import getpass from prompt_toolkit import prompt if __name__ == "__main__": - answer = prompt("What is your name: ", default="%s" % getpass.getuser()) - print("You said: %s" % answer) + answer = prompt("What is your name: ", default=f"{getpass.getuser()}") + print(f"You said: {answer}") diff --git a/examples/prompts/get-input.py b/examples/prompts/get-input.py index 5529bbbb5b..6db7e2c49e 100755 --- a/examples/prompts/get-input.py +++ b/examples/prompts/get-input.py @@ -2,8 +2,9 @@ """ The most simple prompt example. """ + from prompt_toolkit import prompt if __name__ == "__main__": answer = prompt("Give me some input: ") - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/get-multiline-input.py b/examples/prompts/get-multiline-input.py index eda35bee42..cda6fa52c0 100755 --- a/examples/prompts/get-multiline-input.py +++ b/examples/prompts/get-multiline-input.py @@ -26,4 +26,4 @@ def prompt_continuation(width, line_number, wrap_count): answer = prompt( "Multiline input: ", multiline=True, prompt_continuation=prompt_continuation ) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/get-password-with-toggle-display-shortcut.py b/examples/prompts/get-password-with-toggle-display-shortcut.py index b89cb41f00..a233e5e77c 100755 --- a/examples/prompts/get-password-with-toggle-display-shortcut.py +++ b/examples/prompts/get-password-with-toggle-display-shortcut.py @@ -3,6 +3,7 @@ get_password function that displays asterisks instead of the actual characters. With the addition of a ControlT shortcut to hide/show the input. """ + from prompt_toolkit import prompt from prompt_toolkit.filters import Condition from prompt_toolkit.key_binding import KeyBindings @@ -21,7 +22,7 @@ def _(event): password = prompt( "Password: ", is_password=Condition(lambda: hidden[0]), key_bindings=bindings ) - print("You said: %s" % password) + print(f"You said: {password}") if __name__ == "__main__": diff --git a/examples/prompts/get-password.py b/examples/prompts/get-password.py index 1c9517c60f..a9c0c27f78 100755 --- a/examples/prompts/get-password.py +++ b/examples/prompts/get-password.py @@ -3,4 +3,4 @@ if __name__ == "__main__": password = prompt("Password: ", is_password=True) - print("You said: %s" % password) + print(f"You said: {password}") diff --git a/examples/prompts/history/persistent-history.py b/examples/prompts/history/persistent-history.py index 2bdb7587f4..6299bdce10 100755 --- a/examples/prompts/history/persistent-history.py +++ b/examples/prompts/history/persistent-history.py @@ -4,6 +4,7 @@ strings in a file. When you run this script for a second time, pressing arrow-up will go back in history. """ + from prompt_toolkit import PromptSession from prompt_toolkit.history import FileHistory @@ -18,7 +19,7 @@ def main(): while True: text = session.prompt("Say something: ") - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/history/slow-history.py b/examples/prompts/history/slow-history.py index 5b6a7a2f54..10e45921e2 100755 --- a/examples/prompts/history/slow-history.py +++ b/examples/prompts/history/slow-history.py @@ -5,6 +5,7 @@ By wrapping it in `ThreadedHistory`, the history will load in the background without blocking any user interaction. """ + import time from prompt_toolkit import PromptSession @@ -41,7 +42,7 @@ def main(): while True: text = session.prompt("Say something: ") - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/html-input.py b/examples/prompts/html-input.py index 4c51737773..e8ecc007eb 100755 --- a/examples/prompts/html-input.py +++ b/examples/prompts/html-input.py @@ -3,6 +3,7 @@ Simple example of a syntax-highlighted HTML input line. (This requires Pygments to be installed.) """ + from pygments.lexers.html import HtmlLexer from prompt_toolkit import prompt @@ -11,7 +12,7 @@ def main(): text = prompt("Enter HTML: ", lexer=PygmentsLexer(HtmlLexer)) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/input-validation.py b/examples/prompts/input-validation.py index d8bd3eef94..2151671815 100755 --- a/examples/prompts/input-validation.py +++ b/examples/prompts/input-validation.py @@ -2,6 +2,7 @@ """ Simple example of input validation. """ + from prompt_toolkit import prompt from prompt_toolkit.validation import Validator @@ -22,13 +23,13 @@ def main(): text = prompt( "Enter e-mail address: ", validator=validator, validate_while_typing=False ) - print("You said: %s" % text) + print(f"You said: {text}") # While typing text = prompt( "Enter e-mail address: ", validator=validator, validate_while_typing=True ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/inputhook.py b/examples/prompts/inputhook.py index 7cbfe18045..a7762463ad 100755 --- a/examples/prompts/inputhook.py +++ b/examples/prompts/inputhook.py @@ -11,6 +11,7 @@ `InputHookContext.input_is_ready()`. Another way is to check for `InputHookContext.fileno()` to be ready. In this example we do the latter. """ + import gobject import gtk from pygments.lexers.python import PythonLexer @@ -76,7 +77,7 @@ def main(): "Python >>> ", inputhook=inputhook, lexer=PygmentsLexer(PythonLexer) ) result = session.prompt() - print("You said: %s" % result) + print(f"You said: {result}") if __name__ == "__main__": diff --git a/examples/prompts/mouse-support.py b/examples/prompts/mouse-support.py index 1e4ee76005..b1b4bb70ed 100755 --- a/examples/prompts/mouse-support.py +++ b/examples/prompts/mouse-support.py @@ -7,4 +7,4 @@ ) print("You can click with the mouse in order to select text.") answer = prompt("Multiline input: ", multiline=True, mouse_support=True) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/multiline-prompt.py b/examples/prompts/multiline-prompt.py index d6a7698cbc..f2e70ef30e 100755 --- a/examples/prompts/multiline-prompt.py +++ b/examples/prompts/multiline-prompt.py @@ -2,10 +2,11 @@ """ Demonstration of how the input can be indented. """ + from prompt_toolkit import prompt if __name__ == "__main__": answer = prompt( "Give me some input: (ESCAPE followed by ENTER to accept)\n > ", multiline=True ) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/no-wrapping.py b/examples/prompts/no-wrapping.py index 371486ea66..170e7d53c8 100755 --- a/examples/prompts/no-wrapping.py +++ b/examples/prompts/no-wrapping.py @@ -3,4 +3,4 @@ if __name__ == "__main__": answer = prompt("Give me some input: ", wrap_lines=False, multiline=True) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/operate-and-get-next.py b/examples/prompts/operate-and-get-next.py index 6ea4d796a6..0bc70ba25b 100755 --- a/examples/prompts/operate-and-get-next.py +++ b/examples/prompts/operate-and-get-next.py @@ -5,6 +5,7 @@ (Actually, this creates one prompt application, and keeps running the same app over and over again. -- For now, this is the only way to get this working.) """ + from prompt_toolkit.shortcuts import PromptSession diff --git a/examples/prompts/patch-stdout.py b/examples/prompts/patch-stdout.py index 1c83524d8d..3a89f36508 100755 --- a/examples/prompts/patch-stdout.py +++ b/examples/prompts/patch-stdout.py @@ -5,6 +5,7 @@ This makes sure that output from other threads doesn't disturb the rendering of the prompt, but instead is printed nicely above the prompt. """ + import threading import time @@ -31,7 +32,7 @@ def thread(): # should not disturb anything. with patch_stdout(): result = prompt("Say something: ") - print("You said: %s" % result) + print(f"You said: {result}") # Stop thread. running = False diff --git a/examples/prompts/placeholder-text.py b/examples/prompts/placeholder-text.py index 35e1c6c5c9..65d77a1244 100755 --- a/examples/prompts/placeholder-text.py +++ b/examples/prompts/placeholder-text.py @@ -2,6 +2,7 @@ """ Example of a placeholder that's displayed as long as no input is given. """ + from prompt_toolkit import prompt from prompt_toolkit.formatted_text import HTML @@ -10,4 +11,4 @@ "Give me some input: ", placeholder=HTML(''), ) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/regular-language.py b/examples/prompts/regular-language.py index cbe7256da8..12cf2571cc 100755 --- a/examples/prompts/regular-language.py +++ b/examples/prompts/regular-language.py @@ -12,6 +12,7 @@ This example shows how you can define the grammar of a regular language and how to use variables in this grammar with completers and tokens attached. """ + import math from prompt_toolkit import prompt @@ -99,7 +100,7 @@ def create_grammar(): }[vars.get("operator1") or vars.get("operator2")] # Execute and print the result. - print("Result: %s\n" % (operator(var1, var2))) + print(f"Result: {operator(var1, var2)}\n") elif vars.get("operator2"): print("Operator 2") diff --git a/examples/prompts/rprompt.py b/examples/prompts/rprompt.py index f7656b7af6..fd4fe1bf7f 100755 --- a/examples/prompts/rprompt.py +++ b/examples/prompts/rprompt.py @@ -6,6 +6,7 @@ This is similar to RPROMPT is Zsh. """ + from prompt_toolkit import prompt from prompt_toolkit.formatted_text import ANSI, HTML from prompt_toolkit.styles import Style @@ -30,23 +31,23 @@ def get_rprompt_text(): def main(): # Option 1: pass a string to 'rprompt': answer = prompt("> ", rprompt=" ", style=example_style) - print("You said: %s" % answer) + print(f"You said: {answer}") # Option 2: pass HTML: answer = prompt("> ", rprompt=HTML(" <rprompt> "), style=example_style) - print("You said: %s" % answer) + print(f"You said: {answer}") # Option 3: pass ANSI: answer = prompt( "> ", rprompt=ANSI(" \x1b[4m\x1b[0m "), style=example_style ) - print("You said: %s" % answer) + print(f"You said: {answer}") # Option 4: Pass a callable. (This callable can either return plain text, # an HTML object, an ANSI object or a list of (style, text) # tuples. answer = prompt("> ", rprompt=get_rprompt_text, style=example_style) - print("You said: %s" % answer) + print(f"You said: {answer}") if __name__ == "__main__": diff --git a/examples/prompts/swap-light-and-dark-colors.py b/examples/prompts/swap-light-and-dark-colors.py index e602449d45..4237d73212 100755 --- a/examples/prompts/swap-light-and-dark-colors.py +++ b/examples/prompts/swap-light-and-dark-colors.py @@ -7,6 +7,7 @@ turns light green into dark green and the other way around. Foreground and background are independent of each other. """ + from pygments.lexers.html import HtmlLexer from prompt_toolkit import prompt @@ -71,7 +72,7 @@ def bottom_toolbar(): lexer=PygmentsLexer(HtmlLexer), swap_light_and_dark_colors=Condition(lambda: swapped[0]), ) - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/prompts/switch-between-vi-emacs.py b/examples/prompts/switch-between-vi-emacs.py index 249c7efd57..a69b14058d 100755 --- a/examples/prompts/switch-between-vi-emacs.py +++ b/examples/prompts/switch-between-vi-emacs.py @@ -3,6 +3,7 @@ Example that displays how to switch between Emacs and Vi input mode. """ + from prompt_toolkit import prompt from prompt_toolkit.application.current import get_app from prompt_toolkit.enums import EditingMode diff --git a/examples/prompts/system-clipboard-integration.py b/examples/prompts/system-clipboard-integration.py index f6059217fb..0b9136b9bd 100755 --- a/examples/prompts/system-clipboard-integration.py +++ b/examples/prompts/system-clipboard-integration.py @@ -3,6 +3,7 @@ Demonstration of a custom clipboard class. This requires the 'pyperclip' library to be installed. """ + from prompt_toolkit import prompt from prompt_toolkit.clipboard.pyperclip import PyperclipClipboard @@ -14,4 +15,4 @@ print("") answer = prompt("Give me some input: ", clipboard=PyperclipClipboard()) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/system-prompt.py b/examples/prompts/system-prompt.py index 47aa2a5620..e9ff46095b 100755 --- a/examples/prompts/system-prompt.py +++ b/examples/prompts/system-prompt.py @@ -7,14 +7,14 @@ "(1/3) If you press meta-! or esc-! at the following prompt, you can enter system commands." ) answer = prompt("Give me some input: ", enable_system_prompt=True) - print("You said: %s" % answer) + print(f"You said: {answer}") # Enable suspend. print("(2/3) If you press Control-Z, the application will suspend.") answer = prompt("Give me some input: ", enable_suspend=True) - print("You said: %s" % answer) + print(f"You said: {answer}") # Enable open_in_editor print("(3/3) If you press Control-X Control-E, the prompt will open in $EDITOR.") answer = prompt("Give me some input: ", enable_open_in_editor=True) - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/terminal-title.py b/examples/prompts/terminal-title.py index 14f945999c..dc49c2671a 100755 --- a/examples/prompts/terminal-title.py +++ b/examples/prompts/terminal-title.py @@ -7,4 +7,4 @@ answer = prompt("Give me some input: ") set_title("") - print("You said: %s" % answer) + print(f"You said: {answer}") diff --git a/examples/prompts/up-arrow-partial-string-matching.py b/examples/prompts/up-arrow-partial-string-matching.py index 742a12eda2..999b1f95e8 100755 --- a/examples/prompts/up-arrow-partial-string-matching.py +++ b/examples/prompts/up-arrow-partial-string-matching.py @@ -5,6 +5,7 @@ When you type some input, it's possible to use the up arrow to filter the history on the items starting with the given input text. """ + from prompt_toolkit import PromptSession from prompt_toolkit.history import InMemoryHistory @@ -34,7 +35,7 @@ def main(): else: break - print("You said: %s" % text) + print(f"You said: {text}") if __name__ == "__main__": diff --git a/examples/ssh/asyncssh-server.py b/examples/ssh/asyncssh-server.py index 27d0dd22cc..0b09f2bc44 100755 --- a/examples/ssh/asyncssh-server.py +++ b/examples/ssh/asyncssh-server.py @@ -2,6 +2,7 @@ """ Example of running a prompt_toolkit application in an asyncssh server. """ + import asyncio import logging diff --git a/examples/telnet/chat-app.py b/examples/telnet/chat-app.py index 2e3508d44e..8f4cb2c376 100755 --- a/examples/telnet/chat-app.py +++ b/examples/telnet/chat-app.py @@ -4,6 +4,7 @@ Everyone that connects is asked for his name, and then people can chat with each other. """ + import logging import random from asyncio import Future, run @@ -84,9 +85,9 @@ def _send_to_everyone(sender_connection, name, message, color): if c != sender_connection: c.send_above_prompt( [ - ("fg:" + color, "[%s]" % name), + ("fg:" + color, f"[{name}]"), ("", " "), - ("fg:" + color, "%s\n" % message), + ("fg:" + color, f"{message}\n"), ] ) diff --git a/examples/telnet/dialog.py b/examples/telnet/dialog.py index c674a9da17..1044fb0f85 100755 --- a/examples/telnet/dialog.py +++ b/examples/telnet/dialog.py @@ -2,6 +2,7 @@ """ Example of a telnet application that displays a dialog window. """ + import logging from asyncio import Future, run diff --git a/examples/telnet/hello-world.py b/examples/telnet/hello-world.py index c19c60ca9a..f7bbda1927 100755 --- a/examples/telnet/hello-world.py +++ b/examples/telnet/hello-world.py @@ -6,6 +6,7 @@ Also see the `hello-world-asyncio.py` example which uses an asyncio coroutine. That is probably the preferred way if you only need Python 3 support. """ + import logging from asyncio import run diff --git a/examples/telnet/toolbar.py b/examples/telnet/toolbar.py index d6ae88656a..6e31c9f0fd 100755 --- a/examples/telnet/toolbar.py +++ b/examples/telnet/toolbar.py @@ -3,6 +3,7 @@ Example of a telnet application that displays a bottom toolbar and completions in the prompt. """ + import logging from asyncio import run diff --git a/pyproject.toml b/pyproject.toml index aa74bd688c..1bff4baec2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,6 +31,7 @@ lint.ignore = [ "src/prompt_toolkit/filters/__init__.py" = ["F403", "F405"] # Possibly undefined due to star import. "src/prompt_toolkit/filters/cli.py" = ["F403", "F405"] # Possibly undefined due to star import. "src/prompt_toolkit/shortcuts/progress_bar/formatters.py" = ["UP031"] # %-style formatting. +"src/*" = ["UP032"] # f-strings instead of format calls. [tool.ruff.lint.isort] diff --git a/src/prompt_toolkit/__init__.py b/src/prompt_toolkit/__init__.py index 82324cb815..0a27c5436b 100644 --- a/src/prompt_toolkit/__init__.py +++ b/src/prompt_toolkit/__init__.py @@ -13,6 +13,7 @@ Probably, to get started, you might also want to have a look at `prompt_toolkit.shortcuts.prompt`. """ + from __future__ import annotations import re diff --git a/src/prompt_toolkit/application/run_in_terminal.py b/src/prompt_toolkit/application/run_in_terminal.py index 1e4da2d9cb..18a3dadeb9 100644 --- a/src/prompt_toolkit/application/run_in_terminal.py +++ b/src/prompt_toolkit/application/run_in_terminal.py @@ -1,6 +1,7 @@ """ Tools for running functions on the terminal above the current application or prompt. """ + from __future__ import annotations from asyncio import Future, ensure_future diff --git a/src/prompt_toolkit/auto_suggest.py b/src/prompt_toolkit/auto_suggest.py index 98cb4ddd92..73213ba690 100644 --- a/src/prompt_toolkit/auto_suggest.py +++ b/src/prompt_toolkit/auto_suggest.py @@ -11,6 +11,7 @@ then wrap the :class:`.AutoSuggest` instance into a :class:`.ThreadedAutoSuggest`. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod @@ -46,7 +47,7 @@ def __init__(self, text: str) -> None: self.text = text def __repr__(self) -> str: - return "Suggestion(%s)" % self.text + return f"Suggestion({self.text})" class AutoSuggest(metaclass=ABCMeta): diff --git a/src/prompt_toolkit/buffer.py b/src/prompt_toolkit/buffer.py index 100ca78d7b..2c20bc606a 100644 --- a/src/prompt_toolkit/buffer.py +++ b/src/prompt_toolkit/buffer.py @@ -2,6 +2,7 @@ Data structures for the Buffer. It holds the text, cursor position, history, etc... """ + from __future__ import annotations import asyncio @@ -85,12 +86,7 @@ def __init__( self.complete_index = complete_index # Position in the `_completions` array. def __repr__(self) -> str: - return "{}({!r}, <{!r}> completions, index={!r})".format( - self.__class__.__name__, - self.original_document, - len(self.completions), - self.complete_index, - ) + return f"{self.__class__.__name__}({self.original_document!r}, <{len(self.completions)!r}> completions, index={self.complete_index!r})" def go_to_index(self, index: int | None) -> None: """ @@ -149,12 +145,7 @@ def __init__( self.n = n def __repr__(self) -> str: - return "{}(history_position={!r}, n={!r}, previous_inserted_word={!r})".format( - self.__class__.__name__, - self.history_position, - self.n, - self.previous_inserted_word, - ) + return f"{self.__class__.__name__}(history_position={self.history_position!r}, n={self.n!r}, previous_inserted_word={self.previous_inserted_word!r})" BufferEventHandler = Callable[["Buffer"], None] diff --git a/src/prompt_toolkit/clipboard/base.py b/src/prompt_toolkit/clipboard/base.py index b05275ba63..28cfdcd766 100644 --- a/src/prompt_toolkit/clipboard/base.py +++ b/src/prompt_toolkit/clipboard/base.py @@ -1,6 +1,7 @@ """ Clipboard for command line interface. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod diff --git a/src/prompt_toolkit/completion/base.py b/src/prompt_toolkit/completion/base.py index 04a712df7e..3846ef7562 100644 --- a/src/prompt_toolkit/completion/base.py +++ b/src/prompt_toolkit/completion/base.py @@ -1,5 +1,5 @@ -""" -""" +""" """ + from __future__ import annotations from abc import ABCMeta, abstractmethod @@ -66,18 +66,9 @@ def __init__( def __repr__(self) -> str: if isinstance(self.display, str) and self.display == self.text: - return "{}(text={!r}, start_position={!r})".format( - self.__class__.__name__, - self.text, - self.start_position, - ) + return f"{self.__class__.__name__}(text={self.text!r}, start_position={self.start_position!r})" else: - return "{}(text={!r}, start_position={!r}, display={!r})".format( - self.__class__.__name__, - self.text, - self.start_position, - self.display, - ) + return f"{self.__class__.__name__}(text={self.text!r}, start_position={self.start_position!r}, display={self.display!r})" def __eq__(self, other: object) -> bool: if not isinstance(other, Completion): @@ -156,11 +147,7 @@ def __init__( self.completion_requested = completion_requested def __repr__(self) -> str: - return "{}(text_inserted={!r}, completion_requested={!r})".format( - self.__class__.__name__, - self.text_inserted, - self.completion_requested, - ) + return f"{self.__class__.__name__}(text_inserted={self.text_inserted!r}, completion_requested={self.completion_requested!r})" class Completer(metaclass=ABCMeta): diff --git a/src/prompt_toolkit/completion/nested.py b/src/prompt_toolkit/completion/nested.py index a1d211ab06..8569bd2cff 100644 --- a/src/prompt_toolkit/completion/nested.py +++ b/src/prompt_toolkit/completion/nested.py @@ -1,6 +1,7 @@ """ Nestedcompleter for completion of hierarchical data structures. """ + from __future__ import annotations from typing import Any, Iterable, Mapping, Set, Union diff --git a/src/prompt_toolkit/contrib/regular_languages/__init__.py b/src/prompt_toolkit/contrib/regular_languages/__init__.py index c947fd5337..38b027cd16 100644 --- a/src/prompt_toolkit/contrib/regular_languages/__init__.py +++ b/src/prompt_toolkit/contrib/regular_languages/__init__.py @@ -72,6 +72,7 @@ - How to create an autocompleter from this grammar. - How to create a parser from this grammar. """ + from __future__ import annotations from .compiler import compile diff --git a/src/prompt_toolkit/contrib/regular_languages/compiler.py b/src/prompt_toolkit/contrib/regular_languages/compiler.py index 474f6cfd10..dd558a68a2 100644 --- a/src/prompt_toolkit/contrib/regular_languages/compiler.py +++ b/src/prompt_toolkit/contrib/regular_languages/compiler.py @@ -38,6 +38,7 @@ m.variables().get('operator2') # Returns "add" """ + from __future__ import annotations import re @@ -96,13 +97,13 @@ def __init__( counter = [0] def create_group_func(node: Variable) -> str: - name = "n%s" % counter[0] + name = f"n{counter[0]}" self._group_names_to_nodes[name] = node.varname counter[0] += 1 return name # Compile regex strings. - self._re_pattern = "^%s$" % self._transform(root_node, create_group_func) + self._re_pattern = f"^{self._transform(root_node, create_group_func)}$" self._re_prefix_patterns = list( self._transform_prefix(root_node, create_group_func) ) @@ -153,7 +154,7 @@ def _transform( def transform(node: Node) -> str: # Turn `AnyNode` into an OR. if isinstance(node, AnyNode): - return "(?:%s)" % "|".join(transform(c) for c in node.children) + return "(?:{})".format("|".join(transform(c) for c in node.children)) # Concatenate a `NodeSequence` elif isinstance(node, NodeSequence): @@ -311,11 +312,11 @@ def transform(node: Node) -> Iterable[str]: yield "".join(result) elif isinstance(node, Regex): - yield "(?:%s)?" % node.regex + yield f"(?:{node.regex})?" elif isinstance(node, Lookahead): if node.negative: - yield "(?!%s)" % cls._transform(node.childnode, create_group_func) + yield f"(?!{cls._transform(node.childnode, create_group_func)})" else: # Not sure what the correct semantics are in this case. # (Probably it's not worth implementing this.) @@ -349,10 +350,10 @@ def transform(node: Node) -> Iterable[str]: ) else: - raise TypeError("Got %r" % node) + raise TypeError(f"Got {node!r}") for r in transform(root_node): - yield "^(?:%s)$" % r + yield f"^(?:{r})$" def match(self, string: str) -> Match | None: """ diff --git a/src/prompt_toolkit/contrib/regular_languages/completion.py b/src/prompt_toolkit/contrib/regular_languages/completion.py index 2e353e8d5a..126e027523 100644 --- a/src/prompt_toolkit/contrib/regular_languages/completion.py +++ b/src/prompt_toolkit/contrib/regular_languages/completion.py @@ -1,6 +1,7 @@ """ Completer for a regular grammar. """ + from __future__ import annotations from typing import Iterable diff --git a/src/prompt_toolkit/contrib/regular_languages/lexer.py b/src/prompt_toolkit/contrib/regular_languages/lexer.py index b0a4debefa..c5434cfdee 100644 --- a/src/prompt_toolkit/contrib/regular_languages/lexer.py +++ b/src/prompt_toolkit/contrib/regular_languages/lexer.py @@ -2,6 +2,7 @@ `GrammarLexer` is compatible with other lexers and can be used to highlight the input using a regular grammar with annotations. """ + from __future__ import annotations from typing import Callable diff --git a/src/prompt_toolkit/contrib/regular_languages/regex_parser.py b/src/prompt_toolkit/contrib/regular_languages/regex_parser.py index a365ba8e04..353e54ff72 100644 --- a/src/prompt_toolkit/contrib/regular_languages/regex_parser.py +++ b/src/prompt_toolkit/contrib/regular_languages/regex_parser.py @@ -14,6 +14,7 @@ Limitations: - Lookahead is not supported. """ + from __future__ import annotations import re @@ -115,11 +116,7 @@ def __init__(self, childnode: Node, varname: str = "") -> None: self.varname = varname def __repr__(self) -> str: - return "{}(childnode={!r}, varname={!r})".format( - self.__class__.__name__, - self.childnode, - self.varname, - ) + return f"{self.__class__.__name__}(childnode={self.childnode!r}, varname={self.varname!r})" class Repeat(Node): @@ -265,7 +262,7 @@ def wrapped_result() -> Node: raise Exception(f"{t}-style repetition not yet supported") elif t.startswith("(?"): - raise Exception("%r not supported" % t) + raise Exception(f"{t!r} not supported") elif t.isspace(): pass diff --git a/src/prompt_toolkit/contrib/regular_languages/validation.py b/src/prompt_toolkit/contrib/regular_languages/validation.py index 8e56e05013..e6cfd74132 100644 --- a/src/prompt_toolkit/contrib/regular_languages/validation.py +++ b/src/prompt_toolkit/contrib/regular_languages/validation.py @@ -1,6 +1,7 @@ """ Validator for a regular language. """ + from __future__ import annotations from prompt_toolkit.document import Document diff --git a/src/prompt_toolkit/contrib/ssh/server.py b/src/prompt_toolkit/contrib/ssh/server.py index 9a5d4022a0..4badc6cad0 100644 --- a/src/prompt_toolkit/contrib/ssh/server.py +++ b/src/prompt_toolkit/contrib/ssh/server.py @@ -1,6 +1,7 @@ """ Utility for running a prompt_toolkit application in an asyncssh server. """ + from __future__ import annotations import asyncio diff --git a/src/prompt_toolkit/contrib/telnet/log.py b/src/prompt_toolkit/contrib/telnet/log.py index 0fe843375c..476dffc677 100644 --- a/src/prompt_toolkit/contrib/telnet/log.py +++ b/src/prompt_toolkit/contrib/telnet/log.py @@ -1,6 +1,7 @@ """ Python logger for the telnet server. """ + from __future__ import annotations import logging diff --git a/src/prompt_toolkit/contrib/telnet/protocol.py b/src/prompt_toolkit/contrib/telnet/protocol.py index 4b90e9853a..58286e23e7 100644 --- a/src/prompt_toolkit/contrib/telnet/protocol.py +++ b/src/prompt_toolkit/contrib/telnet/protocol.py @@ -4,6 +4,7 @@ Inspired by `Twisted.conch.telnet`. """ + from __future__ import annotations import struct diff --git a/src/prompt_toolkit/contrib/telnet/server.py b/src/prompt_toolkit/contrib/telnet/server.py index 9ebe66c62d..69e9a88adc 100644 --- a/src/prompt_toolkit/contrib/telnet/server.py +++ b/src/prompt_toolkit/contrib/telnet/server.py @@ -1,6 +1,7 @@ """ Telnet server. """ + from __future__ import annotations import asyncio @@ -99,7 +100,7 @@ def flush(self) -> None: if not self._closed: self._connection.send(b"".join(self._buffer)) except OSError as e: - logger.warning("Couldn't send data over socket: %s" % e) + logger.warning(f"Couldn't send data over socket: {e}") self._buffer = [] @@ -416,7 +417,7 @@ async def run() -> None: # Unhandled control-c propagated by a prompt. logger.info("Unhandled KeyboardInterrupt in telnet application.") except BaseException as e: - print("Got %s" % type(e).__name__, e) + print(f"Got {type(e).__name__}", e) import traceback traceback.print_exc() diff --git a/src/prompt_toolkit/document.py b/src/prompt_toolkit/document.py index 74f4c13f86..df5293e626 100644 --- a/src/prompt_toolkit/document.py +++ b/src/prompt_toolkit/document.py @@ -1,6 +1,7 @@ """ The `Document` that implements all the text operations/querying. """ + from __future__ import annotations import bisect diff --git a/src/prompt_toolkit/eventloop/async_generator.py b/src/prompt_toolkit/eventloop/async_generator.py index 5aee50a409..32e5f88247 100644 --- a/src/prompt_toolkit/eventloop/async_generator.py +++ b/src/prompt_toolkit/eventloop/async_generator.py @@ -1,6 +1,7 @@ """ Implementation for async generators. """ + from __future__ import annotations from asyncio import get_running_loop diff --git a/src/prompt_toolkit/eventloop/inputhook.py b/src/prompt_toolkit/eventloop/inputhook.py index a4c0eee6bb..40016e87f6 100644 --- a/src/prompt_toolkit/eventloop/inputhook.py +++ b/src/prompt_toolkit/eventloop/inputhook.py @@ -22,6 +22,7 @@ asynchronous autocompletion. When the completion for instance is ready, we also want prompt-toolkit to gain control again in order to display that. """ + from __future__ import annotations import asyncio diff --git a/src/prompt_toolkit/filters/__init__.py b/src/prompt_toolkit/filters/__init__.py index 277f428ee9..556ed8846b 100644 --- a/src/prompt_toolkit/filters/__init__.py +++ b/src/prompt_toolkit/filters/__init__.py @@ -16,6 +16,7 @@ filter = has_focus('default') & ~ has_selection """ + from __future__ import annotations from .app import * diff --git a/src/prompt_toolkit/filters/app.py b/src/prompt_toolkit/filters/app.py index aacb228416..b1b7c1beea 100644 --- a/src/prompt_toolkit/filters/app.py +++ b/src/prompt_toolkit/filters/app.py @@ -1,6 +1,7 @@ """ Filters that accept a `Application` as argument. """ + from __future__ import annotations from typing import TYPE_CHECKING, cast diff --git a/src/prompt_toolkit/filters/base.py b/src/prompt_toolkit/filters/base.py index aefd9bfbd8..410749db47 100644 --- a/src/prompt_toolkit/filters/base.py +++ b/src/prompt_toolkit/filters/base.py @@ -30,7 +30,7 @@ def __and__(self, other: Filter) -> Filter: """ Chaining of filters using the & operator. """ - assert isinstance(other, Filter), "Expecting filter, got %r" % other + assert isinstance(other, Filter), f"Expecting filter, got {other!r}" if isinstance(other, Always): return self @@ -48,7 +48,7 @@ def __or__(self, other: Filter) -> Filter: """ Chaining of filters using the | operator. """ - assert isinstance(other, Filter), "Expecting filter, got %r" % other + assert isinstance(other, Filter), f"Expecting filter, got {other!r}" if isinstance(other, Always): return other @@ -193,7 +193,7 @@ def __call__(self) -> bool: return not self.filter() def __repr__(self) -> str: - return "~%r" % self.filter + return f"~{self.filter!r}" class Always(Filter): @@ -254,7 +254,7 @@ def __call__(self) -> bool: return self.func() def __repr__(self) -> str: - return "Condition(%r)" % self.func + return f"Condition({self.func!r})" # Often used as type annotation. diff --git a/src/prompt_toolkit/filters/cli.py b/src/prompt_toolkit/filters/cli.py index c95080a927..902fbaae98 100644 --- a/src/prompt_toolkit/filters/cli.py +++ b/src/prompt_toolkit/filters/cli.py @@ -2,6 +2,7 @@ For backwards-compatibility. keep this file. (Many people are going to have key bindings that rely on this file.) """ + from __future__ import annotations from .app import * diff --git a/src/prompt_toolkit/filters/utils.py b/src/prompt_toolkit/filters/utils.py index bac85bab62..20e00ee09e 100644 --- a/src/prompt_toolkit/filters/utils.py +++ b/src/prompt_toolkit/filters/utils.py @@ -29,7 +29,7 @@ def to_filter(bool_or_filter: FilterOrBool) -> Filter: if isinstance(bool_or_filter, Filter): return bool_or_filter - raise TypeError("Expecting a bool or a Filter instance. Got %r" % bool_or_filter) + raise TypeError(f"Expecting a bool or a Filter instance. Got {bool_or_filter!r}") def is_true(value: FilterOrBool) -> bool: diff --git a/src/prompt_toolkit/formatted_text/__init__.py b/src/prompt_toolkit/formatted_text/__init__.py index db44ab9266..0590c81585 100644 --- a/src/prompt_toolkit/formatted_text/__init__.py +++ b/src/prompt_toolkit/formatted_text/__init__.py @@ -10,6 +10,7 @@ `(style_string, text)` tuples. The :func:`.to_formatted_text` conversion function takes any of these and turns all of them into such a tuple sequence. """ + from __future__ import annotations from .ansi import ANSI diff --git a/src/prompt_toolkit/formatted_text/ansi.py b/src/prompt_toolkit/formatted_text/ansi.py index 08ec0b322e..4761982ab3 100644 --- a/src/prompt_toolkit/formatted_text/ansi.py +++ b/src/prompt_toolkit/formatted_text/ansi.py @@ -210,10 +210,8 @@ def _select_graphic_rendition(self, attrs: list[int]) -> None: # True colors. if n == 2 and len(attrs) >= 3: try: - color_str = "#{:02x}{:02x}{:02x}".format( - attrs.pop(), - attrs.pop(), - attrs.pop(), + color_str = ( + f"#{attrs.pop():02x}{attrs.pop():02x}{attrs.pop():02x}" ) except IndexError: pass diff --git a/src/prompt_toolkit/formatted_text/base.py b/src/prompt_toolkit/formatted_text/base.py index 92de353577..5fee1f862d 100644 --- a/src/prompt_toolkit/formatted_text/base.py +++ b/src/prompt_toolkit/formatted_text/base.py @@ -38,8 +38,7 @@ class MagicFormattedText(Protocol): text. """ - def __pt_formatted_text__(self) -> StyleAndTextTuples: - ... + def __pt_formatted_text__(self) -> StyleAndTextTuples: ... AnyFormattedText = Union[ @@ -132,7 +131,7 @@ def __pt_formatted_text__(self) -> StyleAndTextTuples: return self def __repr__(self) -> str: - return "FormattedText(%s)" % super().__repr__() + return f"FormattedText({super().__repr__()})" class Template: diff --git a/src/prompt_toolkit/formatted_text/utils.py b/src/prompt_toolkit/formatted_text/utils.py index c8c37e0946..43228c3cda 100644 --- a/src/prompt_toolkit/formatted_text/utils.py +++ b/src/prompt_toolkit/formatted_text/utils.py @@ -4,6 +4,7 @@ When ``to_formatted_text`` has been called, we get a list of ``(style, text)`` tuples. This file contains functions for manipulating such a list. """ + from __future__ import annotations from typing import Iterable, cast diff --git a/src/prompt_toolkit/history.py b/src/prompt_toolkit/history.py index ea1f225b13..c82358de2e 100644 --- a/src/prompt_toolkit/history.py +++ b/src/prompt_toolkit/history.py @@ -7,6 +7,7 @@ loading can be done asynchronously and making the history swappable would probably break this. """ + from __future__ import annotations import datetime @@ -297,6 +298,6 @@ def store_string(self, string: str) -> None: def write(t: str) -> None: f.write(t.encode("utf-8")) - write("\n# %s\n" % datetime.datetime.now()) + write(f"\n# {datetime.datetime.now()}\n") for line in string.split("\n"): - write("+%s\n" % line) + write(f"+{line}\n") diff --git a/src/prompt_toolkit/input/ansi_escape_sequences.py b/src/prompt_toolkit/input/ansi_escape_sequences.py index 5648c6646a..1fba418b73 100644 --- a/src/prompt_toolkit/input/ansi_escape_sequences.py +++ b/src/prompt_toolkit/input/ansi_escape_sequences.py @@ -10,6 +10,7 @@ Some useful docs: - Mintty: https://github.com/mintty/mintty/blob/master/wiki/Keycodes.md """ + from __future__ import annotations from ..keys import Keys diff --git a/src/prompt_toolkit/input/base.py b/src/prompt_toolkit/input/base.py index fd1429df2e..3dcb994bd9 100644 --- a/src/prompt_toolkit/input/base.py +++ b/src/prompt_toolkit/input/base.py @@ -1,6 +1,7 @@ """ Abstraction of CLI Input. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod, abstractproperty @@ -116,7 +117,7 @@ def fileno(self) -> int: raise NotImplementedError def typeahead_hash(self) -> str: - return "dummy-%s" % id(self) + return f"dummy-{id(self)}" def read_keys(self) -> list[KeyPress]: return [] diff --git a/src/prompt_toolkit/input/typeahead.py b/src/prompt_toolkit/input/typeahead.py index a45e7cf50b..f8faa93289 100644 --- a/src/prompt_toolkit/input/typeahead.py +++ b/src/prompt_toolkit/input/typeahead.py @@ -31,6 +31,7 @@ read too early, so that they can be feed into to the next `prompt()` call or to the next prompt_toolkit `Application`. """ + from __future__ import annotations from collections import defaultdict diff --git a/src/prompt_toolkit/input/vt100_parser.py b/src/prompt_toolkit/input/vt100_parser.py index 99e2d99c58..73dbce3d83 100644 --- a/src/prompt_toolkit/input/vt100_parser.py +++ b/src/prompt_toolkit/input/vt100_parser.py @@ -1,6 +1,7 @@ """ Parser for VT100 input stream. """ + from __future__ import annotations import re diff --git a/src/prompt_toolkit/input/win32.py b/src/prompt_toolkit/input/win32.py index 35e8948d22..322d7c0d72 100644 --- a/src/prompt_toolkit/input/win32.py +++ b/src/prompt_toolkit/input/win32.py @@ -329,8 +329,8 @@ def _merge_paired_surrogates(key_presses: list[KeyPress]) -> Iterator[KeyPress]: buffered_high_surrogate = None for key in key_presses: is_text = not isinstance(key.key, Keys) - is_high_surrogate = is_text and "\uD800" <= key.key <= "\uDBFF" - is_low_surrogate = is_text and "\uDC00" <= key.key <= "\uDFFF" + is_high_surrogate = is_text and "\ud800" <= key.key <= "\udbff" + is_low_surrogate = is_text and "\udc00" <= key.key <= "\udfff" if buffered_high_surrogate: if is_low_surrogate: diff --git a/src/prompt_toolkit/key_binding/bindings/auto_suggest.py b/src/prompt_toolkit/key_binding/bindings/auto_suggest.py index 3d8a843d4a..b487f14ffe 100644 --- a/src/prompt_toolkit/key_binding/bindings/auto_suggest.py +++ b/src/prompt_toolkit/key_binding/bindings/auto_suggest.py @@ -1,6 +1,7 @@ """ Key bindings for auto suggestion (for fish-style auto suggestion). """ + from __future__ import annotations import re diff --git a/src/prompt_toolkit/key_binding/bindings/completion.py b/src/prompt_toolkit/key_binding/bindings/completion.py index 016821f492..8c5e005da8 100644 --- a/src/prompt_toolkit/key_binding/bindings/completion.py +++ b/src/prompt_toolkit/key_binding/bindings/completion.py @@ -1,6 +1,7 @@ """ Key binding handlers for displaying completions. """ + from __future__ import annotations import asyncio diff --git a/src/prompt_toolkit/key_binding/bindings/named_commands.py b/src/prompt_toolkit/key_binding/bindings/named_commands.py index d8361169f9..8ea8dd03de 100644 --- a/src/prompt_toolkit/key_binding/bindings/named_commands.py +++ b/src/prompt_toolkit/key_binding/bindings/named_commands.py @@ -3,6 +3,7 @@ See: http://www.delorie.com/gnu/docs/readline/rlman_13.html """ + from __future__ import annotations from typing import Callable, TypeVar, Union, cast @@ -58,7 +59,7 @@ def get_by_name(name: str) -> Binding: try: return _readline_commands[name] except KeyError as e: - raise KeyError("Unknown Readline command: %r" % name) from e + raise KeyError(f"Unknown Readline command: {name!r}") from e # diff --git a/src/prompt_toolkit/key_binding/bindings/open_in_editor.py b/src/prompt_toolkit/key_binding/bindings/open_in_editor.py index d156424f20..26b8685b0a 100644 --- a/src/prompt_toolkit/key_binding/bindings/open_in_editor.py +++ b/src/prompt_toolkit/key_binding/bindings/open_in_editor.py @@ -1,6 +1,7 @@ """ Open in editor key bindings. """ + from __future__ import annotations from prompt_toolkit.filters import emacs_mode, has_selection, vi_navigation_mode diff --git a/src/prompt_toolkit/key_binding/bindings/page_navigation.py b/src/prompt_toolkit/key_binding/bindings/page_navigation.py index 3918e14120..c490425fe2 100644 --- a/src/prompt_toolkit/key_binding/bindings/page_navigation.py +++ b/src/prompt_toolkit/key_binding/bindings/page_navigation.py @@ -2,6 +2,7 @@ Key bindings for extra page navigation: bindings for up/down scrolling through long pages, like in Emacs or Vi. """ + from __future__ import annotations from prompt_toolkit.filters import buffer_has_focus, emacs_mode, vi_mode diff --git a/src/prompt_toolkit/key_binding/bindings/scroll.py b/src/prompt_toolkit/key_binding/bindings/scroll.py index 83a4be1f8f..13e44ed4dc 100644 --- a/src/prompt_toolkit/key_binding/bindings/scroll.py +++ b/src/prompt_toolkit/key_binding/bindings/scroll.py @@ -5,6 +5,7 @@ they are very useful for navigating through long multiline buffers, like in Vi, Emacs, etc... """ + from __future__ import annotations from prompt_toolkit.key_binding.key_processor import KeyPressEvent diff --git a/src/prompt_toolkit/key_binding/bindings/search.py b/src/prompt_toolkit/key_binding/bindings/search.py index ba5e117ff6..a57c52e4f2 100644 --- a/src/prompt_toolkit/key_binding/bindings/search.py +++ b/src/prompt_toolkit/key_binding/bindings/search.py @@ -1,6 +1,7 @@ """ Search related key bindings. """ + from __future__ import annotations from prompt_toolkit import search diff --git a/src/prompt_toolkit/key_binding/defaults.py b/src/prompt_toolkit/key_binding/defaults.py index 166da8d4ac..6c26571160 100644 --- a/src/prompt_toolkit/key_binding/defaults.py +++ b/src/prompt_toolkit/key_binding/defaults.py @@ -4,6 +4,7 @@ key_bindings = load_key_bindings() app = Application(key_bindings=key_bindings) """ + from __future__ import annotations from prompt_toolkit.filters import buffer_has_focus diff --git a/src/prompt_toolkit/key_binding/digraphs.py b/src/prompt_toolkit/key_binding/digraphs.py index 1e8a43266b..f0152dc4cb 100644 --- a/src/prompt_toolkit/key_binding/digraphs.py +++ b/src/prompt_toolkit/key_binding/digraphs.py @@ -6,6 +6,7 @@ Taken from Neovim and translated to Python: https://raw.githubusercontent.com/neovim/neovim/master/src/nvim/digraph.c """ + from __future__ import annotations __all__ = [ diff --git a/src/prompt_toolkit/key_binding/key_bindings.py b/src/prompt_toolkit/key_binding/key_bindings.py index 62530f2b77..854da8012b 100644 --- a/src/prompt_toolkit/key_binding/key_bindings.py +++ b/src/prompt_toolkit/key_binding/key_bindings.py @@ -34,6 +34,7 @@ def my_key_binding(event): # Later, add it to the key bindings. kb.add(Keys.A, my_key_binding) """ + from __future__ import annotations from abc import ABCMeta, abstractmethod, abstractproperty @@ -140,10 +141,8 @@ async def bg_task() -> None: event.app.invalidate() def __repr__(self) -> str: - return "{}(keys={!r}, handler={!r})".format( - self.__class__.__name__, - self.keys, - self.handler, + return ( + f"{self.__class__.__name__}(keys={self.keys!r}, handler={self.handler!r})" ) @@ -226,9 +225,9 @@ def _(event): def __init__(self) -> None: self._bindings: list[Binding] = [] - self._get_bindings_for_keys_cache: SimpleCache[ - KeysTuple, list[Binding] - ] = SimpleCache(maxsize=10000) + self._get_bindings_for_keys_cache: SimpleCache[KeysTuple, list[Binding]] = ( + SimpleCache(maxsize=10000) + ) self._get_bindings_starting_with_keys_cache: SimpleCache[ KeysTuple, list[Binding] ] = SimpleCache(maxsize=1000) diff --git a/src/prompt_toolkit/key_binding/key_processor.py b/src/prompt_toolkit/key_binding/key_processor.py index 4c4f0d155d..e2070a14f0 100644 --- a/src/prompt_toolkit/key_binding/key_processor.py +++ b/src/prompt_toolkit/key_binding/key_processor.py @@ -5,6 +5,7 @@ The `KeyProcessor` will according to the implemented keybindings call the correct callbacks when new key presses are feed through `feed`. """ + from __future__ import annotations import weakref @@ -450,11 +451,7 @@ def __init__( self._app = get_app() def __repr__(self) -> str: - return "KeyPressEvent(arg={!r}, key_sequence={!r}, is_repeat={!r})".format( - self.arg, - self.key_sequence, - self.is_repeat, - ) + return f"KeyPressEvent(arg={self.arg!r}, key_sequence={self.key_sequence!r}, is_repeat={self.is_repeat!r})" @property def data(self) -> str: diff --git a/src/prompt_toolkit/layout/__init__.py b/src/prompt_toolkit/layout/__init__.py index c5fce461a0..7cd0c7725c 100644 --- a/src/prompt_toolkit/layout/__init__.py +++ b/src/prompt_toolkit/layout/__init__.py @@ -44,6 +44,7 @@ - CompletionsMenu """ + from __future__ import annotations from .containers import ( diff --git a/src/prompt_toolkit/layout/containers.py b/src/prompt_toolkit/layout/containers.py index 100d4aaebc..99b453477c 100644 --- a/src/prompt_toolkit/layout/containers.py +++ b/src/prompt_toolkit/layout/containers.py @@ -2,6 +2,7 @@ Container for the layout. (Containers can contain other containers or user interface controls.) """ + from __future__ import annotations from abc import ABCMeta, abstractmethod @@ -156,8 +157,7 @@ class MagicContainer(Protocol): Any object that implements ``__pt_container__`` represents a container. """ - def __pt_container__(self) -> AnyContainer: - ... + def __pt_container__(self) -> AnyContainer: ... AnyContainer = Union[Container, "MagicContainer"] @@ -296,9 +296,9 @@ def __init__( self.align = align - self._children_cache: SimpleCache[ - tuple[Container, ...], list[Container] - ] = SimpleCache(maxsize=1) + self._children_cache: SimpleCache[tuple[Container, ...], list[Container]] = ( + SimpleCache(maxsize=1) + ) self._remaining_space_window = Window() # Dummy window. def preferred_width(self, max_available_width: int) -> Dimension: @@ -533,9 +533,9 @@ def __init__( self.align = align - self._children_cache: SimpleCache[ - tuple[Container, ...], list[Container] - ] = SimpleCache(maxsize=1) + self._children_cache: SimpleCache[tuple[Container, ...], list[Container]] = ( + SimpleCache(maxsize=1) + ) self._remaining_space_window = Window() # Dummy window. def preferred_width(self, max_available_width: int) -> Dimension: @@ -1093,7 +1093,7 @@ def get_height(self) -> int | None: return self.height def __repr__(self) -> str: - return "Float(content=%r)" % self.content + return f"Float(content={self.content!r})" class WindowRenderInfo: @@ -1352,12 +1352,7 @@ def right(self) -> int: return to_int(self._right) def __repr__(self) -> str: - return "ScrollOffsets(top={!r}, bottom={!r}, left={!r}, right={!r})".format( - self._top, - self._bottom, - self._left, - self._right, - ) + return f"ScrollOffsets(top={self._top!r}, bottom={self._bottom!r}, left={self._left!r}, right={self._right!r})" class ColorColumn: @@ -1504,9 +1499,9 @@ def __init__( self.z_index = z_index # Cache for the screens generated by the margin. - self._ui_content_cache: SimpleCache[ - tuple[int, int, int], UIContent - ] = SimpleCache(maxsize=8) + self._ui_content_cache: SimpleCache[tuple[int, int, int], UIContent] = ( + SimpleCache(maxsize=8) + ) self._margin_width_cache: SimpleCache[tuple[Margin, int], int] = SimpleCache( maxsize=1 ) @@ -1514,7 +1509,7 @@ def __init__( self.reset() def __repr__(self) -> str: - return "Window(content=%r)" % self.content + return f"Window(content={self.content!r})" def reset(self) -> None: self.content.reset() diff --git a/src/prompt_toolkit/layout/controls.py b/src/prompt_toolkit/layout/controls.py index c30c0effa8..222e471c57 100644 --- a/src/prompt_toolkit/layout/controls.py +++ b/src/prompt_toolkit/layout/controls.py @@ -1,6 +1,7 @@ """ User interface Controls for the layout. """ + from __future__ import annotations import time diff --git a/src/prompt_toolkit/layout/dimension.py b/src/prompt_toolkit/layout/dimension.py index c1f05f9439..2e6f5dd4eb 100644 --- a/src/prompt_toolkit/layout/dimension.py +++ b/src/prompt_toolkit/layout/dimension.py @@ -2,6 +2,7 @@ Layout dimensions are used to give the minimum, maximum and preferred dimensions for containers and controls. """ + from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, Union @@ -105,15 +106,15 @@ def is_zero(self) -> bool: def __repr__(self) -> str: fields = [] if self.min_specified: - fields.append("min=%r" % self.min) + fields.append(f"min={self.min!r}") if self.max_specified: - fields.append("max=%r" % self.max) + fields.append(f"max={self.max!r}") if self.preferred_specified: - fields.append("preferred=%r" % self.preferred) + fields.append(f"preferred={self.preferred!r}") if self.weight_specified: - fields.append("weight=%r" % self.weight) + fields.append(f"weight={self.weight!r}") - return "Dimension(%s)" % ", ".join(fields) + return "Dimension({})".format(", ".join(fields)) def sum_layout_dimensions(dimensions: list[Dimension]) -> Dimension: diff --git a/src/prompt_toolkit/layout/dummy.py b/src/prompt_toolkit/layout/dummy.py index 139f311579..1ee3e6c9bd 100644 --- a/src/prompt_toolkit/layout/dummy.py +++ b/src/prompt_toolkit/layout/dummy.py @@ -2,6 +2,7 @@ Dummy layout. Used when somebody creates an `Application` without specifying a `Layout`. """ + from __future__ import annotations from prompt_toolkit.formatted_text import HTML diff --git a/src/prompt_toolkit/layout/layout.py b/src/prompt_toolkit/layout/layout.py index a5e7a80e75..f9b7110925 100644 --- a/src/prompt_toolkit/layout/layout.py +++ b/src/prompt_toolkit/layout/layout.py @@ -1,6 +1,7 @@ """ Wrapper for the layout. """ + from __future__ import annotations from typing import Generator, Iterable, Union diff --git a/src/prompt_toolkit/layout/margins.py b/src/prompt_toolkit/layout/margins.py index cc9dd964b4..737a74d29b 100644 --- a/src/prompt_toolkit/layout/margins.py +++ b/src/prompt_toolkit/layout/margins.py @@ -1,6 +1,7 @@ """ Margin implementations for a :class:`~prompt_toolkit.layout.containers.Window`. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod @@ -83,7 +84,7 @@ def __init__( def get_width(self, get_ui_content: Callable[[], UIContent]) -> int: line_count = get_ui_content().line_count - return max(3, len("%s" % line_count) + 1) + return max(3, len(f"{line_count}") + 1) def create_margin( self, window_render_info: WindowRenderInfo, width: int, height: int diff --git a/src/prompt_toolkit/layout/menus.py b/src/prompt_toolkit/layout/menus.py index 2c2ccb6436..612e8ab6a3 100644 --- a/src/prompt_toolkit/layout/menus.py +++ b/src/prompt_toolkit/layout/menus.py @@ -212,10 +212,7 @@ def _get_menu_item_fragments( width. """ if is_current_completion: - style_str = "class:completion-menu.completion.current {} {}".format( - completion.style, - completion.selected_style, - ) + style_str = f"class:completion-menu.completion.current {completion.style} {completion.selected_style}" else: style_str = "class:completion-menu.completion " + completion.style diff --git a/src/prompt_toolkit/layout/mouse_handlers.py b/src/prompt_toolkit/layout/mouse_handlers.py index 56a4eddd9d..52deac1456 100644 --- a/src/prompt_toolkit/layout/mouse_handlers.py +++ b/src/prompt_toolkit/layout/mouse_handlers.py @@ -34,9 +34,9 @@ def dummy_callback(mouse_event: MouseEvent) -> NotImplementedOrNone: # over the mouse handlers of the visible region in the scrollable pane. # Map y (row) to x (column) to handlers. - self.mouse_handlers: defaultdict[ - int, defaultdict[int, MouseHandler] - ] = defaultdict(lambda: defaultdict(lambda: dummy_callback)) + self.mouse_handlers: defaultdict[int, defaultdict[int, MouseHandler]] = ( + defaultdict(lambda: defaultdict(lambda: dummy_callback)) + ) def set_mouse_handler_for_range( self, diff --git a/src/prompt_toolkit/layout/processors.py b/src/prompt_toolkit/layout/processors.py index b7376115e4..b10ecf7184 100644 --- a/src/prompt_toolkit/layout/processors.py +++ b/src/prompt_toolkit/layout/processors.py @@ -5,6 +5,7 @@ They can insert fragments before or after, or highlight fragments by replacing the fragment types. """ + from __future__ import annotations import re @@ -343,9 +344,9 @@ def __init__( self.chars = chars self.max_cursor_distance = max_cursor_distance - self._positions_cache: SimpleCache[ - Hashable, list[tuple[int, int]] - ] = SimpleCache(maxsize=8) + self._positions_cache: SimpleCache[Hashable, list[tuple[int, int]]] = ( + SimpleCache(maxsize=8) + ) def _get_positions_to_highlight(self, document: Document) -> list[tuple[int, int]]: """ @@ -924,11 +925,7 @@ def apply_transformation( return Transformation(transformation_input.fragments) def __repr__(self) -> str: - return "{}(processor={!r}, filter={!r})".format( - self.__class__.__name__, - self.processor, - self.filter, - ) + return f"{self.__class__.__name__}(processor={self.processor!r}, filter={self.filter!r})" class DynamicProcessor(Processor): diff --git a/src/prompt_toolkit/layout/screen.py b/src/prompt_toolkit/layout/screen.py index 49aebbd626..0f19f52a8d 100644 --- a/src/prompt_toolkit/layout/screen.py +++ b/src/prompt_toolkit/layout/screen.py @@ -320,10 +320,4 @@ def __init__(self, xpos: int, ypos: int, width: int, height: int) -> None: self.height = height def __repr__(self) -> str: - return "{}(x={!r}, y={!r}, width={!r}, height={!r})".format( - self.__class__.__name__, - self.xpos, - self.ypos, - self.width, - self.height, - ) + return f"{self.__class__.__name__}(x={self.xpos!r}, y={self.ypos!r}, width={self.width!r}, height={self.height!r})" diff --git a/src/prompt_toolkit/layout/utils.py b/src/prompt_toolkit/layout/utils.py index 0f78f3713c..373fe52a5a 100644 --- a/src/prompt_toolkit/layout/utils.py +++ b/src/prompt_toolkit/layout/utils.py @@ -36,12 +36,10 @@ def insert(self, index: SupportsIndex, item: _T) -> None: # TODO: When creating a copy() or [:], return also an _ExplodedList. @overload - def __setitem__(self, index: SupportsIndex, value: _T) -> None: - ... + def __setitem__(self, index: SupportsIndex, value: _T) -> None: ... @overload - def __setitem__(self, index: slice, value: Iterable[_T]) -> None: - ... + def __setitem__(self, index: slice, value: Iterable[_T]) -> None: ... def __setitem__( self, index: SupportsIndex | slice, value: _T | Iterable[_T] diff --git a/src/prompt_toolkit/lexers/__init__.py b/src/prompt_toolkit/lexers/__init__.py index 9bdc599847..8f72d07ff2 100644 --- a/src/prompt_toolkit/lexers/__init__.py +++ b/src/prompt_toolkit/lexers/__init__.py @@ -2,6 +2,7 @@ Lexer interface and implementations. Used for syntax highlighting. """ + from __future__ import annotations from .base import DynamicLexer, Lexer, SimpleLexer diff --git a/src/prompt_toolkit/lexers/base.py b/src/prompt_toolkit/lexers/base.py index 3f65f8e7c1..c61e2b9d32 100644 --- a/src/prompt_toolkit/lexers/base.py +++ b/src/prompt_toolkit/lexers/base.py @@ -1,6 +1,7 @@ """ Base classes for prompt_toolkit lexers. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod diff --git a/src/prompt_toolkit/lexers/pygments.py b/src/prompt_toolkit/lexers/pygments.py index 4721d730c8..d5a39c4993 100644 --- a/src/prompt_toolkit/lexers/pygments.py +++ b/src/prompt_toolkit/lexers/pygments.py @@ -4,6 +4,7 @@ This includes syntax synchronization code, so that we don't have to start lexing at the beginning of a document, when displaying a very large text. """ + from __future__ import annotations import re diff --git a/src/prompt_toolkit/log.py b/src/prompt_toolkit/log.py index adb5172afd..285357927a 100644 --- a/src/prompt_toolkit/log.py +++ b/src/prompt_toolkit/log.py @@ -1,6 +1,7 @@ """ Logging configuration. """ + from __future__ import annotations import logging diff --git a/src/prompt_toolkit/mouse_events.py b/src/prompt_toolkit/mouse_events.py index 743773b506..f244f8eac4 100644 --- a/src/prompt_toolkit/mouse_events.py +++ b/src/prompt_toolkit/mouse_events.py @@ -15,6 +15,7 @@ coordinates to coordinates relative to the user control, and there `UIControl.mouse_handler` is called. """ + from __future__ import annotations from enum import Enum @@ -81,9 +82,4 @@ def __init__( self.modifiers = modifiers def __repr__(self) -> str: - return "MouseEvent({!r},{!r},{!r},{!r})".format( - self.position, - self.event_type, - self.button, - self.modifiers, - ) + return f"MouseEvent({self.position!r},{self.event_type!r},{self.button!r},{self.modifiers!r})" diff --git a/src/prompt_toolkit/output/base.py b/src/prompt_toolkit/output/base.py index 3c38cec86e..6ba09fdd08 100644 --- a/src/prompt_toolkit/output/base.py +++ b/src/prompt_toolkit/output/base.py @@ -1,6 +1,7 @@ """ Interface for an output. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod diff --git a/src/prompt_toolkit/output/vt100.py b/src/prompt_toolkit/output/vt100.py index 142deab077..069636b8c3 100644 --- a/src/prompt_toolkit/output/vt100.py +++ b/src/prompt_toolkit/output/vt100.py @@ -6,6 +6,7 @@ everything has been highly optimized.) http://pygments.org/ """ + from __future__ import annotations import io @@ -521,7 +522,7 @@ def set_title(self, title: str) -> None: "eterm-color", ): # Not supported by the Linux console. self.write_raw( - "\x1b]2;%s\x07" % title.replace("\x1b", "").replace("\x07", "") + "\x1b]2;{}\x07".format(title.replace("\x1b", "").replace("\x07", "")) ) def clear_title(self) -> None: diff --git a/src/prompt_toolkit/output/win32.py b/src/prompt_toolkit/output/win32.py index edeca0968d..83ccea43fc 100644 --- a/src/prompt_toolkit/output/win32.py +++ b/src/prompt_toolkit/output/win32.py @@ -73,11 +73,11 @@ def __init__(self) -> None: if xterm: message = ( - "Found %s, while expecting a Windows console. " + "Found {}, while expecting a Windows console. " 'Maybe try to run this program using "winpty" ' "or run it in cmd.exe instead. Or otherwise, " "in case of Cygwin, use the Python executable " - "that is compiled for Cygwin." % os.environ["TERM"] + "that is compiled for Cygwin.".format(os.environ["TERM"]) ) else: message = "No Windows console found. Are you running cmd.exe?" @@ -163,13 +163,13 @@ def _winapi(self, func: Callable[..., _T], *a: object, **kw: object) -> _T: self.flush() if _DEBUG_RENDER_OUTPUT: - self.LOG.write(("%r" % func.__name__).encode("utf-8") + b"\n") + self.LOG.write((f"{func.__name__!r}").encode() + b"\n") self.LOG.write( - b" " + ", ".join(["%r" % i for i in a]).encode("utf-8") + b"\n" + b" " + ", ".join([f"{i!r}" for i in a]).encode("utf-8") + b"\n" ) self.LOG.write( b" " - + ", ".join(["%r" % type(i) for i in a]).encode("utf-8") + + ", ".join([f"{type(i)!r}" for i in a]).encode("utf-8") + b"\n" ) self.LOG.flush() @@ -370,7 +370,7 @@ def flush(self) -> None: data = "".join(self._buffer) if _DEBUG_RENDER_OUTPUT: - self.LOG.write(("%r" % data).encode("utf-8") + b"\n") + self.LOG.write((f"{data!r}").encode() + b"\n") self.LOG.flush() # Print characters one by one. This appears to be the best solution diff --git a/src/prompt_toolkit/patch_stdout.py b/src/prompt_toolkit/patch_stdout.py index 528bec7ffe..4958e9d2e4 100644 --- a/src/prompt_toolkit/patch_stdout.py +++ b/src/prompt_toolkit/patch_stdout.py @@ -17,6 +17,7 @@ Multiple applications can run in the body of the context manager, one after the other. """ + from __future__ import annotations import asyncio diff --git a/src/prompt_toolkit/renderer.py b/src/prompt_toolkit/renderer.py index 5ad1dd68d0..3f92303a81 100644 --- a/src/prompt_toolkit/renderer.py +++ b/src/prompt_toolkit/renderer.py @@ -2,6 +2,7 @@ Renders the command line on the console. (Redraws parts of the input line that were changed.) """ + from __future__ import annotations from asyncio import FIRST_COMPLETED, Future, ensure_future, sleep, wait diff --git a/src/prompt_toolkit/search.py b/src/prompt_toolkit/search.py index fd90a04e90..d1cf7acbac 100644 --- a/src/prompt_toolkit/search.py +++ b/src/prompt_toolkit/search.py @@ -5,6 +5,7 @@ `prompt_toolkit.key_binding.bindings.search`. (Use these for new key bindings instead of calling these function directly.) """ + from __future__ import annotations from enum import Enum @@ -59,12 +60,7 @@ def __init__( self.ignore_case = to_filter(ignore_case) def __repr__(self) -> str: - return "{}({!r}, direction={!r}, ignore_case={!r})".format( - self.__class__.__name__, - self.text, - self.direction, - self.ignore_case, - ) + return f"{self.__class__.__name__}({self.text!r}, direction={self.direction!r}, ignore_case={self.ignore_case!r})" def __invert__(self) -> SearchState: """ diff --git a/src/prompt_toolkit/selection.py b/src/prompt_toolkit/selection.py index 2158fa92a2..ff88535b0f 100644 --- a/src/prompt_toolkit/selection.py +++ b/src/prompt_toolkit/selection.py @@ -1,6 +1,7 @@ """ Data structures for the selection. """ + from __future__ import annotations from enum import Enum @@ -54,8 +55,4 @@ def enter_shift_mode(self) -> None: self.shift_mode = True def __repr__(self) -> str: - return "{}(original_cursor_position={!r}, type={!r})".format( - self.__class__.__name__, - self.original_cursor_position, - self.type, - ) + return f"{self.__class__.__name__}(original_cursor_position={self.original_cursor_position!r}, type={self.type!r})" diff --git a/src/prompt_toolkit/shortcuts/progress_bar/base.py b/src/prompt_toolkit/shortcuts/progress_bar/base.py index 21aa1bece5..a7c2a527d8 100644 --- a/src/prompt_toolkit/shortcuts/progress_bar/base.py +++ b/src/prompt_toolkit/shortcuts/progress_bar/base.py @@ -7,6 +7,7 @@ for item in pb(data): ... """ + from __future__ import annotations import contextvars diff --git a/src/prompt_toolkit/shortcuts/progress_bar/formatters.py b/src/prompt_toolkit/shortcuts/progress_bar/formatters.py index b1a89dd6d0..202949ca07 100644 --- a/src/prompt_toolkit/shortcuts/progress_bar/formatters.py +++ b/src/prompt_toolkit/shortcuts/progress_bar/formatters.py @@ -2,6 +2,7 @@ Formatter classes for the progress bar. Each progress bar consists of a list of these formatters. """ + from __future__ import annotations import datetime @@ -149,7 +150,9 @@ class Bar(Formatter): Display the progress bar itself. """ - template = HTML("{start}{bar_a}{bar_b}{bar_c}{end}") + template = HTML( + "{start}{bar_a}{bar_b}{bar_c}{end}" + ) def __init__( self, @@ -259,9 +262,7 @@ def format( width: int, ) -> AnyFormattedText: text = _format_timedelta(progress.time_elapsed).rjust(width) - return self.template.format( - time_elapsed=text - ) + return self.template.format(time_elapsed=text) def get_width(self, progress_bar: ProgressBar) -> AnyDimension: all_values = [ @@ -347,9 +348,7 @@ def format( width: int, ) -> AnyFormattedText: index = int(time.time() * 3) % len(self.characters) - return self.template.format( - self.characters[index] - ) + return self.template.format(self.characters[index]) def get_width(self, progress_bar: ProgressBar) -> AnyDimension: return D.exact(1) diff --git a/src/prompt_toolkit/shortcuts/prompt.py b/src/prompt_toolkit/shortcuts/prompt.py index 7274b5f03e..115d890075 100644 --- a/src/prompt_toolkit/shortcuts/prompt.py +++ b/src/prompt_toolkit/shortcuts/prompt.py @@ -24,6 +24,7 @@ s = PromptSession() result = s.prompt('Say something: ') """ + from __future__ import annotations from asyncio import get_running_loop diff --git a/src/prompt_toolkit/styles/__init__.py b/src/prompt_toolkit/styles/__init__.py index 23f61bb0f6..39e97cac8e 100644 --- a/src/prompt_toolkit/styles/__init__.py +++ b/src/prompt_toolkit/styles/__init__.py @@ -1,6 +1,7 @@ """ Styling for prompt_toolkit applications. """ + from __future__ import annotations from .base import ( diff --git a/src/prompt_toolkit/styles/base.py b/src/prompt_toolkit/styles/base.py index b50f3b0ea4..06572210a9 100644 --- a/src/prompt_toolkit/styles/base.py +++ b/src/prompt_toolkit/styles/base.py @@ -1,6 +1,7 @@ """ The base classes for the styling. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod, abstractproperty diff --git a/src/prompt_toolkit/styles/defaults.py b/src/prompt_toolkit/styles/defaults.py index 75b8dd21a6..2faba94378 100644 --- a/src/prompt_toolkit/styles/defaults.py +++ b/src/prompt_toolkit/styles/defaults.py @@ -1,6 +1,7 @@ """ The default styling. """ + from __future__ import annotations from prompt_toolkit.cache import memoized diff --git a/src/prompt_toolkit/styles/named_colors.py b/src/prompt_toolkit/styles/named_colors.py index 0395c8bc59..b6290a4e8f 100644 --- a/src/prompt_toolkit/styles/named_colors.py +++ b/src/prompt_toolkit/styles/named_colors.py @@ -2,6 +2,7 @@ All modern web browsers support these 140 color names. Taken from: https://www.w3schools.com/colors/colors_names.asp """ + from __future__ import annotations __all__ = [ diff --git a/src/prompt_toolkit/styles/pygments.py b/src/prompt_toolkit/styles/pygments.py index 3e101f1d36..c0f603108f 100644 --- a/src/prompt_toolkit/styles/pygments.py +++ b/src/prompt_toolkit/styles/pygments.py @@ -6,6 +6,7 @@ from pygments.styles.tango import TangoStyle style = style_from_pygments_cls(pygments_style_cls=TangoStyle) """ + from __future__ import annotations from typing import TYPE_CHECKING diff --git a/src/prompt_toolkit/styles/style.py b/src/prompt_toolkit/styles/style.py index 1abee0f53b..fc8b31bd0a 100644 --- a/src/prompt_toolkit/styles/style.py +++ b/src/prompt_toolkit/styles/style.py @@ -1,6 +1,7 @@ """ Tool for creating styles from a dictionary. """ + from __future__ import annotations import itertools @@ -72,7 +73,7 @@ def parse_color(text: str) -> str: elif text in ("", "default"): return text - raise ValueError("Wrong color format %r" % text) + raise ValueError(f"Wrong color format {text!r}") # Attributes, when they are not filled in by a style. None means that we take diff --git a/src/prompt_toolkit/styles/style_transformation.py b/src/prompt_toolkit/styles/style_transformation.py index fbb5a639ab..e8d5b0a89f 100644 --- a/src/prompt_toolkit/styles/style_transformation.py +++ b/src/prompt_toolkit/styles/style_transformation.py @@ -9,6 +9,7 @@ style strings are turned into `Attrs` objects that represent the actual formatting. """ + from __future__ import annotations from abc import ABCMeta, abstractmethod diff --git a/src/prompt_toolkit/token.py b/src/prompt_toolkit/token.py index a2c80e54c5..e97893de67 100644 --- a/src/prompt_toolkit/token.py +++ b/src/prompt_toolkit/token.py @@ -1,5 +1,4 @@ -""" -""" +""" """ from __future__ import annotations diff --git a/src/prompt_toolkit/validation.py b/src/prompt_toolkit/validation.py index 127445e86e..2b35d1fcc9 100644 --- a/src/prompt_toolkit/validation.py +++ b/src/prompt_toolkit/validation.py @@ -2,6 +2,7 @@ Input validation for a `Buffer`. (Validators will be called before accepting input.) """ + from __future__ import annotations from abc import ABCMeta, abstractmethod @@ -36,11 +37,7 @@ def __init__(self, cursor_position: int = 0, message: str = "") -> None: self.message = message def __repr__(self) -> str: - return "{}(cursor_position={!r}, message={!r})".format( - self.__class__.__name__, - self.cursor_position, - self.message, - ) + return f"{self.__class__.__name__}(cursor_position={self.cursor_position!r}, message={self.message!r})" class Validator(metaclass=ABCMeta): diff --git a/src/prompt_toolkit/widgets/__init__.py b/src/prompt_toolkit/widgets/__init__.py index 9d1d4e3dee..53cc3e1394 100644 --- a/src/prompt_toolkit/widgets/__init__.py +++ b/src/prompt_toolkit/widgets/__init__.py @@ -6,6 +6,7 @@ Most of these widgets implement the ``__pt_container__`` method, which makes it possible to embed these in the layout like any other container. """ + from __future__ import annotations from .base import ( diff --git a/src/prompt_toolkit/widgets/base.py b/src/prompt_toolkit/widgets/base.py index f36a545755..709b7a9499 100644 --- a/src/prompt_toolkit/widgets/base.py +++ b/src/prompt_toolkit/widgets/base.py @@ -12,6 +12,7 @@ guarantees are made yet). The public API in `prompt_toolkit.shortcuts.dialogs` on the other hand is considered stable. """ + from __future__ import annotations from functools import partial diff --git a/src/prompt_toolkit/widgets/dialogs.py b/src/prompt_toolkit/widgets/dialogs.py index c47c15b4f9..5f5f17026d 100644 --- a/src/prompt_toolkit/widgets/dialogs.py +++ b/src/prompt_toolkit/widgets/dialogs.py @@ -1,6 +1,7 @@ """ Collection of reusable components for building full screen applications. """ + from __future__ import annotations from typing import Sequence diff --git a/src/prompt_toolkit/widgets/toolbars.py b/src/prompt_toolkit/widgets/toolbars.py index deddf15423..c5deffc58c 100644 --- a/src/prompt_toolkit/widgets/toolbars.py +++ b/src/prompt_toolkit/widgets/toolbars.py @@ -352,11 +352,7 @@ def get_formatted_text() -> StyleAndTextTuples: ) if show_position: - text = "{} (line={} column={})".format( - buff.validation_error.message, - row + 1, - column + 1, - ) + text = f"{buff.validation_error.message} (line={row + 1} column={column + 1})" else: text = buff.validation_error.message diff --git a/tests/test_cli.py b/tests/test_cli.py index 3a16e9fbd3..c155325f98 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2,6 +2,7 @@ These are almost end-to-end tests. They create a Prompt, feed it with some input and check the result. """ + from __future__ import annotations from functools import partial diff --git a/tests/test_print_formatted_text.py b/tests/test_print_formatted_text.py index 26c7265151..7d0e99a335 100644 --- a/tests/test_print_formatted_text.py +++ b/tests/test_print_formatted_text.py @@ -1,6 +1,7 @@ """ Test the `print` function. """ + from __future__ import annotations import pytest diff --git a/tests/test_regular_languages.py b/tests/test_regular_languages.py index deef6b80b4..3d55dbc514 100644 --- a/tests/test_regular_languages.py +++ b/tests/test_regular_languages.py @@ -78,13 +78,13 @@ def test_prefix(): def test_completer(): class completer1(Completer): def get_completions(self, document, complete_event): - yield Completion("before-%s-after" % document.text, -len(document.text)) - yield Completion("before-%s-after-B" % document.text, -len(document.text)) + yield Completion(f"before-{document.text}-after", -len(document.text)) + yield Completion(f"before-{document.text}-after-B", -len(document.text)) class completer2(Completer): def get_completions(self, document, complete_event): - yield Completion("before2-%s-after2" % document.text, -len(document.text)) - yield Completion("before2-%s-after2-B" % document.text, -len(document.text)) + yield Completion(f"before2-{document.text}-after2", -len(document.text)) + yield Completion(f"before2-{document.text}-after2-B", -len(document.text)) # Create grammar. "var1" + "whitespace" + "var2" g = compile(r"(?P[a-z]*) \s+ (?P[a-z]*)") diff --git a/tools/debug_input_cross_platform.py b/tools/debug_input_cross_platform.py index 55f61907ba..d87cfcc03d 100755 --- a/tools/debug_input_cross_platform.py +++ b/tools/debug_input_cross_platform.py @@ -5,6 +5,7 @@ Works on both Windows and Posix. """ + import asyncio from prompt_toolkit.input import create_input diff --git a/tools/debug_vt100_input.py b/tools/debug_vt100_input.py index d3660b9a37..b74c06fb84 100755 --- a/tools/debug_vt100_input.py +++ b/tools/debug_vt100_input.py @@ -5,6 +5,7 @@ (This does not use the `Input` implementation, but only the `Vt100Parser`.) """ + import sys from prompt_toolkit.input.vt100 import raw_mode From a9d413f9ac22d2e439bbda77c54adfaa9ed5b750 Mon Sep 17 00:00:00 2001 From: Jonathan Slenders Date: Wed, 15 May 2024 10:42:32 +0000 Subject: [PATCH 2/2] Typing fix in FileHistory. --- src/prompt_toolkit/history.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/prompt_toolkit/history.py b/src/prompt_toolkit/history.py index c82358de2e..2d497a0209 100644 --- a/src/prompt_toolkit/history.py +++ b/src/prompt_toolkit/history.py @@ -15,7 +15,7 @@ import threading from abc import ABCMeta, abstractmethod from asyncio import get_running_loop -from typing import AsyncGenerator, Iterable, Sequence +from typing import AsyncGenerator, Iterable, Sequence, Union __all__ = [ "History", @@ -255,12 +255,15 @@ def append_string(self, string: str) -> None: pass +_StrOrBytesPath = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"] + + class FileHistory(History): """ :class:`.History` class that stores all strings in a file. """ - def __init__(self, filename: str | os.PathLike) -> None: + def __init__(self, filename: _StrOrBytesPath) -> None: self.filename = filename super().__init__()