id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
172,067 | from __future__ import annotations
from prompt_toolkit.filters import emacs_mode, has_selection, vi_navigation_mode
from ..key_bindings import KeyBindings, KeyBindingsBase, merge_key_bindings
from .named_commands import get_by_name
def load_emacs_open_in_editor_bindings() -> KeyBindings:
"""
Pressing C-X C-E will open the buffer in an external editor.
"""
key_bindings = KeyBindings()
key_bindings.add("c-x", "c-e", filter=emacs_mode & ~has_selection)(
get_by_name("edit-and-execute-command")
)
return key_bindings
def load_vi_open_in_editor_bindings() -> KeyBindings:
"""
Pressing 'v' in navigation mode will open the buffer in an external editor.
"""
key_bindings = KeyBindings()
key_bindings.add("v", filter=vi_navigation_mode)(
get_by_name("edit-and-execute-command")
)
return key_bindings
class KeyBindingsBase(metaclass=ABCMeta):
"""
Interface for a KeyBindings.
"""
def _version(self) -> Hashable:
"""
For cache invalidation. - This should increase every time that
something changes.
"""
return 0
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle these keys.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
return []
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
return []
def bindings(self) -> list[Binding]:
"""
List of `Binding` objects.
(These need to be exposed, so that `KeyBindings` objects can be merged
together.)
"""
return []
# `add` and `remove` don't have to be part of this interface.
def merge_key_bindings(bindings: Sequence[KeyBindingsBase]) -> _MergedKeyBindings:
"""
Merge multiple :class:`.Keybinding` objects together.
Usage::
bindings = merge_key_bindings([bindings1, bindings2, ...])
"""
return _MergedKeyBindings(bindings)
The provided code snippet includes necessary dependencies for implementing the `load_open_in_editor_bindings` function. Write a Python function `def load_open_in_editor_bindings() -> KeyBindingsBase` to solve the following problem:
Load both the Vi and emacs key bindings for handling edit-and-execute-command.
Here is the function:
def load_open_in_editor_bindings() -> KeyBindingsBase:
"""
Load both the Vi and emacs key bindings for handling edit-and-execute-command.
"""
return merge_key_bindings(
[
load_emacs_open_in_editor_bindings(),
load_vi_open_in_editor_bindings(),
]
) | Load both the Vi and emacs key bindings for handling edit-and-execute-command. |
172,068 | from __future__ import annotations
from prompt_toolkit.filters import buffer_has_focus, emacs_mode, vi_mode
from prompt_toolkit.key_binding.key_bindings import (
ConditionalKeyBindings,
KeyBindings,
KeyBindingsBase,
merge_key_bindings,
)
from .scroll import (
scroll_backward,
scroll_forward,
scroll_half_page_down,
scroll_half_page_up,
scroll_one_line_down,
scroll_one_line_up,
scroll_page_down,
scroll_page_up,
)
def load_emacs_page_navigation_bindings() -> KeyBindingsBase:
"""
Key bindings, for scrolling up and down through pages.
This are separate bindings, because GNU readline doesn't have them.
"""
key_bindings = KeyBindings()
handle = key_bindings.add
handle("c-v")(scroll_page_down)
handle("pagedown")(scroll_page_down)
handle("escape", "v")(scroll_page_up)
handle("pageup")(scroll_page_up)
return ConditionalKeyBindings(key_bindings, emacs_mode)
def load_vi_page_navigation_bindings() -> KeyBindingsBase:
"""
Key bindings, for scrolling up and down through pages.
This are separate bindings, because GNU readline doesn't have them.
"""
key_bindings = KeyBindings()
handle = key_bindings.add
handle("c-f")(scroll_forward)
handle("c-b")(scroll_backward)
handle("c-d")(scroll_half_page_down)
handle("c-u")(scroll_half_page_up)
handle("c-e")(scroll_one_line_down)
handle("c-y")(scroll_one_line_up)
handle("pagedown")(scroll_page_down)
handle("pageup")(scroll_page_up)
return ConditionalKeyBindings(key_bindings, vi_mode)
class KeyBindingsBase(metaclass=ABCMeta):
"""
Interface for a KeyBindings.
"""
def _version(self) -> Hashable:
"""
For cache invalidation. - This should increase every time that
something changes.
"""
return 0
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle these keys.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
return []
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
return []
def bindings(self) -> list[Binding]:
"""
List of `Binding` objects.
(These need to be exposed, so that `KeyBindings` objects can be merged
together.)
"""
return []
# `add` and `remove` don't have to be part of this interface.
class ConditionalKeyBindings(_Proxy):
"""
Wraps around a `KeyBindings`. Disable/enable all the key bindings according to
the given (additional) filter.::
def setting_is_true():
return True # or False
registry = ConditionalKeyBindings(key_bindings, setting_is_true)
When new key bindings are added to this object. They are also
enable/disabled according to the given `filter`.
:param registries: List of :class:`.KeyBindings` objects.
:param filter: :class:`~prompt_toolkit.filters.Filter` object.
"""
def __init__(
self, key_bindings: KeyBindingsBase, filter: FilterOrBool = True
) -> None:
_Proxy.__init__(self)
self.key_bindings = key_bindings
self.filter = to_filter(filter)
def _update_cache(self) -> None:
"If the original key bindings was changed. Update our copy version."
expected_version = self.key_bindings._version
if self._last_version != expected_version:
bindings2 = KeyBindings()
# Copy all bindings from `self.key_bindings`, adding our condition.
for b in self.key_bindings.bindings:
bindings2.bindings.append(
Binding(
keys=b.keys,
handler=b.handler,
filter=self.filter & b.filter,
eager=b.eager,
is_global=b.is_global,
save_before=b.save_before,
record_in_macro=b.record_in_macro,
)
)
self._bindings2 = bindings2
self._last_version = expected_version
def merge_key_bindings(bindings: Sequence[KeyBindingsBase]) -> _MergedKeyBindings:
"""
Merge multiple :class:`.Keybinding` objects together.
Usage::
bindings = merge_key_bindings([bindings1, bindings2, ...])
"""
return _MergedKeyBindings(bindings)
The provided code snippet includes necessary dependencies for implementing the `load_page_navigation_bindings` function. Write a Python function `def load_page_navigation_bindings() -> KeyBindingsBase` to solve the following problem:
Load both the Vi and Emacs bindings for page navigation.
Here is the function:
def load_page_navigation_bindings() -> KeyBindingsBase:
"""
Load both the Vi and Emacs bindings for page navigation.
"""
# Only enable when a `Buffer` is focused, otherwise, we would catch keys
# when another widget is focused (like for instance `c-d` in a
# ptterm.Terminal).
return ConditionalKeyBindings(
merge_key_bindings(
[
load_emacs_page_navigation_bindings(),
load_vi_page_navigation_bindings(),
]
),
buffer_has_focus,
) | Load both the Vi and Emacs bindings for page navigation. |
172,069 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
_Handler = Callable[[KeyPressEvent], None]
_T = TypeVar("_T", bound=_HandlerOrBinding)
_readline_commands: dict[str, Binding] = {}
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
class Binding:
"""
Key binding: (key sequence + handler + filter).
(Immutable binding class.)
:param record_in_macro: When True, don't record this key binding when a
macro is recorded.
"""
def __init__(
self,
keys: tuple[Keys | str, ...],
handler: KeyHandlerCallable,
filter: FilterOrBool = True,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
record_in_macro: FilterOrBool = True,
) -> None:
self.keys = keys
self.handler = handler
self.filter = to_filter(filter)
self.eager = to_filter(eager)
self.is_global = to_filter(is_global)
self.save_before = save_before
self.record_in_macro = to_filter(record_in_macro)
def call(self, event: KeyPressEvent) -> None:
result = self.handler(event)
# If the handler is a coroutine, create an asyncio task.
if isawaitable(result):
awaitable = cast(Awaitable["NotImplementedOrNone"], result)
async def bg_task() -> None:
result = await awaitable
if result != NotImplemented:
event.app.invalidate()
event.app.create_background_task(bg_task())
elif result != NotImplemented:
event.app.invalidate()
def __repr__(self) -> str:
return "{}(keys={!r}, handler={!r})".format(
self.__class__.__name__,
self.keys,
self.handler,
)
def key_binding(
filter: FilterOrBool = True,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda event: True),
record_in_macro: FilterOrBool = True,
) -> Callable[[KeyHandlerCallable], Binding]:
"""
Decorator that turn a function into a `Binding` object. This can be added
to a `KeyBindings` object when a key binding is assigned.
"""
assert save_before is None or callable(save_before)
filter = to_filter(filter)
eager = to_filter(eager)
is_global = to_filter(is_global)
save_before = save_before
record_in_macro = to_filter(record_in_macro)
keys = ()
def decorator(function: KeyHandlerCallable) -> Binding:
return Binding(
keys,
function,
filter=filter,
eager=eager,
is_global=is_global,
save_before=save_before,
record_in_macro=record_in_macro,
)
return decorator
The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(name: str) -> Callable[[_T], _T]` to solve the following problem:
Store handler in the `_readline_commands` dictionary.
Here is the function:
def register(name: str) -> Callable[[_T], _T]:
"""
Store handler in the `_readline_commands` dictionary.
"""
def decorator(handler: _T) -> _T:
"`handler` is a callable or Binding."
if isinstance(handler, Binding):
_readline_commands[name] = handler
else:
_readline_commands[name] = key_binding()(cast(_Handler, handler))
return handler
return decorator | Store handler in the `_readline_commands` dictionary. |
172,070 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `beginning_of_buffer` function. Write a Python function `def beginning_of_buffer(event: E) -> None` to solve the following problem:
Move to the start of the buffer.
Here is the function:
def beginning_of_buffer(event: E) -> None:
"""
Move to the start of the buffer.
"""
buff = event.current_buffer
buff.cursor_position = 0 | Move to the start of the buffer. |
172,071 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `end_of_buffer` function. Write a Python function `def end_of_buffer(event: E) -> None` to solve the following problem:
Move to the end of the buffer.
Here is the function:
def end_of_buffer(event: E) -> None:
"""
Move to the end of the buffer.
"""
buff = event.current_buffer
buff.cursor_position = len(buff.text) | Move to the end of the buffer. |
172,072 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `beginning_of_line` function. Write a Python function `def beginning_of_line(event: E) -> None` to solve the following problem:
Move to the start of the current line.
Here is the function:
def beginning_of_line(event: E) -> None:
"""
Move to the start of the current line.
"""
buff = event.current_buffer
buff.cursor_position += buff.document.get_start_of_line_position(
after_whitespace=False
) | Move to the start of the current line. |
172,073 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `backward_word` function. Write a Python function `def backward_word(event: E) -> None` to solve the following problem:
Move back to the start of the current or previous word. Words are composed of letters and digits.
Here is the function:
def backward_word(event: E) -> None:
"""
Move back to the start of the current or previous word. Words are composed
of letters and digits.
"""
buff = event.current_buffer
pos = buff.document.find_previous_word_beginning(count=event.arg)
if pos:
buff.cursor_position += pos | Move back to the start of the current or previous word. Words are composed of letters and digits. |
172,074 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `clear_screen` function. Write a Python function `def clear_screen(event: E) -> None` to solve the following problem:
Clear the screen and redraw everything at the top of the screen.
Here is the function:
def clear_screen(event: E) -> None:
"""
Clear the screen and redraw everything at the top of the screen.
"""
event.app.renderer.clear() | Clear the screen and redraw everything at the top of the screen. |
172,075 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `redraw_current_line` function. Write a Python function `def redraw_current_line(event: E) -> None` to solve the following problem:
Refresh the current line. (Readline defines this command, but prompt-toolkit doesn't have it.)
Here is the function:
def redraw_current_line(event: E) -> None:
"""
Refresh the current line.
(Readline defines this command, but prompt-toolkit doesn't have it.)
"""
pass | Refresh the current line. (Readline defines this command, but prompt-toolkit doesn't have it.) |
172,076 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `accept_line` function. Write a Python function `def accept_line(event: E) -> None` to solve the following problem:
Accept the line regardless of where the cursor is.
Here is the function:
def accept_line(event: E) -> None:
"""
Accept the line regardless of where the cursor is.
"""
event.current_buffer.validate_and_handle() | Accept the line regardless of where the cursor is. |
172,077 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `previous_history` function. Write a Python function `def previous_history(event: E) -> None` to solve the following problem:
Move `back` through the history list, fetching the previous command.
Here is the function:
def previous_history(event: E) -> None:
"""
Move `back` through the history list, fetching the previous command.
"""
event.current_buffer.history_backward(count=event.arg) | Move `back` through the history list, fetching the previous command. |
172,078 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `next_history` function. Write a Python function `def next_history(event: E) -> None` to solve the following problem:
Move `forward` through the history list, fetching the next command.
Here is the function:
def next_history(event: E) -> None:
"""
Move `forward` through the history list, fetching the next command.
"""
event.current_buffer.history_forward(count=event.arg) | Move `forward` through the history list, fetching the next command. |
172,079 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `beginning_of_history` function. Write a Python function `def beginning_of_history(event: E) -> None` to solve the following problem:
Move to the first line in the history.
Here is the function:
def beginning_of_history(event: E) -> None:
"""
Move to the first line in the history.
"""
event.current_buffer.go_to_history(0) | Move to the first line in the history. |
172,080 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `end_of_history` function. Write a Python function `def end_of_history(event: E) -> None` to solve the following problem:
Move to the end of the input history, i.e., the line currently being entered.
Here is the function:
def end_of_history(event: E) -> None:
"""
Move to the end of the input history, i.e., the line currently being entered.
"""
event.current_buffer.history_forward(count=10**100)
buff = event.current_buffer
buff.go_to_history(len(buff._working_lines) - 1) | Move to the end of the input history, i.e., the line currently being entered. |
172,081 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class BufferControl(UIControl):
"""
Control for visualising the content of a :class:`.Buffer`.
:param buffer: The :class:`.Buffer` object to be displayed.
:param input_processors: A list of
:class:`~prompt_toolkit.layout.processors.Processor` objects.
:param include_default_input_processors: When True, include the default
processors for highlighting of selection, search and displaying of
multiple cursors.
:param lexer: :class:`.Lexer` instance for syntax highlighting.
:param preview_search: `bool` or :class:`.Filter`: Show search while
typing. When this is `True`, probably you want to add a
``HighlightIncrementalSearchProcessor`` as well. Otherwise only the
cursor position will move, but the text won't be highlighted.
:param focusable: `bool` or :class:`.Filter`: Tell whether this control is focusable.
:param focus_on_click: Focus this buffer when it's click, but not yet focused.
:param key_bindings: a :class:`.KeyBindings` object.
"""
def __init__(
self,
buffer: Buffer | None = None,
input_processors: list[Processor] | None = None,
include_default_input_processors: bool = True,
lexer: Lexer | None = None,
preview_search: FilterOrBool = False,
focusable: FilterOrBool = True,
search_buffer_control: (
None | SearchBufferControl | Callable[[], SearchBufferControl]
) = None,
menu_position: Callable[[], int | None] | None = None,
focus_on_click: FilterOrBool = False,
key_bindings: KeyBindingsBase | None = None,
):
self.input_processors = input_processors
self.include_default_input_processors = include_default_input_processors
self.default_input_processors = [
HighlightSearchProcessor(),
HighlightIncrementalSearchProcessor(),
HighlightSelectionProcessor(),
DisplayMultipleCursors(),
]
self.preview_search = to_filter(preview_search)
self.focusable = to_filter(focusable)
self.focus_on_click = to_filter(focus_on_click)
self.buffer = buffer or Buffer()
self.menu_position = menu_position
self.lexer = lexer or SimpleLexer()
self.key_bindings = key_bindings
self._search_buffer_control = search_buffer_control
#: Cache for the lexer.
#: Often, due to cursor movement, undo/redo and window resizing
#: operations, it happens that a short time, the same document has to be
#: lexed. This is a fairly easy way to cache such an expensive operation.
self._fragment_cache: SimpleCache[
Hashable, Callable[[int], StyleAndTextTuples]
] = SimpleCache(maxsize=8)
self._last_click_timestamp: float | None = None
self._last_get_processed_line: Callable[[int], _ProcessedLine] | None = None
def __repr__(self) -> str:
return f"<{self.__class__.__name__} buffer={self.buffer!r} at {id(self)!r}>"
def search_buffer_control(self) -> SearchBufferControl | None:
result: SearchBufferControl | None
if callable(self._search_buffer_control):
result = self._search_buffer_control()
else:
result = self._search_buffer_control
assert result is None or isinstance(result, SearchBufferControl)
return result
def search_buffer(self) -> Buffer | None:
control = self.search_buffer_control
if control is not None:
return control.buffer
return None
def search_state(self) -> SearchState:
"""
Return the `SearchState` for searching this `BufferControl`. This is
always associated with the search control. If one search bar is used
for searching multiple `BufferControls`, then they share the same
`SearchState`.
"""
search_buffer_control = self.search_buffer_control
if search_buffer_control:
return search_buffer_control.searcher_search_state
else:
return SearchState()
def is_focusable(self) -> bool:
return self.focusable()
def preferred_width(self, max_available_width: int) -> int | None:
"""
This should return the preferred width.
Note: We don't specify a preferred width according to the content,
because it would be too expensive. Calculating the preferred
width can be done by calculating the longest line, but this would
require applying all the processors to each line. This is
unfeasible for a larger document, and doing it for small
documents only would result in inconsistent behaviour.
"""
return None
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int | None:
# Calculate the content height, if it was drawn on a screen with the
# given width.
height = 0
content = self.create_content(width, height=1) # Pass a dummy '1' as height.
# When line wrapping is off, the height should be equal to the amount
# of lines.
if not wrap_lines:
return content.line_count
# When the number of lines exceeds the max_available_height, just
# return max_available_height. No need to calculate anything.
if content.line_count >= max_available_height:
return max_available_height
for i in range(content.line_count):
height += content.get_height_for_line(i, width, get_line_prefix)
if height >= max_available_height:
return max_available_height
return height
def _get_formatted_text_for_line_func(
self, document: Document
) -> Callable[[int], StyleAndTextTuples]:
"""
Create a function that returns the fragments for a given line.
"""
# Cache using `document.text`.
def get_formatted_text_for_line() -> Callable[[int], StyleAndTextTuples]:
return self.lexer.lex_document(document)
key = (document.text, self.lexer.invalidation_hash())
return self._fragment_cache.get(key, get_formatted_text_for_line)
def _create_get_processed_line_func(
self, document: Document, width: int, height: int
) -> Callable[[int], _ProcessedLine]:
"""
Create a function that takes a line number of the current document and
returns a _ProcessedLine(processed_fragments, source_to_display, display_to_source)
tuple.
"""
# Merge all input processors together.
input_processors = self.input_processors or []
if self.include_default_input_processors:
input_processors = self.default_input_processors + input_processors
merged_processor = merge_processors(input_processors)
def transform(lineno: int, fragments: StyleAndTextTuples) -> _ProcessedLine:
"Transform the fragments for a given line number."
# Get cursor position at this line.
def source_to_display(i: int) -> int:
"""X position from the buffer to the x position in the
processed fragment list. By default, we start from the 'identity'
operation."""
return i
transformation = merged_processor.apply_transformation(
TransformationInput(
self, document, lineno, source_to_display, fragments, width, height
)
)
return _ProcessedLine(
transformation.fragments,
transformation.source_to_display,
transformation.display_to_source,
)
def create_func() -> Callable[[int], _ProcessedLine]:
get_line = self._get_formatted_text_for_line_func(document)
cache: dict[int, _ProcessedLine] = {}
def get_processed_line(i: int) -> _ProcessedLine:
try:
return cache[i]
except KeyError:
processed_line = transform(i, get_line(i))
cache[i] = processed_line
return processed_line
return get_processed_line
return create_func()
def create_content(
self, width: int, height: int, preview_search: bool = False
) -> UIContent:
"""
Create a UIContent.
"""
buffer = self.buffer
# Trigger history loading of the buffer. We do this during the
# rendering of the UI here, because it needs to happen when an
# `Application` with its event loop is running. During the rendering of
# the buffer control is the earliest place we can achieve this, where
# we're sure the right event loop is active, and don't require user
# interaction (like in a key binding).
buffer.load_history_if_not_yet_loaded()
# Get the document to be shown. If we are currently searching (the
# search buffer has focus, and the preview_search filter is enabled),
# then use the search document, which has possibly a different
# text/cursor position.)
search_control = self.search_buffer_control
preview_now = preview_search or bool(
# Only if this feature is enabled.
self.preview_search()
and
# And something was typed in the associated search field.
search_control
and search_control.buffer.text
and
# And we are searching in this control. (Many controls can point to
# the same search field, like in Pyvim.)
get_app().layout.search_target_buffer_control == self
)
if preview_now and search_control is not None:
ss = self.search_state
document = buffer.document_for_search(
SearchState(
text=search_control.buffer.text,
direction=ss.direction,
ignore_case=ss.ignore_case,
)
)
else:
document = buffer.document
get_processed_line = self._create_get_processed_line_func(
document, width, height
)
self._last_get_processed_line = get_processed_line
def translate_rowcol(row: int, col: int) -> Point:
"Return the content column for this coordinate."
return Point(x=get_processed_line(row).source_to_display(col), y=row)
def get_line(i: int) -> StyleAndTextTuples:
"Return the fragments for a given line number."
fragments = get_processed_line(i).fragments
# Add a space at the end, because that is a possible cursor
# position. (When inserting after the input.) We should do this on
# all the lines, not just the line containing the cursor. (Because
# otherwise, line wrapping/scrolling could change when moving the
# cursor around.)
fragments = fragments + [("", " ")]
return fragments
content = UIContent(
get_line=get_line,
line_count=document.line_count,
cursor_position=translate_rowcol(
document.cursor_position_row, document.cursor_position_col
),
)
# If there is an auto completion going on, use that start point for a
# pop-up menu position. (But only when this buffer has the focus --
# there is only one place for a menu, determined by the focused buffer.)
if get_app().layout.current_control == self:
menu_position = self.menu_position() if self.menu_position else None
if menu_position is not None:
assert isinstance(menu_position, int)
menu_row, menu_col = buffer.document.translate_index_to_position(
menu_position
)
content.menu_position = translate_rowcol(menu_row, menu_col)
elif buffer.complete_state:
# Position for completion menu.
# Note: We use 'min', because the original cursor position could be
# behind the input string when the actual completion is for
# some reason shorter than the text we had before. (A completion
# can change and shorten the input.)
menu_row, menu_col = buffer.document.translate_index_to_position(
min(
buffer.cursor_position,
buffer.complete_state.original_document.cursor_position,
)
)
content.menu_position = translate_rowcol(menu_row, menu_col)
else:
content.menu_position = None
return content
def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Mouse handler for this control.
"""
buffer = self.buffer
position = mouse_event.position
# Focus buffer when clicked.
if get_app().layout.current_control == self:
if self._last_get_processed_line:
processed_line = self._last_get_processed_line(position.y)
# Translate coordinates back to the cursor position of the
# original input.
xpos = processed_line.display_to_source(position.x)
index = buffer.document.translate_row_col_to_index(position.y, xpos)
# Set the cursor position.
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
buffer.exit_selection()
buffer.cursor_position = index
elif (
mouse_event.event_type == MouseEventType.MOUSE_MOVE
and mouse_event.button != MouseButton.NONE
):
# Click and drag to highlight a selection
if (
buffer.selection_state is None
and abs(buffer.cursor_position - index) > 0
):
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position = index
elif mouse_event.event_type == MouseEventType.MOUSE_UP:
# When the cursor was moved to another place, select the text.
# (The >1 is actually a small but acceptable workaround for
# selecting text in Vi navigation mode. In navigation mode,
# the cursor can never be after the text, so the cursor
# will be repositioned automatically.)
if abs(buffer.cursor_position - index) > 1:
if buffer.selection_state is None:
buffer.start_selection(
selection_type=SelectionType.CHARACTERS
)
buffer.cursor_position = index
# Select word around cursor on double click.
# Two MOUSE_UP events in a short timespan are considered a double click.
double_click = (
self._last_click_timestamp
and time.time() - self._last_click_timestamp < 0.3
)
self._last_click_timestamp = time.time()
if double_click:
start, end = buffer.document.find_boundaries_of_current_word()
buffer.cursor_position += start
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position += end - start
else:
# Don't handle scroll events here.
return NotImplemented
# Not focused, but focusing on click events.
else:
if (
self.focus_on_click()
and mouse_event.event_type == MouseEventType.MOUSE_UP
):
# Focus happens on mouseup. (If we did this on mousedown, the
# up event will be received at the point where this widget is
# focused and be handled anyway.)
get_app().layout.current_control = self
else:
return NotImplemented
return None
def move_cursor_down(self) -> None:
b = self.buffer
b.cursor_position += b.document.get_cursor_down_position()
def move_cursor_up(self) -> None:
b = self.buffer
b.cursor_position += b.document.get_cursor_up_position()
def get_key_bindings(self) -> KeyBindingsBase | None:
"""
When additional key bindings are given. Return these.
"""
return self.key_bindings
def get_invalidate_events(self) -> Iterable[Event[object]]:
"""
Return the Window invalidate events.
"""
# Whenever the buffer changes, the UI has to be updated.
yield self.buffer.on_text_changed
yield self.buffer.on_cursor_position_changed
yield self.buffer.on_completions_changed
yield self.buffer.on_suggestion_set
class SearchDirection(Enum):
FORWARD = "FORWARD"
BACKWARD = "BACKWARD"
The provided code snippet includes necessary dependencies for implementing the `reverse_search_history` function. Write a Python function `def reverse_search_history(event: E) -> None` to solve the following problem:
Search backward starting at the current line and moving `up` through the history as necessary. This is an incremental search.
Here is the function:
def reverse_search_history(event: E) -> None:
"""
Search backward starting at the current line and moving `up` through
the history as necessary. This is an incremental search.
"""
control = event.app.layout.current_control
if isinstance(control, BufferControl) and control.search_buffer_control:
event.app.current_search_state.direction = SearchDirection.BACKWARD
event.app.layout.current_control = control.search_buffer_control | Search backward starting at the current line and moving `up` through the history as necessary. This is an incremental search. |
172,082 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `end_of_file` function. Write a Python function `def end_of_file(event: E) -> None` to solve the following problem:
Exit.
Here is the function:
def end_of_file(event: E) -> None:
"""
Exit.
"""
event.app.exit() | Exit. |
172,083 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `delete_char` function. Write a Python function `def delete_char(event: E) -> None` to solve the following problem:
Delete character before the cursor.
Here is the function:
def delete_char(event: E) -> None:
"""
Delete character before the cursor.
"""
deleted = event.current_buffer.delete(count=event.arg)
if not deleted:
event.app.output.bell() | Delete character before the cursor. |
172,084 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `self_insert` function. Write a Python function `def self_insert(event: E) -> None` to solve the following problem:
Insert yourself.
Here is the function:
def self_insert(event: E) -> None:
"""
Insert yourself.
"""
event.current_buffer.insert_text(event.data * event.arg) | Insert yourself. |
172,085 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `transpose_chars` function. Write a Python function `def transpose_chars(event: E) -> None` to solve the following problem:
Emulate Emacs transpose-char behavior: at the beginning of the buffer, do nothing. At the end of a line or buffer, swap the characters before the cursor. Otherwise, move the cursor right, and then swap the characters before the cursor.
Here is the function:
def transpose_chars(event: E) -> None:
"""
Emulate Emacs transpose-char behavior: at the beginning of the buffer,
do nothing. At the end of a line or buffer, swap the characters before
the cursor. Otherwise, move the cursor right, and then swap the
characters before the cursor.
"""
b = event.current_buffer
p = b.cursor_position
if p == 0:
return
elif p == len(b.text) or b.text[p] == "\n":
b.swap_characters_before_cursor()
else:
b.cursor_position += b.document.get_cursor_right_position()
b.swap_characters_before_cursor() | Emulate Emacs transpose-char behavior: at the beginning of the buffer, do nothing. At the end of a line or buffer, swap the characters before the cursor. Otherwise, move the cursor right, and then swap the characters before the cursor. |
172,086 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `uppercase_word` function. Write a Python function `def uppercase_word(event: E) -> None` to solve the following problem:
Uppercase the current (or following) word.
Here is the function:
def uppercase_word(event: E) -> None:
"""
Uppercase the current (or following) word.
"""
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.upper(), overwrite=True) | Uppercase the current (or following) word. |
172,087 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `downcase_word` function. Write a Python function `def downcase_word(event: E) -> None` to solve the following problem:
Lowercase the current (or following) word.
Here is the function:
def downcase_word(event: E) -> None:
"""
Lowercase the current (or following) word.
"""
buff = event.current_buffer
for i in range(event.arg): # XXX: not DRY: see meta_c and meta_u!!
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.lower(), overwrite=True) | Lowercase the current (or following) word. |
172,088 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `capitalize_word` function. Write a Python function `def capitalize_word(event: E) -> None` to solve the following problem:
Capitalize the current (or following) word.
Here is the function:
def capitalize_word(event: E) -> None:
"""
Capitalize the current (or following) word.
"""
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.title(), overwrite=True) | Capitalize the current (or following) word. |
172,089 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `kill_line` function. Write a Python function `def kill_line(event: E) -> None` to solve the following problem:
Kill the text from the cursor to the end of the line. If we are at the end of the line, this should remove the newline. (That way, it is possible to delete multiple lines by executing this command multiple times.)
Here is the function:
def kill_line(event: E) -> None:
"""
Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.)
"""
buff = event.current_buffer
if event.arg < 0:
deleted = buff.delete_before_cursor(
count=-buff.document.get_start_of_line_position()
)
else:
if buff.document.current_char == "\n":
deleted = buff.delete(1)
else:
deleted = buff.delete(count=buff.document.get_end_of_line_position())
event.app.clipboard.set_text(deleted) | Kill the text from the cursor to the end of the line. If we are at the end of the line, this should remove the newline. (That way, it is possible to delete multiple lines by executing this command multiple times.) |
172,090 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `kill_word` function. Write a Python function `def kill_word(event: E) -> None` to solve the following problem:
Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word.
Here is the function:
def kill_word(event: E) -> None:
"""
Kill from point to the end of the current word, or if between words, to the
end of the next word. Word boundaries are the same as forward-word.
"""
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
deleted = buff.delete(count=pos)
if event.is_repeat:
deleted = event.app.clipboard.get_data().text + deleted
event.app.clipboard.set_text(deleted) | Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as forward-word. |
172,091 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
def unix_word_rubout(event: E, WORD: bool = True) -> None:
"""
Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW.
"""
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if pos is None:
# Nothing found? delete until the start of the document. (The
# input starts with whitespace and no words were found before the
# cursor.)
pos = -buff.cursor_position
if pos:
deleted = buff.delete_before_cursor(count=-pos)
# If the previous key press was also Control-W, concatenate deleted
# text.
if event.is_repeat:
deleted += event.app.clipboard.get_data().text
event.app.clipboard.set_text(deleted)
else:
# Nothing to delete. Bell.
event.app.output.bell()
The provided code snippet includes necessary dependencies for implementing the `backward_kill_word` function. Write a Python function `def backward_kill_word(event: E) -> None` to solve the following problem:
Kills the word before point, using "not a letter nor a digit" as a word boundary. Usually bound to M-Del or M-Backspace.
Here is the function:
def backward_kill_word(event: E) -> None:
"""
Kills the word before point, using "not a letter nor a digit" as a word boundary.
Usually bound to M-Del or M-Backspace.
"""
unix_word_rubout(event, WORD=False) | Kills the word before point, using "not a letter nor a digit" as a word boundary. Usually bound to M-Del or M-Backspace. |
172,092 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `delete_horizontal_space` function. Write a Python function `def delete_horizontal_space(event: E) -> None` to solve the following problem:
Delete all spaces and tabs around point.
Here is the function:
def delete_horizontal_space(event: E) -> None:
"""
Delete all spaces and tabs around point.
"""
buff = event.current_buffer
text_before_cursor = buff.document.text_before_cursor
text_after_cursor = buff.document.text_after_cursor
delete_before = len(text_before_cursor) - len(text_before_cursor.rstrip("\t "))
delete_after = len(text_after_cursor) - len(text_after_cursor.lstrip("\t "))
buff.delete_before_cursor(count=delete_before)
buff.delete(count=delete_after) | Delete all spaces and tabs around point. |
172,093 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `unix_line_discard` function. Write a Python function `def unix_line_discard(event: E) -> None` to solve the following problem:
Kill backward from the cursor to the beginning of the current line.
Here is the function:
def unix_line_discard(event: E) -> None:
"""
Kill backward from the cursor to the beginning of the current line.
"""
buff = event.current_buffer
if buff.document.cursor_position_col == 0 and buff.document.cursor_position > 0:
buff.delete_before_cursor(count=1)
else:
deleted = buff.delete_before_cursor(
count=-buff.document.get_start_of_line_position()
)
event.app.clipboard.set_text(deleted) | Kill backward from the cursor to the beginning of the current line. |
172,094 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class PasteMode(Enum):
EMACS = "EMACS" # Yank like emacs.
VI_AFTER = "VI_AFTER" # When pressing 'p' in Vi.
VI_BEFORE = "VI_BEFORE" # When pressing 'P' in Vi.
The provided code snippet includes necessary dependencies for implementing the `yank` function. Write a Python function `def yank(event: E) -> None` to solve the following problem:
Paste before cursor.
Here is the function:
def yank(event: E) -> None:
"""
Paste before cursor.
"""
event.current_buffer.paste_clipboard_data(
event.app.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS
) | Paste before cursor. |
172,095 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `yank_nth_arg` function. Write a Python function `def yank_nth_arg(event: E) -> None` to solve the following problem:
Insert the first argument of the previous command. With an argument, insert the nth word from the previous command (start counting at 0).
Here is the function:
def yank_nth_arg(event: E) -> None:
"""
Insert the first argument of the previous command. With an argument, insert
the nth word from the previous command (start counting at 0).
"""
n = event.arg if event.arg_present else None
event.current_buffer.yank_nth_arg(n) | Insert the first argument of the previous command. With an argument, insert the nth word from the previous command (start counting at 0). |
172,096 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `yank_last_arg` function. Write a Python function `def yank_last_arg(event: E) -> None` to solve the following problem:
Like `yank_nth_arg`, but if no argument has been given, yank the last word of each line.
Here is the function:
def yank_last_arg(event: E) -> None:
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
"""
n = event.arg if event.arg_present else None
event.current_buffer.yank_last_arg(n) | Like `yank_nth_arg`, but if no argument has been given, yank the last word of each line. |
172,097 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class PasteMode(Enum):
EMACS = "EMACS" # Yank like emacs.
VI_AFTER = "VI_AFTER" # When pressing 'p' in Vi.
VI_BEFORE = "VI_BEFORE" # When pressing 'P' in Vi.
The provided code snippet includes necessary dependencies for implementing the `yank_pop` function. Write a Python function `def yank_pop(event: E) -> None` to solve the following problem:
Rotate the kill ring, and yank the new top. Only works following yank or yank-pop.
Here is the function:
def yank_pop(event: E) -> None:
"""
Rotate the kill ring, and yank the new top. Only works following yank or
yank-pop.
"""
buff = event.current_buffer
doc_before_paste = buff.document_before_paste
clipboard = event.app.clipboard
if doc_before_paste is not None:
buff.document = doc_before_paste
clipboard.rotate()
buff.paste_clipboard_data(clipboard.get_data(), paste_mode=PasteMode.EMACS) | Rotate the kill ring, and yank the new top. Only works following yank or yank-pop. |
172,098 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
def display_completions_like_readline(event: E) -> None:
"""
Key binding handler for readline-style tab completion.
This is meant to be as similar as possible to the way how readline displays
completions.
Generate the completions immediately (blocking) and display them above the
prompt in columns.
Usage::
# Call this handler when 'Tab' has been pressed.
key_bindings.add(Keys.ControlI)(display_completions_like_readline)
"""
# Request completions.
b = event.current_buffer
if b.completer is None:
return
complete_event = CompleteEvent(completion_requested=True)
completions = list(b.completer.get_completions(b.document, complete_event))
# Calculate the common suffix.
common_suffix = get_common_complete_suffix(b.document, completions)
# One completion: insert it.
if len(completions) == 1:
b.delete_before_cursor(-completions[0].start_position)
b.insert_text(completions[0].text)
# Multiple completions with common part.
elif common_suffix:
b.insert_text(common_suffix)
# Otherwise: display all completions.
elif completions:
_display_completions_like_readline(event.app, completions)
The provided code snippet includes necessary dependencies for implementing the `complete` function. Write a Python function `def complete(event: E) -> None` to solve the following problem:
Attempt to perform completion.
Here is the function:
def complete(event: E) -> None:
"""
Attempt to perform completion.
"""
display_completions_like_readline(event) | Attempt to perform completion. |
172,099 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
def generate_completions(event: E) -> None:
r"""
Tab-completion: where the first tab completes the common suffix and the
second tab lists all the completions.
"""
b = event.current_buffer
# When already navigating through completions, select the next one.
if b.complete_state:
b.complete_next()
else:
b.start_completion(insert_common_part=True)
The provided code snippet includes necessary dependencies for implementing the `menu_complete` function. Write a Python function `def menu_complete(event: E) -> None` to solve the following problem:
Generate completions, or go to the next completion. (This is the default way of completing input in prompt_toolkit.)
Here is the function:
def menu_complete(event: E) -> None:
"""
Generate completions, or go to the next completion. (This is the default
way of completing input in prompt_toolkit.)
"""
generate_completions(event) | Generate completions, or go to the next completion. (This is the default way of completing input in prompt_toolkit.) |
172,100 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `menu_complete_backward` function. Write a Python function `def menu_complete_backward(event: E) -> None` to solve the following problem:
Move backward through the list of possible completions.
Here is the function:
def menu_complete_backward(event: E) -> None:
"""
Move backward through the list of possible completions.
"""
event.current_buffer.complete_previous() | Move backward through the list of possible completions. |
172,101 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `start_kbd_macro` function. Write a Python function `def start_kbd_macro(event: E) -> None` to solve the following problem:
Begin saving the characters typed into the current keyboard macro.
Here is the function:
def start_kbd_macro(event: E) -> None:
"""
Begin saving the characters typed into the current keyboard macro.
"""
event.app.emacs_state.start_macro() | Begin saving the characters typed into the current keyboard macro. |
172,102 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `end_kbd_macro` function. Write a Python function `def end_kbd_macro(event: E) -> None` to solve the following problem:
Stop saving the characters typed into the current keyboard macro and save the definition.
Here is the function:
def end_kbd_macro(event: E) -> None:
"""
Stop saving the characters typed into the current keyboard macro and save
the definition.
"""
event.app.emacs_state.end_macro() | Stop saving the characters typed into the current keyboard macro and save the definition. |
172,103 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `call_last_kbd_macro` function. Write a Python function `def call_last_kbd_macro(event: E) -> None` to solve the following problem:
Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. Notice that we pass `record_in_macro=False`. This ensures that the 'c-x e' key sequence doesn't appear in the recording itself. This function inserts the body of the called macro back into the KeyProcessor, so these keys will be added later on to the macro of their handlers have `record_in_macro=True`.
Here is the function:
def call_last_kbd_macro(event: E) -> None:
"""
Re-execute the last keyboard macro defined, by making the characters in the
macro appear as if typed at the keyboard.
Notice that we pass `record_in_macro=False`. This ensures that the 'c-x e'
key sequence doesn't appear in the recording itself. This function inserts
the body of the called macro back into the KeyProcessor, so these keys will
be added later on to the macro of their handlers have `record_in_macro=True`.
"""
# Insert the macro.
macro = event.app.emacs_state.macro
if macro:
event.app.key_processor.feed_multiple(macro, first=True) | Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. Notice that we pass `record_in_macro=False`. This ensures that the 'c-x e' key sequence doesn't appear in the recording itself. This function inserts the body of the called macro back into the KeyProcessor, so these keys will be added later on to the macro of their handlers have `record_in_macro=True`. |
172,104 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
def run_in_terminal(
func: Callable[[], _T], render_cli_done: bool = False, in_executor: bool = False
) -> Awaitable[_T]:
"""
Run function on the terminal above the current application or prompt.
What this does is first hiding the prompt, then running this callable
(which can safely output to the terminal), and then again rendering the
prompt which causes the output of this function to scroll above the
prompt.
``func`` is supposed to be a synchronous function. If you need an
asynchronous version of this function, use the ``in_terminal`` context
manager directly.
:param func: The callable to execute.
:param render_cli_done: When True, render the interface in the
'Done' state first, then execute the function. If False,
erase the interface first.
:param in_executor: When True, run in executor. (Use this for long
blocking functions, when you don't want to block the event loop.)
:returns: A `Future`.
"""
async def run() -> _T:
async with in_terminal(render_cli_done=render_cli_done):
if in_executor:
return await run_in_executor_with_context(func)
else:
return func()
return ensure_future(run())
The provided code snippet includes necessary dependencies for implementing the `print_last_kbd_macro` function. Write a Python function `def print_last_kbd_macro(event: E) -> None` to solve the following problem:
Print the last keyboard macro.
Here is the function:
def print_last_kbd_macro(event: E) -> None:
"""
Print the last keyboard macro.
"""
# TODO: Make the format suitable for the inputrc file.
def print_macro() -> None:
macro = event.app.emacs_state.macro
if macro:
for k in macro:
print(k)
from prompt_toolkit.application.run_in_terminal import run_in_terminal
run_in_terminal(print_macro) | Print the last keyboard macro. |
172,105 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class Document:
"""
This is a immutable class around the text and cursor position, and contains
methods for querying this data, e.g. to give the text before the cursor.
This class is usually instantiated by a :class:`~prompt_toolkit.buffer.Buffer`
object, and accessed as the `document` property of that class.
:param text: string
:param cursor_position: int
:param selection: :class:`.SelectionState`
"""
__slots__ = ("_text", "_cursor_position", "_selection", "_cache")
def __init__(
self,
text: str = "",
cursor_position: int | None = None,
selection: SelectionState | None = None,
) -> None:
# Check cursor position. It can also be right after the end. (Where we
# insert text.)
assert cursor_position is None or cursor_position <= len(text), AssertionError(
f"cursor_position={cursor_position!r}, len_text={len(text)!r}"
)
# By default, if no cursor position was given, make sure to put the
# cursor position is at the end of the document. This is what makes
# sense in most places.
if cursor_position is None:
cursor_position = len(text)
# Keep these attributes private. A `Document` really has to be
# considered to be immutable, because otherwise the caching will break
# things. Because of that, we wrap these into read-only properties.
self._text = text
self._cursor_position = cursor_position
self._selection = selection
# Cache for lines/indexes. (Shared with other Document instances that
# contain the same text.
try:
self._cache = _text_to_document_cache[self.text]
except KeyError:
self._cache = _DocumentCache()
_text_to_document_cache[self.text] = self._cache
# XX: For some reason, above, we can't use 'WeakValueDictionary.setdefault'.
# This fails in Pypy3. `self._cache` becomes None, because that's what
# 'setdefault' returns.
# self._cache = _text_to_document_cache.setdefault(self.text, _DocumentCache())
# assert self._cache
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.text!r}, {self.cursor_position!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Document):
return False
return (
self.text == other.text
and self.cursor_position == other.cursor_position
and self.selection == other.selection
)
def text(self) -> str:
"The document text."
return self._text
def cursor_position(self) -> int:
"The document cursor position."
return self._cursor_position
def selection(self) -> SelectionState | None:
":class:`.SelectionState` object."
return self._selection
def current_char(self) -> str:
"""Return character under cursor or an empty string."""
return self._get_char_relative_to_cursor(0) or ""
def char_before_cursor(self) -> str:
"""Return character before the cursor or an empty string."""
return self._get_char_relative_to_cursor(-1) or ""
def text_before_cursor(self) -> str:
return self.text[: self.cursor_position :]
def text_after_cursor(self) -> str:
return self.text[self.cursor_position :]
def current_line_before_cursor(self) -> str:
"""Text from the start of the line until the cursor."""
_, _, text = self.text_before_cursor.rpartition("\n")
return text
def current_line_after_cursor(self) -> str:
"""Text from the cursor until the end of the line."""
text, _, _ = self.text_after_cursor.partition("\n")
return text
def lines(self) -> list[str]:
"""
Array of all the lines.
"""
# Cache, because this one is reused very often.
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split("\n"))
return self._cache.lines
def _line_start_indexes(self) -> list[int]:
"""
Array pointing to the start indexes of all the lines.
"""
# Cache, because this is often reused. (If it is used, it's often used
# many times. And this has to be fast for editing big documents!)
if self._cache.line_indexes is None:
# Create list of line lengths.
line_lengths = map(len, self.lines)
# Calculate cumulative sums.
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
# Remove the last item. (This is not a new line.)
if len(indexes) > 1:
indexes.pop()
self._cache.line_indexes = indexes
return self._cache.line_indexes
def lines_from_current(self) -> list[str]:
"""
Array of the lines starting from the current line, until the last line.
"""
return self.lines[self.cursor_position_row :]
def line_count(self) -> int:
r"""Return the number of lines in this document. If the document ends
with a trailing \n, that counts as the beginning of a new line."""
return len(self.lines)
def current_line(self) -> str:
"""Return the text on the line where the cursor is. (when the input
consists of just one line, it equals `text`."""
return self.current_line_before_cursor + self.current_line_after_cursor
def leading_whitespace_in_current_line(self) -> str:
"""The leading whitespace in the left margin of the current line."""
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length]
def _get_char_relative_to_cursor(self, offset: int = 0) -> str:
"""
Return character relative to cursor position, or empty string
"""
try:
return self.text[self.cursor_position + offset]
except IndexError:
return ""
def on_first_line(self) -> bool:
"""
True when we are at the first line.
"""
return self.cursor_position_row == 0
def on_last_line(self) -> bool:
"""
True when we are at the last line.
"""
return self.cursor_position_row == self.line_count - 1
def cursor_position_row(self) -> int:
"""
Current row. (0-based.)
"""
row, _ = self._find_line_start_index(self.cursor_position)
return row
def cursor_position_col(self) -> int:
"""
Current column. (0-based.)
"""
# (Don't use self.text_before_cursor to calculate this. Creating
# substrings and doing rsplit is too expensive for getting the cursor
# position.)
_, line_start_index = self._find_line_start_index(self.cursor_position)
return self.cursor_position - line_start_index
def _find_line_start_index(self, index: int) -> tuple[int, int]:
"""
For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple.
"""
indexes = self._line_start_indexes
pos = bisect.bisect_right(indexes, index) - 1
return pos, indexes[pos]
def translate_index_to_position(self, index: int) -> tuple[int, int]:
"""
Given an index for the text, return the corresponding (row, col) tuple.
(0-based. Returns (0, 0) for index=0.)
"""
# Find start of this line.
row, row_index = self._find_line_start_index(index)
col = index - row_index
return row, col
def translate_row_col_to_index(self, row: int, col: int) -> int:
"""
Given a (row, col) tuple, return the corresponding index.
(Row and col params are 0-based.)
Negative row/col values are turned into zero.
"""
try:
result = self._line_start_indexes[row]
line = self.lines[row]
except IndexError:
if row < 0:
result = self._line_start_indexes[0]
line = self.lines[0]
else:
result = self._line_start_indexes[-1]
line = self.lines[-1]
result += max(0, min(col, len(line)))
# Keep in range. (len(self.text) is included, because the cursor can be
# right after the end of the text as well.)
result = max(0, min(result, len(self.text)))
return result
def is_cursor_at_the_end(self) -> bool:
"""True when the cursor is at the end of the text."""
return self.cursor_position == len(self.text)
def is_cursor_at_the_end_of_line(self) -> bool:
"""True when the cursor is at the end of this line."""
return self.current_char in ("\n", "")
def has_match_at_current_position(self, sub: str) -> bool:
"""
`True` when this substring is found at the cursor position.
"""
return self.text.find(sub, self.cursor_position) == self.cursor_position
def find(
self,
sub: str,
in_current_line: bool = False,
include_current_position: bool = False,
ignore_case: bool = False,
count: int = 1,
) -> int | None:
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurrence.
"""
assert isinstance(ignore_case, bool)
if in_current_line:
text = self.current_line_after_cursor
else:
text = self.text_after_cursor
if not include_current_position:
if len(text) == 0:
return None # (Otherwise, we always get a match for the empty string.)
else:
text = text[1:]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub), text, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
if include_current_position:
return match.start(0)
else:
return match.start(0) + 1
except StopIteration:
pass
return None
def find_all(self, sub: str, ignore_case: bool = False) -> list[int]:
"""
Find all occurrences of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)]
def find_backwards(
self,
sub: str,
in_current_line: bool = False,
ignore_case: bool = False,
count: int = 1,
) -> int | None:
"""
Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurrence.
"""
if in_current_line:
before_cursor = self.current_line_before_cursor[::-1]
else:
before_cursor = self.text_before_cursor[::-1]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.start(0) - len(sub)
except StopIteration:
pass
return None
def get_word_before_cursor(
self, WORD: bool = False, pattern: Pattern[str] | None = None
) -> str:
"""
Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string.
:param pattern: (None or compiled regex). When given, use this regex
pattern.
"""
if self._is_word_before_cursor_complete(WORD=WORD, pattern=pattern):
# Space before the cursor or no text before cursor.
return ""
text_before_cursor = self.text_before_cursor
start = self.find_start_of_previous_word(WORD=WORD, pattern=pattern) or 0
return text_before_cursor[len(text_before_cursor) + start :]
def _is_word_before_cursor_complete(
self, WORD: bool = False, pattern: Pattern[str] | None = None
) -> bool:
if pattern:
return self.find_start_of_previous_word(WORD=WORD, pattern=pattern) is None
else:
return (
self.text_before_cursor == "" or self.text_before_cursor[-1:].isspace()
)
def find_start_of_previous_word(
self, count: int = 1, WORD: bool = False, pattern: Pattern[str] | None = None
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found.
:param pattern: (None or compiled regex). When given, use this regex
pattern.
"""
assert not (WORD and pattern)
# Reverse the text before the cursor, in order to do an efficient
# backwards search.
text_before_cursor = self.text_before_cursor[::-1]
if pattern:
regex = pattern
elif WORD:
regex = _FIND_BIG_WORD_RE
else:
regex = _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.end(0)
except StopIteration:
pass
return None
def find_boundaries_of_current_word(
self,
WORD: bool = False,
include_leading_whitespace: bool = False,
include_trailing_whitespace: bool = False,
) -> tuple[int, int]:
"""
Return the relative boundaries (startpos, endpos) of the current word under the
cursor. (This is at the current line, because line boundaries obviously
don't belong to any word.)
If not on a word, this returns (0,0)
"""
text_before_cursor = self.current_line_before_cursor[::-1]
text_after_cursor = self.current_line_after_cursor
def get_regex(include_whitespace: bool) -> Pattern[str]:
return {
(False, False): _FIND_CURRENT_WORD_RE,
(False, True): _FIND_CURRENT_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
(True, False): _FIND_CURRENT_BIG_WORD_RE,
(True, True): _FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
}[(WORD, include_whitespace)]
match_before = get_regex(include_leading_whitespace).search(text_before_cursor)
match_after = get_regex(include_trailing_whitespace).search(text_after_cursor)
# When there is a match before and after, and we're not looking for
# WORDs, make sure that both the part before and after the cursor are
# either in the [a-zA-Z_] alphabet or not. Otherwise, drop the part
# before the cursor.
if not WORD and match_before and match_after:
c1 = self.text[self.cursor_position - 1]
c2 = self.text[self.cursor_position]
alphabet = string.ascii_letters + "0123456789_"
if (c1 in alphabet) != (c2 in alphabet):
match_before = None
return (
-match_before.end(1) if match_before else 0,
match_after.end(1) if match_after else 0,
)
def get_word_under_cursor(self, WORD: bool = False) -> str:
"""
Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region.
"""
start, end = self.find_boundaries_of_current_word(WORD=WORD)
return self.text[self.cursor_position + start : self.cursor_position + end]
def find_next_word_beginning(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_after_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return match.start(1)
except StopIteration:
pass
return None
def find_next_word_ending(
self, include_current_position: bool = False, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_ending(count=-count, WORD=WORD)
if include_current_position:
text = self.text_after_cursor
else:
text = self.text_after_cursor[1:]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterable = regex.finditer(text)
try:
for i, match in enumerate(iterable):
if i + 1 == count:
value = match.end(1)
if include_current_position:
return value
else:
return value + 1
except StopIteration:
pass
return None
def find_previous_word_beginning(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_before_cursor[::-1])
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.end(1)
except StopIteration:
pass
return None
def find_previous_word_ending(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the end
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_ending(count=-count, WORD=WORD)
text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return -match.start(1) + 1
except StopIteration:
pass
return None
def find_next_matching_line(
self, match_func: Callable[[str], bool], count: int = 1
) -> int | None:
"""
Look downwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[self.cursor_position_row + 1 :]):
if match_func(line):
result = 1 + index
count -= 1
if count == 0:
break
return result
def find_previous_matching_line(
self, match_func: Callable[[str], bool], count: int = 1
) -> int | None:
"""
Look upwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[: self.cursor_position_row][::-1]):
if match_func(line):
result = -1 - index
count -= 1
if count == 0:
break
return result
def get_cursor_left_position(self, count: int = 1) -> int:
"""
Relative position for cursor left.
"""
if count < 0:
return self.get_cursor_right_position(-count)
return -min(self.cursor_position_col, count)
def get_cursor_right_position(self, count: int = 1) -> int:
"""
Relative position for cursor_right.
"""
if count < 0:
return self.get_cursor_left_position(-count)
return min(count, len(self.current_line_after_cursor))
def get_cursor_up_position(
self, count: int = 1, preferred_column: int | None = None
) -> int:
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-up button.
:param preferred_column: When given, go to this column instead of
staying at the current column.
"""
assert count >= 1
column = (
self.cursor_position_col if preferred_column is None else preferred_column
)
return (
self.translate_row_col_to_index(
max(0, self.cursor_position_row - count), column
)
- self.cursor_position
)
def get_cursor_down_position(
self, count: int = 1, preferred_column: int | None = None
) -> int:
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-down button.
:param preferred_column: When given, go to this column instead of
staying at the current column.
"""
assert count >= 1
column = (
self.cursor_position_col if preferred_column is None else preferred_column
)
return (
self.translate_row_col_to_index(self.cursor_position_row + count, column)
- self.cursor_position
)
def find_enclosing_bracket_right(
self, left_ch: str, right_ch: str, end_pos: int | None = None
) -> int | None:
"""
Find the right bracket enclosing current position. Return the relative
position to the cursor position.
When `end_pos` is given, don't look past the position.
"""
if self.current_char == right_ch:
return 0
if end_pos is None:
end_pos = len(self.text)
else:
end_pos = min(len(self.text), end_pos)
stack = 1
# Look forward.
for i in range(self.cursor_position + 1, end_pos):
c = self.text[i]
if c == left_ch:
stack += 1
elif c == right_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position
return None
def find_enclosing_bracket_left(
self, left_ch: str, right_ch: str, start_pos: int | None = None
) -> int | None:
"""
Find the left bracket enclosing current position. Return the relative
position to the cursor position.
When `start_pos` is given, don't look past the position.
"""
if self.current_char == left_ch:
return 0
if start_pos is None:
start_pos = 0
else:
start_pos = max(0, start_pos)
stack = 1
# Look backward.
for i in range(self.cursor_position - 1, start_pos - 1, -1):
c = self.text[i]
if c == right_ch:
stack += 1
elif c == left_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position
return None
def find_matching_bracket_position(
self, start_pos: int | None = None, end_pos: int | None = None
) -> int:
"""
Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
# Look for a match.
for pair in "()", "[]", "{}", "<>":
A = pair[0]
B = pair[1]
if self.current_char == A:
return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
elif self.current_char == B:
return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
return 0
def get_start_of_document_position(self) -> int:
"""Relative position for the start of the document."""
return -self.cursor_position
def get_end_of_document_position(self) -> int:
"""Relative position for the end of the document."""
return len(self.text) - self.cursor_position
def get_start_of_line_position(self, after_whitespace: bool = False) -> int:
"""Relative position for the start of this line."""
if after_whitespace:
current_line = self.current_line
return (
len(current_line)
- len(current_line.lstrip())
- self.cursor_position_col
)
else:
return -len(self.current_line_before_cursor)
def get_end_of_line_position(self) -> int:
"""Relative position for the end of this line."""
return len(self.current_line_after_cursor)
def last_non_blank_of_current_line_position(self) -> int:
"""
Relative position for the last non blank character of this line.
"""
return len(self.current_line.rstrip()) - self.cursor_position_col - 1
def get_column_cursor_position(self, column: int) -> int:
"""
Return the relative cursor position for this column at the current
line. (It will stay between the boundaries of the line in case of a
larger number.)
"""
line_length = len(self.current_line)
current_column = self.cursor_position_col
column = max(0, min(line_length, column))
return column - current_column
def selection_range(
self,
) -> tuple[
int, int
]: # XXX: shouldn't this return `None` if there is no selection???
"""
Return (from, to) tuple of the selection.
start and end position are included.
This doesn't take the selection type into account. Use
`selection_ranges` instead.
"""
if self.selection:
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
else:
from_, to = self.cursor_position, self.cursor_position
return from_, to
def selection_ranges(self) -> Iterable[tuple[int, int]]:
"""
Return a list of `(from, to)` tuples for the selection or none if
nothing was selected. The upper boundary is not included.
This will yield several (from, to) tuples in case of a BLOCK selection.
This will return zero ranges, like (8,8) for empty lines in a block
selection.
"""
if self.selection:
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
if self.selection.type == SelectionType.BLOCK:
from_line, from_column = self.translate_index_to_position(from_)
to_line, to_column = self.translate_index_to_position(to)
from_column, to_column = sorted([from_column, to_column])
lines = self.lines
if vi_mode():
to_column += 1
for l in range(from_line, to_line + 1):
line_length = len(lines[l])
if from_column <= line_length:
yield (
self.translate_row_col_to_index(l, from_column),
self.translate_row_col_to_index(
l, min(line_length, to_column)
),
)
else:
# In case of a LINES selection, go to the start/end of the lines.
if self.selection.type == SelectionType.LINES:
from_ = max(0, self.text.rfind("\n", 0, from_) + 1)
if self.text.find("\n", to) >= 0:
to = self.text.find("\n", to)
else:
to = len(self.text) - 1
# In Vi mode, the upper boundary is always included. For Emacs,
# that's not the case.
if vi_mode():
to += 1
yield from_, to
def selection_range_at_line(self, row: int) -> tuple[int, int] | None:
"""
If the selection spans a portion of the given line, return a (from, to) tuple.
The returned upper boundary is not included in the selection, so
`(0, 0)` is an empty selection. `(0, 1)`, is a one character selection.
Returns None if the selection doesn't cover this line at all.
"""
if self.selection:
line = self.lines[row]
row_start = self.translate_row_col_to_index(row, 0)
row_end = self.translate_row_col_to_index(row, len(line))
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
# Take the intersection of the current line and the selection.
intersection_start = max(row_start, from_)
intersection_end = min(row_end, to)
if intersection_start <= intersection_end:
if self.selection.type == SelectionType.LINES:
intersection_start = row_start
intersection_end = row_end
elif self.selection.type == SelectionType.BLOCK:
_, col1 = self.translate_index_to_position(from_)
_, col2 = self.translate_index_to_position(to)
col1, col2 = sorted([col1, col2])
if col1 > len(line):
return None # Block selection doesn't cross this line.
intersection_start = self.translate_row_col_to_index(row, col1)
intersection_end = self.translate_row_col_to_index(row, col2)
_, from_column = self.translate_index_to_position(intersection_start)
_, to_column = self.translate_index_to_position(intersection_end)
# In Vi mode, the upper boundary is always included. For Emacs
# mode, that's not the case.
if vi_mode():
to_column += 1
return from_column, to_column
return None
def cut_selection(self) -> tuple[Document, ClipboardData]:
"""
Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the
document represents the new document when the selection is cut, and the
clipboard data, represents whatever has to be put on the clipboard.
"""
if self.selection:
cut_parts = []
remaining_parts = []
new_cursor_position = self.cursor_position
last_to = 0
for from_, to in self.selection_ranges():
if last_to == 0:
new_cursor_position = from_
remaining_parts.append(self.text[last_to:from_])
cut_parts.append(self.text[from_:to])
last_to = to
remaining_parts.append(self.text[last_to:])
cut_text = "\n".join(cut_parts)
remaining_text = "".join(remaining_parts)
# In case of a LINES selection, don't include the trailing newline.
if self.selection.type == SelectionType.LINES and cut_text.endswith("\n"):
cut_text = cut_text[:-1]
return (
Document(text=remaining_text, cursor_position=new_cursor_position),
ClipboardData(cut_text, self.selection.type),
)
else:
return self, ClipboardData("")
def paste_clipboard_data(
self,
data: ClipboardData,
paste_mode: PasteMode = PasteMode.EMACS,
count: int = 1,
) -> Document:
"""
Return a new :class:`.Document` instance which contains the result if
we would paste this data at the current cursor position.
:param paste_mode: Where to paste. (Before/after/emacs.)
:param count: When >1, Paste multiple times.
"""
before = paste_mode == PasteMode.VI_BEFORE
after = paste_mode == PasteMode.VI_AFTER
if data.type == SelectionType.CHARACTERS:
if after:
new_text = (
self.text[: self.cursor_position + 1]
+ data.text * count
+ self.text[self.cursor_position + 1 :]
)
else:
new_text = (
self.text_before_cursor + data.text * count + self.text_after_cursor
)
new_cursor_position = self.cursor_position + len(data.text) * count
if before:
new_cursor_position -= 1
elif data.type == SelectionType.LINES:
l = self.cursor_position_row
if before:
lines = self.lines[:l] + [data.text] * count + self.lines[l:]
new_text = "\n".join(lines)
new_cursor_position = len("".join(self.lines[:l])) + l
else:
lines = self.lines[: l + 1] + [data.text] * count + self.lines[l + 1 :]
new_cursor_position = len("".join(self.lines[: l + 1])) + l + 1
new_text = "\n".join(lines)
elif data.type == SelectionType.BLOCK:
lines = self.lines[:]
start_line = self.cursor_position_row
start_column = self.cursor_position_col + (0 if before else 1)
for i, line in enumerate(data.text.split("\n")):
index = i + start_line
if index >= len(lines):
lines.append("")
lines[index] = lines[index].ljust(start_column)
lines[index] = (
lines[index][:start_column]
+ line * count
+ lines[index][start_column:]
)
new_text = "\n".join(lines)
new_cursor_position = self.cursor_position + (0 if before else 1)
return Document(text=new_text, cursor_position=new_cursor_position)
def empty_line_count_at_the_end(self) -> int:
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count
def start_of_paragraph(self, count: int = 1, before: bool = False) -> int:
"""
Return the start of the current paragraph. (Relative cursor position.)
"""
def match_func(text: str) -> bool:
return not text or text.isspace()
line_index = self.find_previous_matching_line(
match_func=match_func, count=count
)
if line_index:
add = 0 if before else 1
return min(0, self.get_cursor_up_position(count=-line_index) + add)
else:
return -self.cursor_position
def end_of_paragraph(self, count: int = 1, after: bool = False) -> int:
"""
Return the end of the current paragraph. (Relative cursor position.)
"""
def match_func(text: str) -> bool:
return not text or text.isspace()
line_index = self.find_next_matching_line(match_func=match_func, count=count)
if line_index:
add = 0 if after else 1
return max(0, self.get_cursor_down_position(count=line_index) - add)
else:
return len(self.text_after_cursor)
# Modifiers.
def insert_after(self, text: str) -> Document:
"""
Create a new document, with this text inserted after the buffer.
It keeps selection ranges and cursor position in sync.
"""
return Document(
text=self.text + text,
cursor_position=self.cursor_position,
selection=self.selection,
)
def insert_before(self, text: str) -> Document:
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
original_cursor_position=selection_state.original_cursor_position
+ len(text),
type=selection_state.type,
)
return Document(
text=text + self.text,
cursor_position=self.cursor_position + len(text),
selection=selection_state,
)
The provided code snippet includes necessary dependencies for implementing the `insert_comment` function. Write a Python function `def insert_comment(event: E) -> None` to solve the following problem:
Without numeric argument, comment all lines. With numeric argument, uncomment all lines. In any case accept the input.
Here is the function:
def insert_comment(event: E) -> None:
"""
Without numeric argument, comment all lines.
With numeric argument, uncomment all lines.
In any case accept the input.
"""
buff = event.current_buffer
# Transform all lines.
if event.arg != 1:
def change(line: str) -> str:
return line[1:] if line.startswith("#") else line
else:
def change(line: str) -> str:
return "#" + line
buff.document = Document(
text="\n".join(map(change, buff.text.splitlines())), cursor_position=0
)
# Accept input.
buff.validate_and_handle() | Without numeric argument, comment all lines. With numeric argument, uncomment all lines. In any case accept the input. |
172,106 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
The provided code snippet includes necessary dependencies for implementing the `vi_editing_mode` function. Write a Python function `def vi_editing_mode(event: E) -> None` to solve the following problem:
Switch to Vi editing mode.
Here is the function:
def vi_editing_mode(event: E) -> None:
"""
Switch to Vi editing mode.
"""
event.app.editing_mode = EditingMode.VI | Switch to Vi editing mode. |
172,107 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
The provided code snippet includes necessary dependencies for implementing the `emacs_editing_mode` function. Write a Python function `def emacs_editing_mode(event: E) -> None` to solve the following problem:
Switch to Emacs editing mode.
Here is the function:
def emacs_editing_mode(event: E) -> None:
"""
Switch to Emacs editing mode.
"""
event.app.editing_mode = EditingMode.EMACS | Switch to Emacs editing mode. |
172,108 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
class KeyPress:
"""
:param key: A `Keys` instance or text (one character).
:param data: The received string on stdin. (Often vt100 escape codes.)
"""
def __init__(self, key: Keys | str, data: str | None = None) -> None:
assert isinstance(key, Keys) or len(key) == 1
if data is None:
if isinstance(key, Keys):
data = key.value
else:
data = key # 'key' is a one character string.
self.key = key
self.data = data
def __repr__(self) -> str:
return f"{self.__class__.__name__}(key={self.key!r}, data={self.data!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, KeyPress):
return False
return self.key == other.key and self.data == other.data
class Keys(str, Enum):
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
value: str
Escape = "escape" # Also Control-[
ShiftEscape = "s-escape"
ControlAt = "c-@" # Also Control-Space.
ControlA = "c-a"
ControlB = "c-b"
ControlC = "c-c"
ControlD = "c-d"
ControlE = "c-e"
ControlF = "c-f"
ControlG = "c-g"
ControlH = "c-h"
ControlI = "c-i" # Tab
ControlJ = "c-j" # Newline
ControlK = "c-k"
ControlL = "c-l"
ControlM = "c-m" # Carriage return
ControlN = "c-n"
ControlO = "c-o"
ControlP = "c-p"
ControlQ = "c-q"
ControlR = "c-r"
ControlS = "c-s"
ControlT = "c-t"
ControlU = "c-u"
ControlV = "c-v"
ControlW = "c-w"
ControlX = "c-x"
ControlY = "c-y"
ControlZ = "c-z"
Control1 = "c-1"
Control2 = "c-2"
Control3 = "c-3"
Control4 = "c-4"
Control5 = "c-5"
Control6 = "c-6"
Control7 = "c-7"
Control8 = "c-8"
Control9 = "c-9"
Control0 = "c-0"
ControlShift1 = "c-s-1"
ControlShift2 = "c-s-2"
ControlShift3 = "c-s-3"
ControlShift4 = "c-s-4"
ControlShift5 = "c-s-5"
ControlShift6 = "c-s-6"
ControlShift7 = "c-s-7"
ControlShift8 = "c-s-8"
ControlShift9 = "c-s-9"
ControlShift0 = "c-s-0"
ControlBackslash = "c-\\"
ControlSquareClose = "c-]"
ControlCircumflex = "c-^"
ControlUnderscore = "c-_"
Left = "left"
Right = "right"
Up = "up"
Down = "down"
Home = "home"
End = "end"
Insert = "insert"
Delete = "delete"
PageUp = "pageup"
PageDown = "pagedown"
ControlLeft = "c-left"
ControlRight = "c-right"
ControlUp = "c-up"
ControlDown = "c-down"
ControlHome = "c-home"
ControlEnd = "c-end"
ControlInsert = "c-insert"
ControlDelete = "c-delete"
ControlPageUp = "c-pageup"
ControlPageDown = "c-pagedown"
ShiftLeft = "s-left"
ShiftRight = "s-right"
ShiftUp = "s-up"
ShiftDown = "s-down"
ShiftHome = "s-home"
ShiftEnd = "s-end"
ShiftInsert = "s-insert"
ShiftDelete = "s-delete"
ShiftPageUp = "s-pageup"
ShiftPageDown = "s-pagedown"
ControlShiftLeft = "c-s-left"
ControlShiftRight = "c-s-right"
ControlShiftUp = "c-s-up"
ControlShiftDown = "c-s-down"
ControlShiftHome = "c-s-home"
ControlShiftEnd = "c-s-end"
ControlShiftInsert = "c-s-insert"
ControlShiftDelete = "c-s-delete"
ControlShiftPageUp = "c-s-pageup"
ControlShiftPageDown = "c-s-pagedown"
BackTab = "s-tab" # shift + tab
F1 = "f1"
F2 = "f2"
F3 = "f3"
F4 = "f4"
F5 = "f5"
F6 = "f6"
F7 = "f7"
F8 = "f8"
F9 = "f9"
F10 = "f10"
F11 = "f11"
F12 = "f12"
F13 = "f13"
F14 = "f14"
F15 = "f15"
F16 = "f16"
F17 = "f17"
F18 = "f18"
F19 = "f19"
F20 = "f20"
F21 = "f21"
F22 = "f22"
F23 = "f23"
F24 = "f24"
ControlF1 = "c-f1"
ControlF2 = "c-f2"
ControlF3 = "c-f3"
ControlF4 = "c-f4"
ControlF5 = "c-f5"
ControlF6 = "c-f6"
ControlF7 = "c-f7"
ControlF8 = "c-f8"
ControlF9 = "c-f9"
ControlF10 = "c-f10"
ControlF11 = "c-f11"
ControlF12 = "c-f12"
ControlF13 = "c-f13"
ControlF14 = "c-f14"
ControlF15 = "c-f15"
ControlF16 = "c-f16"
ControlF17 = "c-f17"
ControlF18 = "c-f18"
ControlF19 = "c-f19"
ControlF20 = "c-f20"
ControlF21 = "c-f21"
ControlF22 = "c-f22"
ControlF23 = "c-f23"
ControlF24 = "c-f24"
# Matches any key.
Any = "<any>"
# Special.
ScrollUp = "<scroll-up>"
ScrollDown = "<scroll-down>"
CPRResponse = "<cursor-position-response>"
Vt100MouseEvent = "<vt100-mouse-event>"
WindowsMouseEvent = "<windows-mouse-event>"
BracketedPaste = "<bracketed-paste>"
SIGINT = "<sigint>"
# For internal use: key which is ignored.
# (The key binding for this key should not do anything.)
Ignore = "<ignore>"
# Some 'Key' aliases (for backwards-compatibility).
ControlSpace = ControlAt
Tab = ControlI
Enter = ControlM
Backspace = ControlH
# ShiftControl was renamed to ControlShift in
# 888fcb6fa4efea0de8333177e1bbc792f3ff3c24 (20 Feb 2020).
ShiftControlLeft = ControlShiftLeft
ShiftControlRight = ControlShiftRight
ShiftControlHome = ControlShiftHome
ShiftControlEnd = ControlShiftEnd
The provided code snippet includes necessary dependencies for implementing the `prefix_meta` function. Write a Python function `def prefix_meta(event: E) -> None` to solve the following problem:
Metafy the next character typed. This is for keyboards without a meta key. Sometimes people also want to bind other keys to Meta, e.g. 'jj':: key_bindings.add_key_binding('j', 'j', filter=ViInsertMode())(prefix_meta)
Here is the function:
def prefix_meta(event: E) -> None:
"""
Metafy the next character typed. This is for keyboards without a meta key.
Sometimes people also want to bind other keys to Meta, e.g. 'jj'::
key_bindings.add_key_binding('j', 'j', filter=ViInsertMode())(prefix_meta)
"""
# ('first' should be true, because we want to insert it at the current
# position in the queue.)
event.app.key_processor.feed(KeyPress(Keys.Escape), first=True) | Metafy the next character typed. This is for keyboards without a meta key. Sometimes people also want to bind other keys to Meta, e.g. 'jj':: key_bindings.add_key_binding('j', 'j', filter=ViInsertMode())(prefix_meta) |
172,109 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `operate_and_get_next` function. Write a Python function `def operate_and_get_next(event: E) -> None` to solve the following problem:
Accept the current line for execution and fetch the next line relative to the current line from the history for editing.
Here is the function:
def operate_and_get_next(event: E) -> None:
"""
Accept the current line for execution and fetch the next line relative to
the current line from the history for editing.
"""
buff = event.current_buffer
new_index = buff.working_index + 1
# Accept the current input. (This will also redraw the interface in the
# 'done' state.)
buff.validate_and_handle()
# Set the new index at the start of the next run.
def set_working_index() -> None:
if new_index < len(buff._working_lines):
buff.working_index = new_index
event.app.pre_run_callables.append(set_working_index) | Accept the current line for execution and fetch the next line relative to the current line from the history for editing. |
172,110 | from __future__ import annotations
from typing import Callable, Dict, TypeVar, Union, cast
from prompt_toolkit.document import Document
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import Binding, key_binding
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode
from .completion import display_completions_like_readline, generate_completions
E = KeyPressEvent
The provided code snippet includes necessary dependencies for implementing the `edit_and_execute` function. Write a Python function `def edit_and_execute(event: E) -> None` to solve the following problem:
Invoke an editor on the current command line, and accept the result.
Here is the function:
def edit_and_execute(event: E) -> None:
"""
Invoke an editor on the current command line, and accept the result.
"""
buff = event.current_buffer
buff.open_in_editor(validate_and_handle=True) | Invoke an editor on the current command line, and accept the result. |
172,111 | from __future__ import annotations
from prompt_toolkit import search
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition, control_is_searchable, is_searching
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from ..key_bindings import key_binding
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `_previous_buffer_is_returnable` function. Write a Python function `def _previous_buffer_is_returnable() -> bool` to solve the following problem:
True if the previously focused buffer has a return handler.
Here is the function:
def _previous_buffer_is_returnable() -> bool:
"""
True if the previously focused buffer has a return handler.
"""
prev_control = get_app().layout.search_target_buffer_control
return bool(prev_control and prev_control.buffer.is_returnable) | True if the previously focused buffer has a return handler. |
172,112 | from __future__ import annotations
from prompt_toolkit import search
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition, control_is_searchable, is_searching
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from ..key_bindings import key_binding
E = KeyPressEvent
def accept_search(event: E) -> None:
"""
When enter pressed in isearch, quit isearch mode. (Multiline
isearch would be too complicated.)
(Usually bound to Enter.)
"""
search.accept_search()
The provided code snippet includes necessary dependencies for implementing the `accept_search_and_accept_input` function. Write a Python function `def accept_search_and_accept_input(event: E) -> None` to solve the following problem:
Accept the search operation first, then accept the input.
Here is the function:
def accept_search_and_accept_input(event: E) -> None:
"""
Accept the search operation first, then accept the input.
"""
search.accept_search()
event.current_buffer.validate_and_handle() | Accept the search operation first, then accept the input. |
172,113 | from __future__ import annotations
import codecs
import string
from enum import Enum
from itertools import accumulate
from typing import Callable, Iterable, List, Optional, Tuple, TypeVar, Union
from prompt_toolkit.application.current import get_app
from prompt_toolkit.buffer import Buffer, indent, reshape_text, unindent
from prompt_toolkit.clipboard import ClipboardData
from prompt_toolkit.document import Document
from prompt_toolkit.filters import (
Always,
Condition,
Filter,
has_arg,
is_read_only,
is_searching,
)
from prompt_toolkit.filters.app import (
in_paste_mode,
is_multiline,
vi_digraph_mode,
vi_insert_mode,
vi_insert_multiple_mode,
vi_mode,
vi_navigation_mode,
vi_recording_macro,
vi_replace_mode,
vi_replace_single_mode,
vi_search_direction_reversed,
vi_selection_mode,
vi_waiting_for_text_object_mode,
)
from prompt_toolkit.input.vt100_parser import Vt100Parser
from prompt_toolkit.key_binding.digraphs import DIGRAPHS
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.key_binding.vi_state import CharacterFind, InputMode
from prompt_toolkit.keys import Keys
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode, SelectionState, SelectionType
from ..key_bindings import ConditionalKeyBindings, KeyBindings, KeyBindingsBase
from .named_commands import get_by_name
__all__ = [
"load_vi_bindings",
"load_vi_search_bindings",
]
E = KeyPressEvent
ascii_lowercase = string.ascii_lowercase
vi_register_names = ascii_lowercase + "0123456789"
class TextObjectType(Enum):
EXCLUSIVE = "EXCLUSIVE"
INCLUSIVE = "INCLUSIVE"
LINEWISE = "LINEWISE"
BLOCK = "BLOCK"
class TextObject:
"""
Return struct for functions wrapped in ``text_object``.
Both `start` and `end` are relative to the current cursor position.
"""
def __init__(
self, start: int, end: int = 0, type: TextObjectType = TextObjectType.EXCLUSIVE
):
self.start = start
self.end = end
self.type = type
def selection_type(self) -> SelectionType:
if self.type == TextObjectType.LINEWISE:
return SelectionType.LINES
if self.type == TextObjectType.BLOCK:
return SelectionType.BLOCK
else:
return SelectionType.CHARACTERS
def sorted(self) -> tuple[int, int]:
"""
Return a (start, end) tuple where start <= end.
"""
if self.start < self.end:
return self.start, self.end
else:
return self.end, self.start
def operator_range(self, document: Document) -> tuple[int, int]:
"""
Return a (start, end) tuple with start <= end that indicates the range
operators should operate on.
`buffer` is used to get start and end of line positions.
This should return something that can be used in a slice, so the `end`
position is *not* included.
"""
start, end = self.sorted()
doc = document
if (
self.type == TextObjectType.EXCLUSIVE
and doc.translate_index_to_position(end + doc.cursor_position)[1] == 0
):
# If the motion is exclusive and the end of motion is on the first
# column, the end position becomes end of previous line.
end -= 1
if self.type == TextObjectType.INCLUSIVE:
end += 1
if self.type == TextObjectType.LINEWISE:
# Select whole lines
row, col = doc.translate_index_to_position(start + doc.cursor_position)
start = doc.translate_row_col_to_index(row, 0) - doc.cursor_position
row, col = doc.translate_index_to_position(end + doc.cursor_position)
end = (
doc.translate_row_col_to_index(row, len(doc.lines[row]))
- doc.cursor_position
)
return start, end
def get_line_numbers(self, buffer: Buffer) -> tuple[int, int]:
"""
Return a (start_line, end_line) pair.
"""
# Get absolute cursor positions from the text object.
from_, to = self.operator_range(buffer.document)
from_ += buffer.cursor_position
to += buffer.cursor_position
# Take the start of the lines.
from_, _ = buffer.document.translate_index_to_position(from_)
to, _ = buffer.document.translate_index_to_position(to)
return from_, to
def cut(self, buffer: Buffer) -> tuple[Document, ClipboardData]:
"""
Turn text object into `ClipboardData` instance.
"""
from_, to = self.operator_range(buffer.document)
from_ += buffer.cursor_position
to += buffer.cursor_position
# For Vi mode, the SelectionState does include the upper position,
# while `self.operator_range` does not. So, go one to the left, unless
# we're in the line mode, then we don't want to risk going to the
# previous line, and missing one line in the selection.
if self.type != TextObjectType.LINEWISE:
to -= 1
document = Document(
buffer.text,
to,
SelectionState(original_cursor_position=from_, type=self.selection_type),
)
new_document, clipboard_data = document.cut_selection()
return new_document, clipboard_data
TextObjectFunction = Callable[[E], TextObject]
_TOF = TypeVar("_TOF", bound=TextObjectFunction)
def create_text_object_decorator(
key_bindings: KeyBindings,
) -> Callable[..., Callable[[_TOF], _TOF]]:
"""
Create a decorator that can be used to register Vi text object implementations.
"""
def text_object_decorator(
*keys: Keys | str,
filter: Filter = Always(),
no_move_handler: bool = False,
no_selection_handler: bool = False,
eager: bool = False,
) -> Callable[[_TOF], _TOF]:
"""
Register a text object function.
Usage::
def handler(event):
# Return a text object for this key.
return TextObject(...)
:param no_move_handler: Disable the move handler in navigation mode.
(It's still active in selection mode.)
"""
def decorator(text_object_func: _TOF) -> _TOF:
*keys, filter=vi_waiting_for_text_object_mode & filter, eager=eager
)
def _apply_operator_to_text_object(event: E) -> None:
# Arguments are multiplied.
vi_state = event.app.vi_state
event._arg = str((vi_state.operator_arg or 1) * (event.arg or 1))
# Call the text object handler.
text_obj = text_object_func(event)
# Get the operator function.
# (Should never be None here, given the
# `vi_waiting_for_text_object_mode` filter state.)
operator_func = vi_state.operator_func
if text_obj is not None and operator_func is not None:
# Call the operator function with the text object.
operator_func(event, text_obj)
# Clear operator.
event.app.vi_state.operator_func = None
event.app.vi_state.operator_arg = None
# Register a move operation. (Doesn't need an operator.)
if not no_move_handler:
*keys,
filter=~vi_waiting_for_text_object_mode
& filter
& vi_navigation_mode,
eager=eager,
)
def _move_in_navigation_mode(event: E) -> None:
"""
Move handler for navigation mode.
"""
text_object = text_object_func(event)
event.current_buffer.cursor_position += text_object.start
# Register a move selection operation.
if not no_selection_handler:
*keys,
filter=~vi_waiting_for_text_object_mode
& filter
& vi_selection_mode,
eager=eager,
)
def _move_in_selection_mode(event: E) -> None:
"""
Move handler for selection mode.
"""
text_object = text_object_func(event)
buff = event.current_buffer
selection_state = buff.selection_state
if selection_state is None:
return # Should not happen, because of the `vi_selection_mode` filter.
# When the text object has both a start and end position, like 'i(' or 'iw',
# Turn this into a selection, otherwise the cursor.
if text_object.end:
# Take selection positions from text object.
start, end = text_object.operator_range(buff.document)
start += buff.cursor_position
end += buff.cursor_position
selection_state.original_cursor_position = start
buff.cursor_position = end
# Take selection type from text object.
if text_object.type == TextObjectType.LINEWISE:
selection_state.type = SelectionType.LINES
else:
selection_state.type = SelectionType.CHARACTERS
else:
event.current_buffer.cursor_position += text_object.start
# Make it possible to chain @text_object decorators.
return text_object_func
return decorator
return text_object_decorator
OperatorFunction = Callable[[E, TextObject], None]
_OF = TypeVar("_OF", bound=OperatorFunction)
def create_operator_decorator(
key_bindings: KeyBindings,
) -> Callable[..., Callable[[_OF], _OF]]:
"""
Create a decorator that can be used for registering Vi operators.
"""
def operator_decorator(
*keys: Keys | str, filter: Filter = Always(), eager: bool = False
) -> Callable[[_OF], _OF]:
"""
Register a Vi operator.
Usage::
def handler(event, text_object):
# Do something with the text object here.
"""
def decorator(operator_func: _OF) -> _OF:
*keys,
filter=~vi_waiting_for_text_object_mode & filter & vi_navigation_mode,
eager=eager,
)
def _operator_in_navigation(event: E) -> None:
"""
Handle operator in navigation mode.
"""
# When this key binding is matched, only set the operator
# function in the ViState. We should execute it after a text
# object has been received.
event.app.vi_state.operator_func = operator_func
event.app.vi_state.operator_arg = event.arg
*keys,
filter=~vi_waiting_for_text_object_mode & filter & vi_selection_mode,
eager=eager,
)
def _operator_in_selection(event: E) -> None:
"""
Handle operator in selection mode.
"""
buff = event.current_buffer
selection_state = buff.selection_state
if selection_state is not None:
# Create text object from selection.
if selection_state.type == SelectionType.LINES:
text_obj_type = TextObjectType.LINEWISE
elif selection_state.type == SelectionType.BLOCK:
text_obj_type = TextObjectType.BLOCK
else:
text_obj_type = TextObjectType.INCLUSIVE
text_object = TextObject(
selection_state.original_cursor_position - buff.cursor_position,
type=text_obj_type,
)
# Execute operator.
operator_func(event, text_object)
# Quit selection mode.
buff.selection_state = None
return operator_func
return decorator
return operator_decorator
def load_vi_bindings() -> KeyBindingsBase:
"""
Vi extensions.
# Overview of Readline Vi commands:
# http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
"""
# Note: Some key bindings have the "~IsReadOnly()" filter added. This
# prevents the handler to be executed when the focus is on a
# read-only buffer.
# This is however only required for those that change the ViState to
# INSERT mode. The `Buffer` class itself throws the
# `EditReadOnlyBuffer` exception for any text operations which is
# handled correctly. There is no need to add "~IsReadOnly" to all key
# bindings that do text manipulation.
key_bindings = KeyBindings()
handle = key_bindings.add
# (Note: Always take the navigation bindings in read-only mode, even when
# ViState says different.)
TransformFunction = Tuple[Tuple[str, ...], Filter, Callable[[str], str]]
vi_transform_functions: list[TransformFunction] = [
# Rot 13 transformation
(
("g", "?"),
Always(),
lambda string: codecs.encode(string, "rot_13"),
),
# To lowercase
(("g", "u"), Always(), lambda string: string.lower()),
# To uppercase.
(("g", "U"), Always(), lambda string: string.upper()),
# Swap case.
(("g", "~"), Always(), lambda string: string.swapcase()),
(
("~",),
Condition(lambda: get_app().vi_state.tilde_operator),
lambda string: string.swapcase(),
),
]
# Insert a character literally (quoted insert).
handle("c-v", filter=vi_insert_mode)(get_by_name("quoted-insert"))
def _back_to_navigation(event: E) -> None:
"""
Escape goes to vi navigation mode.
"""
buffer = event.current_buffer
vi_state = event.app.vi_state
if vi_state.input_mode in (InputMode.INSERT, InputMode.REPLACE):
buffer.cursor_position += buffer.document.get_cursor_left_position()
vi_state.input_mode = InputMode.NAVIGATION
if bool(buffer.selection_state):
buffer.exit_selection()
def _up_in_selection(event: E) -> None:
"""
Arrow up in selection mode.
"""
event.current_buffer.cursor_up(count=event.arg)
def _down_in_selection(event: E) -> None:
"""
Arrow down in selection mode.
"""
event.current_buffer.cursor_down(count=event.arg)
def _up_in_navigation(event: E) -> None:
"""
Arrow up and ControlP in navigation mode go up.
"""
event.current_buffer.auto_up(count=event.arg)
def _go_up(event: E) -> None:
"""
Go up, but if we enter a new history entry, move to the start of the
line.
"""
event.current_buffer.auto_up(
count=event.arg, go_to_start_of_line_if_history_changes=True
)
def _go_down(event: E) -> None:
"""
Arrow down and Control-N in navigation mode.
"""
event.current_buffer.auto_down(count=event.arg)
def _go_down2(event: E) -> None:
"""
Go down, but if we enter a new history entry, go to the start of the line.
"""
event.current_buffer.auto_down(
count=event.arg, go_to_start_of_line_if_history_changes=True
)
def _go_left(event: E) -> None:
"""
In navigation-mode, move cursor.
"""
event.current_buffer.cursor_position += (
event.current_buffer.document.get_cursor_left_position(count=event.arg)
)
def _complete_next(event: E) -> None:
b = event.current_buffer
if b.complete_state:
b.complete_next()
else:
b.start_completion(select_first=True)
def _complete_prev(event: E) -> None:
"""
Control-P: To previous completion.
"""
b = event.current_buffer
if b.complete_state:
b.complete_previous()
else:
b.start_completion(select_last=True)
def _accept_completion(event: E) -> None:
"""
Accept current completion.
"""
event.current_buffer.complete_state = None
def _cancel_completion(event: E) -> None:
"""
Cancel completion. Go back to originally typed text.
"""
event.current_buffer.cancel_completion()
def is_returnable() -> bool:
return get_app().current_buffer.is_returnable
# In navigation mode, pressing enter will always return the input.
handle("enter", filter=vi_navigation_mode & is_returnable)(
get_by_name("accept-line")
)
# In insert mode, also accept input when enter is pressed, and the buffer
# has been marked as single line.
handle("enter", filter=is_returnable & ~is_multiline)(get_by_name("accept-line"))
def _start_of_next_line(event: E) -> None:
"""
Go to the beginning of next line.
"""
b = event.current_buffer
b.cursor_down(count=event.arg)
b.cursor_position += b.document.get_start_of_line_position(
after_whitespace=True
)
# ** In navigation mode **
# List of navigation commands: http://hea-www.harvard.edu/~fine/Tech/vi.html
def _insert_mode(event: E) -> None:
"""
Pressing the Insert key.
"""
event.app.vi_state.input_mode = InputMode.INSERT
def _navigation_mode(event: E) -> None:
"""
Pressing the Insert key.
"""
event.app.vi_state.input_mode = InputMode.NAVIGATION
# ~IsReadOnly, because we want to stay in navigation mode for
# read-only buffers.
def _a(event: E) -> None:
event.current_buffer.cursor_position += (
event.current_buffer.document.get_cursor_right_position()
)
event.app.vi_state.input_mode = InputMode.INSERT
def _A(event: E) -> None:
event.current_buffer.cursor_position += (
event.current_buffer.document.get_end_of_line_position()
)
event.app.vi_state.input_mode = InputMode.INSERT
def _change_until_end_of_line(event: E) -> None:
"""
Change to end of line.
Same as 'c$' (which is implemented elsewhere.)
"""
buffer = event.current_buffer
deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
event.app.clipboard.set_text(deleted)
event.app.vi_state.input_mode = InputMode.INSERT
def _change_current_line(event: E) -> None: # TODO: implement 'arg'
"""
Change current line
"""
buffer = event.current_buffer
# We copy the whole line.
data = ClipboardData(buffer.document.current_line, SelectionType.LINES)
event.app.clipboard.set_data(data)
# But we delete after the whitespace
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
buffer.delete(count=buffer.document.get_end_of_line_position())
event.app.vi_state.input_mode = InputMode.INSERT
def _delete_until_end_of_line(event: E) -> None:
"""
Delete from cursor position until the end of the line.
"""
buffer = event.current_buffer
deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
event.app.clipboard.set_text(deleted)
def _delete_line(event: E) -> None:
"""
Delete line. (Or the following 'n' lines.)
"""
buffer = event.current_buffer
# Split string in before/deleted/after text.
lines = buffer.document.lines
before = "\n".join(lines[: buffer.document.cursor_position_row])
deleted = "\n".join(
lines[
buffer.document.cursor_position_row : buffer.document.cursor_position_row
+ event.arg
]
)
after = "\n".join(lines[buffer.document.cursor_position_row + event.arg :])
# Set new text.
if before and after:
before = before + "\n"
# Set text and cursor position.
buffer.document = Document(
text=before + after,
# Cursor At the start of the first 'after' line, after the leading whitespace.
cursor_position=len(before) + len(after) - len(after.lstrip(" ")),
)
# Set clipboard data
event.app.clipboard.set_data(ClipboardData(deleted, SelectionType.LINES))
def _cut(event: E) -> None:
"""
Cut selection.
('x' is not an operator.)
"""
clipboard_data = event.current_buffer.cut_selection()
event.app.clipboard.set_data(clipboard_data)
def _i(event: E) -> None:
event.app.vi_state.input_mode = InputMode.INSERT
def _I(event: E) -> None:
event.app.vi_state.input_mode = InputMode.INSERT
event.current_buffer.cursor_position += (
event.current_buffer.document.get_start_of_line_position(
after_whitespace=True
)
)
def in_block_selection() -> bool:
buff = get_app().current_buffer
return bool(
buff.selection_state and buff.selection_state.type == SelectionType.BLOCK
)
def insert_in_block_selection(event: E, after: bool = False) -> None:
"""
Insert in block selection mode.
"""
buff = event.current_buffer
# Store all cursor positions.
positions = []
if after:
def get_pos(from_to: tuple[int, int]) -> int:
return from_to[1]
else:
def get_pos(from_to: tuple[int, int]) -> int:
return from_to[0]
for i, from_to in enumerate(buff.document.selection_ranges()):
positions.append(get_pos(from_to))
if i == 0:
buff.cursor_position = get_pos(from_to)
buff.multiple_cursor_positions = positions
# Go to 'INSERT_MULTIPLE' mode.
event.app.vi_state.input_mode = InputMode.INSERT_MULTIPLE
buff.exit_selection()
def _append_after_block(event: E) -> None:
insert_in_block_selection(event, after=True)
def _join(event: E) -> None:
"""
Join lines.
"""
for i in range(event.arg):
event.current_buffer.join_next_line()
def _join_nospace(event: E) -> None:
"""
Join lines without space.
"""
for i in range(event.arg):
event.current_buffer.join_next_line(separator="")
def _join_selection(event: E) -> None:
"""
Join selected lines.
"""
event.current_buffer.join_selected_lines()
def _join_selection_nospace(event: E) -> None:
"""
Join selected lines without space.
"""
event.current_buffer.join_selected_lines(separator="")
def _paste(event: E) -> None:
"""
Paste after
"""
event.current_buffer.paste_clipboard_data(
event.app.clipboard.get_data(),
count=event.arg,
paste_mode=PasteMode.VI_AFTER,
)
def _paste_before(event: E) -> None:
"""
Paste before
"""
event.current_buffer.paste_clipboard_data(
event.app.clipboard.get_data(),
count=event.arg,
paste_mode=PasteMode.VI_BEFORE,
)
def _paste_register(event: E) -> None:
"""
Paste from named register.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
data = event.app.vi_state.named_registers.get(c)
if data:
event.current_buffer.paste_clipboard_data(
data, count=event.arg, paste_mode=PasteMode.VI_AFTER
)
def _paste_register_before(event: E) -> None:
"""
Paste (before) from named register.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
data = event.app.vi_state.named_registers.get(c)
if data:
event.current_buffer.paste_clipboard_data(
data, count=event.arg, paste_mode=PasteMode.VI_BEFORE
)
def _replace(event: E) -> None:
"""
Go to 'replace-single'-mode.
"""
event.app.vi_state.input_mode = InputMode.REPLACE_SINGLE
def _replace_mode(event: E) -> None:
"""
Go to 'replace'-mode.
"""
event.app.vi_state.input_mode = InputMode.REPLACE
def _substitute(event: E) -> None:
"""
Substitute with new text
(Delete character(s) and go to insert mode.)
"""
text = event.current_buffer.delete(count=event.arg)
event.app.clipboard.set_text(text)
event.app.vi_state.input_mode = InputMode.INSERT
def _undo(event: E) -> None:
for i in range(event.arg):
event.current_buffer.undo()
def _visual_line(event: E) -> None:
"""
Start lines selection.
"""
event.current_buffer.start_selection(selection_type=SelectionType.LINES)
def _visual_block(event: E) -> None:
"""
Enter block selection mode.
"""
event.current_buffer.start_selection(selection_type=SelectionType.BLOCK)
def _visual_line2(event: E) -> None:
"""
Exit line selection mode, or go from non line selection mode to line
selection mode.
"""
selection_state = event.current_buffer.selection_state
if selection_state is not None:
if selection_state.type != SelectionType.LINES:
selection_state.type = SelectionType.LINES
else:
event.current_buffer.exit_selection()
def _visual(event: E) -> None:
"""
Enter character selection mode.
"""
event.current_buffer.start_selection(selection_type=SelectionType.CHARACTERS)
def _visual2(event: E) -> None:
"""
Exit character selection mode, or go from non-character-selection mode
to character selection mode.
"""
selection_state = event.current_buffer.selection_state
if selection_state is not None:
if selection_state.type != SelectionType.CHARACTERS:
selection_state.type = SelectionType.CHARACTERS
else:
event.current_buffer.exit_selection()
def _visual_block2(event: E) -> None:
"""
Exit block selection mode, or go from non block selection mode to block
selection mode.
"""
selection_state = event.current_buffer.selection_state
if selection_state is not None:
if selection_state.type != SelectionType.BLOCK:
selection_state.type = SelectionType.BLOCK
else:
event.current_buffer.exit_selection()
def _visual_auto_word(event: E) -> None:
"""
Switch from visual linewise mode to visual characterwise mode.
"""
buffer = event.current_buffer
if (
buffer.selection_state
and buffer.selection_state.type == SelectionType.LINES
):
buffer.selection_state.type = SelectionType.CHARACTERS
def _delete(event: E) -> None:
"""
Delete character.
"""
buff = event.current_buffer
count = min(event.arg, len(buff.document.current_line_after_cursor))
if count:
text = event.current_buffer.delete(count=count)
event.app.clipboard.set_text(text)
def _delete_before_cursor(event: E) -> None:
buff = event.current_buffer
count = min(event.arg, len(buff.document.current_line_before_cursor))
if count:
text = event.current_buffer.delete_before_cursor(count=count)
event.app.clipboard.set_text(text)
def _yank_line(event: E) -> None:
"""
Yank the whole line.
"""
text = "\n".join(event.current_buffer.document.lines_from_current[: event.arg])
event.app.clipboard.set_data(ClipboardData(text, SelectionType.LINES))
def _next_line(event: E) -> None:
"""
Move to first non whitespace of next line
"""
buffer = event.current_buffer
buffer.cursor_position += buffer.document.get_cursor_down_position(
count=event.arg
)
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
def _prev_line(event: E) -> None:
"""
Move to first non whitespace of previous line
"""
buffer = event.current_buffer
buffer.cursor_position += buffer.document.get_cursor_up_position(
count=event.arg
)
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
def _indent(event: E) -> None:
"""
Indent lines.
"""
buffer = event.current_buffer
current_row = buffer.document.cursor_position_row
indent(buffer, current_row, current_row + event.arg)
def _unindent(event: E) -> None:
"""
Unindent lines.
"""
current_row = event.current_buffer.document.cursor_position_row
unindent(event.current_buffer, current_row, current_row + event.arg)
def _open_above(event: E) -> None:
"""
Open line above and enter insertion mode
"""
event.current_buffer.insert_line_above(copy_margin=not in_paste_mode())
event.app.vi_state.input_mode = InputMode.INSERT
def _open_below(event: E) -> None:
"""
Open line below and enter insertion mode
"""
event.current_buffer.insert_line_below(copy_margin=not in_paste_mode())
event.app.vi_state.input_mode = InputMode.INSERT
def _reverse_case(event: E) -> None:
"""
Reverse case of current character and move cursor forward.
"""
buffer = event.current_buffer
c = buffer.document.current_char
if c is not None and c != "\n":
buffer.insert_text(c.swapcase(), overwrite=True)
def _lowercase_line(event: E) -> None:
"""
Lowercase current line.
"""
buff = event.current_buffer
buff.transform_current_line(lambda s: s.lower())
def _uppercase_line(event: E) -> None:
"""
Uppercase current line.
"""
buff = event.current_buffer
buff.transform_current_line(lambda s: s.upper())
def _swapcase_line(event: E) -> None:
"""
Swap case of the current line.
"""
buff = event.current_buffer
buff.transform_current_line(lambda s: s.swapcase())
def _prev_occurence(event: E) -> None:
"""
Go to previous occurrence of this word.
"""
b = event.current_buffer
search_state = event.app.current_search_state
search_state.text = b.document.get_word_under_cursor()
search_state.direction = SearchDirection.BACKWARD
b.apply_search(search_state, count=event.arg, include_current_position=False)
def _next_occurance(event: E) -> None:
"""
Go to next occurrence of this word.
"""
b = event.current_buffer
search_state = event.app.current_search_state
search_state.text = b.document.get_word_under_cursor()
search_state.direction = SearchDirection.FORWARD
b.apply_search(search_state, count=event.arg, include_current_position=False)
def _begin_of_sentence(event: E) -> None:
# TODO: go to begin of sentence.
# XXX: should become text_object.
pass
def _end_of_sentence(event: E) -> None:
# TODO: go to end of sentence.
# XXX: should become text_object.
pass
operator = create_operator_decorator(key_bindings)
text_object = create_text_object_decorator(key_bindings)
def _unknown_text_object(event: E) -> None:
"""
Unknown key binding while waiting for a text object.
"""
event.app.output.bell()
#
# *** Operators ***
#
def create_delete_and_change_operators(
delete_only: bool, with_register: bool = False
) -> None:
"""
Delete and change operators.
:param delete_only: Create an operator that deletes, but doesn't go to insert mode.
:param with_register: Copy the deleted text to this named register instead of the clipboard.
"""
handler_keys: Iterable[str]
if with_register:
handler_keys = ('"', Keys.Any, "cd"[delete_only])
else:
handler_keys = "cd"[delete_only]
def delete_or_change_operator(event: E, text_object: TextObject) -> None:
clipboard_data = None
buff = event.current_buffer
if text_object:
new_document, clipboard_data = text_object.cut(buff)
buff.document = new_document
# Set deleted/changed text to clipboard or named register.
if clipboard_data and clipboard_data.text:
if with_register:
reg_name = event.key_sequence[1].data
if reg_name in vi_register_names:
event.app.vi_state.named_registers[reg_name] = clipboard_data
else:
event.app.clipboard.set_data(clipboard_data)
# Only go back to insert mode in case of 'change'.
if not delete_only:
event.app.vi_state.input_mode = InputMode.INSERT
create_delete_and_change_operators(False, False)
create_delete_and_change_operators(False, True)
create_delete_and_change_operators(True, False)
create_delete_and_change_operators(True, True)
def create_transform_handler(
filter: Filter, transform_func: Callable[[str], str], *a: str
) -> None:
def _(event: E, text_object: TextObject) -> None:
"""
Apply transformation (uppercase, lowercase, rot13, swap case).
"""
buff = event.current_buffer
start, end = text_object.operator_range(buff.document)
if start < end:
# Transform.
buff.transform_region(
buff.cursor_position + start,
buff.cursor_position + end,
transform_func,
)
# Move cursor
buff.cursor_position += text_object.end or text_object.start
for k, f, func in vi_transform_functions:
create_transform_handler(f, func, *k)
def _yank(event: E, text_object: TextObject) -> None:
"""
Yank operator. (Copy text.)
"""
_, clipboard_data = text_object.cut(event.current_buffer)
if clipboard_data.text:
event.app.clipboard.set_data(clipboard_data)
def _yank_to_register(event: E, text_object: TextObject) -> None:
"""
Yank selection to named register.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
_, clipboard_data = text_object.cut(event.current_buffer)
event.app.vi_state.named_registers[c] = clipboard_data
def _indent_text_object(event: E, text_object: TextObject) -> None:
"""
Indent.
"""
buff = event.current_buffer
from_, to = text_object.get_line_numbers(buff)
indent(buff, from_, to + 1, count=event.arg)
def _unindent_text_object(event: E, text_object: TextObject) -> None:
"""
Unindent.
"""
buff = event.current_buffer
from_, to = text_object.get_line_numbers(buff)
unindent(buff, from_, to + 1, count=event.arg)
def _reshape(event: E, text_object: TextObject) -> None:
"""
Reshape text.
"""
buff = event.current_buffer
from_, to = text_object.get_line_numbers(buff)
reshape_text(buff, from_, to)
#
# *** Text objects ***
#
def _b(event: E) -> TextObject:
"""
Move one word or token left.
"""
return TextObject(
event.current_buffer.document.find_start_of_previous_word(count=event.arg)
or 0
)
def _B(event: E) -> TextObject:
"""
Move one non-blank word left
"""
return TextObject(
event.current_buffer.document.find_start_of_previous_word(
count=event.arg, WORD=True
)
or 0
)
def _dollar(event: E) -> TextObject:
"""
'c$', 'd$' and '$': Delete/change/move until end of line.
"""
return TextObject(event.current_buffer.document.get_end_of_line_position())
def _word_forward(event: E) -> TextObject:
"""
'word' forward. 'cw', 'dw', 'w': Delete/change/move one word.
"""
return TextObject(
event.current_buffer.document.find_next_word_beginning(count=event.arg)
or event.current_buffer.document.get_end_of_document_position()
)
def _WORD_forward(event: E) -> TextObject:
"""
'WORD' forward. 'cW', 'dW', 'W': Delete/change/move one WORD.
"""
return TextObject(
event.current_buffer.document.find_next_word_beginning(
count=event.arg, WORD=True
)
or event.current_buffer.document.get_end_of_document_position()
)
def _end_of_word(event: E) -> TextObject:
"""
End of 'word': 'ce', 'de', 'e'
"""
end = event.current_buffer.document.find_next_word_ending(count=event.arg)
return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
def _end_of_WORD(event: E) -> TextObject:
"""
End of 'WORD': 'cE', 'dE', 'E'
"""
end = event.current_buffer.document.find_next_word_ending(
count=event.arg, WORD=True
)
return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
def _inner_word(event: E) -> TextObject:
"""
Inner 'word': ciw and diw
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word()
return TextObject(start, end)
def _a_word(event: E) -> TextObject:
"""
A 'word': caw and daw
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word(
include_trailing_whitespace=True
)
return TextObject(start, end)
def _inner_WORD(event: E) -> TextObject:
"""
Inner 'WORD': ciW and diW
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word(
WORD=True
)
return TextObject(start, end)
def _a_WORD(event: E) -> TextObject:
"""
A 'WORD': caw and daw
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word(
WORD=True, include_trailing_whitespace=True
)
return TextObject(start, end)
def _paragraph(event: E) -> TextObject:
"""
Auto paragraph.
"""
start = event.current_buffer.document.start_of_paragraph()
end = event.current_buffer.document.end_of_paragraph(count=event.arg)
return TextObject(start, end)
def _start_of_line(event: E) -> TextObject:
"""'c^', 'd^' and '^': Soft start of line, after whitespace."""
return TextObject(
event.current_buffer.document.get_start_of_line_position(
after_whitespace=True
)
)
def _hard_start_of_line(event: E) -> TextObject:
"""
'c0', 'd0': Hard start of line, before whitespace.
(The move '0' key is implemented elsewhere, because a '0' could also change the `arg`.)
"""
return TextObject(
event.current_buffer.document.get_start_of_line_position(
after_whitespace=False
)
)
def create_ci_ca_handles(
ci_start: str, ci_end: str, inner: bool, key: str | None = None
) -> None:
# TODO: 'dat', 'dit', (tags (like xml)
"""
Delete/Change string between this start and stop character. But keep these characters.
This implements all the ci", ci<, ci{, ci(, di", di<, ca", ca<, ... combinations.
"""
def handler(event: E) -> TextObject:
if ci_start == ci_end:
# Quotes
start = event.current_buffer.document.find_backwards(
ci_start, in_current_line=False
)
end = event.current_buffer.document.find(ci_end, in_current_line=False)
else:
# Brackets
start = event.current_buffer.document.find_enclosing_bracket_left(
ci_start, ci_end
)
end = event.current_buffer.document.find_enclosing_bracket_right(
ci_start, ci_end
)
if start is not None and end is not None:
offset = 0 if inner else 1
return TextObject(start + 1 - offset, end + offset)
else:
# Nothing found.
return TextObject(0)
if key is None:
text_object("ai"[inner], ci_start, no_move_handler=True)(handler)
text_object("ai"[inner], ci_end, no_move_handler=True)(handler)
else:
text_object("ai"[inner], key, no_move_handler=True)(handler)
for inner in (False, True):
for ci_start, ci_end in [
('"', '"'),
("'", "'"),
("`", "`"),
("[", "]"),
("<", ">"),
("{", "}"),
("(", ")"),
]:
create_ci_ca_handles(ci_start, ci_end, inner)
create_ci_ca_handles("(", ")", inner, "b") # 'dab', 'dib'
create_ci_ca_handles("{", "}", inner, "B") # 'daB', 'diB'
def _previous_section(event: E) -> TextObject:
"""
Move to previous blank-line separated section.
Implements '{', 'c{', 'd{', 'y{'
"""
index = event.current_buffer.document.start_of_paragraph(
count=event.arg, before=True
)
return TextObject(index)
def _next_section(event: E) -> TextObject:
"""
Move to next blank-line separated section.
Implements '}', 'c}', 'd}', 'y}'
"""
index = event.current_buffer.document.end_of_paragraph(
count=event.arg, after=True
)
return TextObject(index)
def _next_occurence(event: E) -> TextObject:
"""
Go to next occurrence of character. Typing 'fx' will move the
cursor to the next occurrence of character. 'x'.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, False)
match = event.current_buffer.document.find(
event.data, in_current_line=True, count=event.arg
)
if match:
return TextObject(match, type=TextObjectType.INCLUSIVE)
else:
return TextObject(0)
def _previous_occurance(event: E) -> TextObject:
"""
Go to previous occurrence of character. Typing 'Fx' will move the
cursor to the previous occurrence of character. 'x'.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, True)
return TextObject(
event.current_buffer.document.find_backwards(
event.data, in_current_line=True, count=event.arg
)
or 0
)
def _t(event: E) -> TextObject:
"""
Move right to the next occurrence of c, then one char backward.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, False)
match = event.current_buffer.document.find(
event.data, in_current_line=True, count=event.arg
)
if match:
return TextObject(match - 1, type=TextObjectType.INCLUSIVE)
else:
return TextObject(0)
def _T(event: E) -> TextObject:
"""
Move left to the previous occurrence of c, then one char forward.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, True)
match = event.current_buffer.document.find_backwards(
event.data, in_current_line=True, count=event.arg
)
return TextObject(match + 1 if match else 0)
def repeat(reverse: bool) -> None:
"""
Create ',' and ';' commands.
"""
def _(event: E) -> TextObject:
"""
Repeat the last 'f'/'F'/'t'/'T' command.
"""
pos: int | None = 0
vi_state = event.app.vi_state
type = TextObjectType.EXCLUSIVE
if vi_state.last_character_find:
char = vi_state.last_character_find.character
backwards = vi_state.last_character_find.backwards
if reverse:
backwards = not backwards
if backwards:
pos = event.current_buffer.document.find_backwards(
char, in_current_line=True, count=event.arg
)
else:
pos = event.current_buffer.document.find(
char, in_current_line=True, count=event.arg
)
type = TextObjectType.INCLUSIVE
if pos:
return TextObject(pos, type=type)
else:
return TextObject(0)
repeat(True)
repeat(False)
def _left(event: E) -> TextObject:
"""
Implements 'ch', 'dh', 'h': Cursor left.
"""
return TextObject(
event.current_buffer.document.get_cursor_left_position(count=event.arg)
)
# Note: We also need `no_selection_handler`, because we in
# selection mode, we prefer the other 'j' binding that keeps
# `buffer.preferred_column`.
def _down(event: E) -> TextObject:
"""
Implements 'cj', 'dj', 'j', ... Cursor up.
"""
return TextObject(
event.current_buffer.document.get_cursor_down_position(count=event.arg),
type=TextObjectType.LINEWISE,
)
def _up(event: E) -> TextObject:
"""
Implements 'ck', 'dk', 'k', ... Cursor up.
"""
return TextObject(
event.current_buffer.document.get_cursor_up_position(count=event.arg),
type=TextObjectType.LINEWISE,
)
def _right(event: E) -> TextObject:
"""
Implements 'cl', 'dl', 'l', 'c ', 'd ', ' '. Cursor right.
"""
return TextObject(
event.current_buffer.document.get_cursor_right_position(count=event.arg)
)
def _top_of_screen(event: E) -> TextObject:
"""
Moves to the start of the visible region. (Below the scroll offset.)
Implements 'cH', 'dH', 'H'.
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the start of the visible area.
pos = (
b.document.translate_row_col_to_index(
w.render_info.first_visible_line(after_scroll_offset=True), 0
)
- b.cursor_position
)
else:
# Otherwise, move to the start of the input.
pos = -len(b.document.text_before_cursor)
return TextObject(pos, type=TextObjectType.LINEWISE)
def _middle_of_screen(event: E) -> TextObject:
"""
Moves cursor to the vertical center of the visible region.
Implements 'cM', 'dM', 'M'.
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the center of the visible area.
pos = (
b.document.translate_row_col_to_index(
w.render_info.center_visible_line(), 0
)
- b.cursor_position
)
else:
# Otherwise, move to the start of the input.
pos = -len(b.document.text_before_cursor)
return TextObject(pos, type=TextObjectType.LINEWISE)
def _end_of_screen(event: E) -> TextObject:
"""
Moves to the end of the visible region. (Above the scroll offset.)
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the end of the visible area.
pos = (
b.document.translate_row_col_to_index(
w.render_info.last_visible_line(before_scroll_offset=True), 0
)
- b.cursor_position
)
else:
# Otherwise, move to the end of the input.
pos = len(b.document.text_after_cursor)
return TextObject(pos, type=TextObjectType.LINEWISE)
def _search_next(event: E) -> TextObject:
"""
Search next.
"""
buff = event.current_buffer
search_state = event.app.current_search_state
cursor_position = buff.get_search_position(
search_state, include_current_position=False, count=event.arg
)
return TextObject(cursor_position - buff.cursor_position)
def _search_next2(event: E) -> None:
"""
Search next in navigation mode. (This goes through the history.)
"""
search_state = event.app.current_search_state
event.current_buffer.apply_search(
search_state, include_current_position=False, count=event.arg
)
def _search_previous(event: E) -> TextObject:
"""
Search previous.
"""
buff = event.current_buffer
search_state = event.app.current_search_state
cursor_position = buff.get_search_position(
~search_state, include_current_position=False, count=event.arg
)
return TextObject(cursor_position - buff.cursor_position)
def _search_previous2(event: E) -> None:
"""
Search previous in navigation mode. (This goes through the history.)
"""
search_state = event.app.current_search_state
event.current_buffer.apply_search(
~search_state, include_current_position=False, count=event.arg
)
def _scroll_top(event: E) -> None:
"""
Scrolls the window to makes the current line the first line in the visible region.
"""
b = event.current_buffer
event.app.layout.current_window.vertical_scroll = b.document.cursor_position_row
def _scroll_bottom(event: E) -> None:
"""
Scrolls the window to makes the current line the last line in the visible region.
"""
# We can safely set the scroll offset to zero; the Window will make
# sure that it scrolls at least enough to make the cursor visible
# again.
event.app.layout.current_window.vertical_scroll = 0
def _scroll_center(event: E) -> None:
"""
Center Window vertically around cursor.
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
info = w.render_info
# Calculate the offset that we need in order to position the row
# containing the cursor in the center.
scroll_height = info.window_height // 2
y = max(0, b.document.cursor_position_row - 1)
height = 0
while y > 0:
line_height = info.get_height_for_line(y)
if height + line_height < scroll_height:
height += line_height
y -= 1
else:
break
w.vertical_scroll = y
def _goto_corresponding_bracket(event: E) -> TextObject:
"""
Implements 'c%', 'd%', '%, 'y%' (Move to corresponding bracket.)
If an 'arg' has been given, go this this % position in the file.
"""
buffer = event.current_buffer
if event._arg:
# If 'arg' has been given, the meaning of % is to go to the 'x%'
# row in the file.
if 0 < event.arg <= 100:
absolute_index = buffer.document.translate_row_col_to_index(
int((event.arg * buffer.document.line_count - 1) / 100), 0
)
return TextObject(
absolute_index - buffer.document.cursor_position,
type=TextObjectType.LINEWISE,
)
else:
return TextObject(0) # Do nothing.
else:
# Move to the corresponding opening/closing bracket (()'s, []'s and {}'s).
match = buffer.document.find_matching_bracket_position()
if match:
return TextObject(match, type=TextObjectType.INCLUSIVE)
else:
return TextObject(0)
def _to_column(event: E) -> TextObject:
"""
Move to the n-th column (you may specify the argument n by typing it on
number keys, for example, 20|).
"""
return TextObject(
event.current_buffer.document.get_column_cursor_position(event.arg - 1)
)
def _goto_first_line(event: E) -> TextObject:
"""
Go to the start of the very first line.
Implements 'gg', 'cgg', 'ygg'
"""
d = event.current_buffer.document
if event._arg:
# Move to the given line.
return TextObject(
d.translate_row_col_to_index(event.arg - 1, 0) - d.cursor_position,
type=TextObjectType.LINEWISE,
)
else:
# Move to the top of the input.
return TextObject(
d.get_start_of_document_position(), type=TextObjectType.LINEWISE
)
def _goto_last_line(event: E) -> TextObject:
"""
Go to last non-blank of line.
'g_', 'cg_', 'yg_', etc..
"""
return TextObject(
event.current_buffer.document.last_non_blank_of_current_line_position(),
type=TextObjectType.INCLUSIVE,
)
def _ge(event: E) -> TextObject:
"""
Go to last character of previous word.
'ge', 'cge', 'yge', etc..
"""
prev_end = event.current_buffer.document.find_previous_word_ending(
count=event.arg
)
return TextObject(
prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE
)
def _gE(event: E) -> TextObject:
"""
Go to last character of previous WORD.
'gE', 'cgE', 'ygE', etc..
"""
prev_end = event.current_buffer.document.find_previous_word_ending(
count=event.arg, WORD=True
)
return TextObject(
prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE
)
def _gm(event: E) -> TextObject:
"""
Like g0, but half a screenwidth to the right. (Or as much as possible.)
"""
w = event.app.layout.current_window
buff = event.current_buffer
if w and w.render_info:
width = w.render_info.window_width
start = buff.document.get_start_of_line_position(after_whitespace=False)
start += int(min(width / 2, len(buff.document.current_line)))
return TextObject(start, type=TextObjectType.INCLUSIVE)
return TextObject(0)
def _last_line(event: E) -> TextObject:
"""
Go to the end of the document. (If no arg has been given.)
"""
buf = event.current_buffer
return TextObject(
buf.document.translate_row_col_to_index(buf.document.line_count - 1, 0)
- buf.cursor_position,
type=TextObjectType.LINEWISE,
)
#
# *** Other ***
#
def _to_nth_history_line(event: E) -> None:
"""
If an argument is given, move to this line in the history. (for
example, 15G)
"""
event.current_buffer.go_to_history(event.arg - 1)
for n in "123456789":
n,
filter=vi_navigation_mode
| vi_selection_mode
| vi_waiting_for_text_object_mode,
)
def _arg(event: E) -> None:
"""
Always handle numerics in navigation mode as arg.
"""
event.append_to_arg_count(event.data)
"0",
filter=(
vi_navigation_mode | vi_selection_mode | vi_waiting_for_text_object_mode
)
& has_arg,
)
def _0_arg(event: E) -> None:
"""
Zero when an argument was already give.
"""
event.append_to_arg_count(event.data)
def _insert_text(event: E) -> None:
"""
Insert data at cursor position.
"""
event.current_buffer.insert_text(event.data, overwrite=True)
def _replace_single(event: E) -> None:
"""
Replace single character at cursor position.
"""
event.current_buffer.insert_text(event.data, overwrite=True)
event.current_buffer.cursor_position -= 1
event.app.vi_state.input_mode = InputMode.NAVIGATION
Keys.Any,
filter=vi_insert_multiple_mode,
save_before=(lambda e: not e.is_repeat),
)
def _insert_text_multiple_cursors(event: E) -> None:
"""
Insert data at multiple cursor positions at once.
(Usually a result of pressing 'I' or 'A' in block-selection mode.)
"""
buff = event.current_buffer
original_text = buff.text
# Construct new text.
text = []
p = 0
for p2 in buff.multiple_cursor_positions:
text.append(original_text[p:p2])
text.append(event.data)
p = p2
text.append(original_text[p:])
# Shift all cursor positions.
new_cursor_positions = [
pos + i + 1 for i, pos in enumerate(buff.multiple_cursor_positions)
]
# Set result.
buff.text = "".join(text)
buff.multiple_cursor_positions = new_cursor_positions
buff.cursor_position += 1
def _delete_before_multiple_cursors(event: E) -> None:
"""
Backspace, using multiple cursors.
"""
buff = event.current_buffer
original_text = buff.text
# Construct new text.
deleted_something = False
text = []
p = 0
for p2 in buff.multiple_cursor_positions:
if p2 > 0 and original_text[p2 - 1] != "\n": # Don't delete across lines.
text.append(original_text[p : p2 - 1])
deleted_something = True
else:
text.append(original_text[p:p2])
p = p2
text.append(original_text[p:])
if deleted_something:
# Shift all cursor positions.
lengths = [len(part) for part in text[:-1]]
new_cursor_positions = list(accumulate(lengths))
# Set result.
buff.text = "".join(text)
buff.multiple_cursor_positions = new_cursor_positions
buff.cursor_position -= 1
else:
event.app.output.bell()
def _delete_after_multiple_cursors(event: E) -> None:
"""
Delete, using multiple cursors.
"""
buff = event.current_buffer
original_text = buff.text
# Construct new text.
deleted_something = False
text = []
new_cursor_positions = []
p = 0
for p2 in buff.multiple_cursor_positions:
text.append(original_text[p:p2])
if p2 >= len(original_text) or original_text[p2] == "\n":
# Don't delete across lines.
p = p2
else:
p = p2 + 1
deleted_something = True
text.append(original_text[p:])
if deleted_something:
# Shift all cursor positions.
lengths = [len(part) for part in text[:-1]]
new_cursor_positions = list(accumulate(lengths))
# Set result.
buff.text = "".join(text)
buff.multiple_cursor_positions = new_cursor_positions
else:
event.app.output.bell()
def _left_multiple(event: E) -> None:
"""
Move all cursors to the left.
(But keep all cursors on the same line.)
"""
buff = event.current_buffer
new_positions = []
for p in buff.multiple_cursor_positions:
if buff.document.translate_index_to_position(p)[1] > 0:
p -= 1
new_positions.append(p)
buff.multiple_cursor_positions = new_positions
if buff.document.cursor_position_col > 0:
buff.cursor_position -= 1
def _right_multiple(event: E) -> None:
"""
Move all cursors to the right.
(But keep all cursors on the same line.)
"""
buff = event.current_buffer
new_positions = []
for p in buff.multiple_cursor_positions:
row, column = buff.document.translate_index_to_position(p)
if column < len(buff.document.lines[row]):
p += 1
new_positions.append(p)
buff.multiple_cursor_positions = new_positions
if not buff.document.is_cursor_at_the_end_of_line:
buff.cursor_position += 1
def _updown_multiple(event: E) -> None:
"""
Ignore all up/down key presses when in multiple cursor mode.
"""
def _complete_line(event: E) -> None:
"""
Pressing the ControlX - ControlL sequence in Vi mode does line
completion based on the other lines in the document and the history.
"""
event.current_buffer.start_history_lines_completion()
def _complete_filename(event: E) -> None:
"""
Complete file names.
"""
# TODO
pass
def _digraph(event: E) -> None:
"""
Go into digraph mode.
"""
event.app.vi_state.waiting_for_digraph = True
def digraph_symbol_1_given() -> bool:
return get_app().vi_state.digraph_symbol1 is not None
def _digraph1(event: E) -> None:
"""
First digraph symbol.
"""
event.app.vi_state.digraph_symbol1 = event.data
def _create_digraph(event: E) -> None:
"""
Insert digraph.
"""
try:
# Lookup.
code: tuple[str, str] = (
event.app.vi_state.digraph_symbol1 or "",
event.data,
)
if code not in DIGRAPHS:
code = code[::-1] # Try reversing.
symbol = DIGRAPHS[code]
except KeyError:
# Unknown digraph.
event.app.output.bell()
else:
# Insert digraph.
overwrite = event.app.vi_state.input_mode == InputMode.REPLACE
event.current_buffer.insert_text(chr(symbol), overwrite=overwrite)
event.app.vi_state.waiting_for_digraph = False
finally:
event.app.vi_state.waiting_for_digraph = False
event.app.vi_state.digraph_symbol1 = None
def _quick_normal_mode(event: E) -> None:
"""
Go into normal mode for one single action.
"""
event.app.vi_state.temporary_navigation_mode = True
def _start_macro(event: E) -> None:
"""
Start recording macro.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
vi_state = event.app.vi_state
vi_state.recording_register = c
vi_state.current_recording = ""
def _stop_macro(event: E) -> None:
"""
Stop recording macro.
"""
vi_state = event.app.vi_state
# Store and stop recording.
if vi_state.recording_register:
vi_state.named_registers[vi_state.recording_register] = ClipboardData(
vi_state.current_recording
)
vi_state.recording_register = None
vi_state.current_recording = ""
def _execute_macro(event: E) -> None:
"""
Execute macro.
Notice that we pass `record_in_macro=False`. This ensures that the `@x`
keys don't appear in the recording itself. This function inserts the
body of the called macro back into the KeyProcessor, so these keys will
be added later on to the macro of their handlers have
`record_in_macro=True`.
"""
# Retrieve macro.
c = event.key_sequence[1].data
try:
macro = event.app.vi_state.named_registers[c]
except KeyError:
return
# Expand macro (which is a string in the register), in individual keys.
# Use vt100 parser for this.
keys: list[KeyPress] = []
parser = Vt100Parser(keys.append)
parser.feed(macro.text)
parser.flush()
# Now feed keys back to the input processor.
for _ in range(event.arg):
event.app.key_processor.feed_multiple(keys, first=True)
return ConditionalKeyBindings(key_bindings, vi_mode)
def load_vi_search_bindings() -> KeyBindingsBase:
key_bindings = KeyBindings()
handle = key_bindings.add
from . import search
# Vi-style forward search.
handle(
"/",
filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
)(search.start_forward_incremental_search)
handle(
"?",
filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
)(search.start_forward_incremental_search)
handle("c-s")(search.start_forward_incremental_search)
# Vi-style backward search.
handle(
"?",
filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
)(search.start_reverse_incremental_search)
handle(
"/",
filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
)(search.start_reverse_incremental_search)
handle("c-r")(search.start_reverse_incremental_search)
# Apply the search. (At the / or ? prompt.)
handle("enter", filter=is_searching)(search.accept_search)
handle("c-r", filter=is_searching)(search.reverse_incremental_search)
handle("c-s", filter=is_searching)(search.forward_incremental_search)
handle("c-c")(search.abort_search)
handle("c-g")(search.abort_search)
handle("backspace", filter=search_buffer_is_empty)(search.abort_search)
# Handle escape. This should accept the search, just like readline.
# `abort_search` would be a meaningful alternative.
handle("escape")(search.accept_search)
return ConditionalKeyBindings(key_bindings, vi_mode)
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
class Tuple(BaseTypingInstance):
def _is_homogenous(self):
# To specify a variable-length tuple of homogeneous type, Tuple[T, ...]
# is used.
return self._generics_manager.is_homogenous_tuple()
def py__simple_getitem__(self, index):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
else:
if isinstance(index, int):
return self._generics_manager.get_index_and_execute(index)
debug.dbg('The getitem type on Tuple was %s' % index)
return NO_VALUES
def py__iter__(self, contextualized_node=None):
if self._is_homogenous():
yield LazyKnownValues(self._generics_manager.get_index_and_execute(0))
else:
for v in self._generics_manager.to_tuple():
yield LazyKnownValues(v.execute_annotation())
def py__getitem__(self, index_value_set, contextualized_node):
if self._is_homogenous():
return self._generics_manager.get_index_and_execute(0)
return ValueSet.from_sets(
self._generics_manager.to_tuple()
).execute_annotation()
def _get_wrapped_value(self):
tuple_, = self.inference_state.builtins_module \
.py__getattribute__('tuple').execute_annotation()
return tuple_
def name(self):
return self._wrapped_value.name
def infer_type_vars(self, value_set):
# Circular
from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts
value_set = value_set.filter(
lambda x: x.py__name__().lower() == 'tuple',
)
if self._is_homogenous():
# The parameter annotation is of the form `Tuple[T, ...]`,
# so we treat the incoming tuple like a iterable sequence
# rather than a positional container of elements.
return self._class_value.get_generics()[0].infer_type_vars(
value_set.merge_types_of_iterate(),
)
else:
# The parameter annotation has only explicit type parameters
# (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we
# treat the incoming values as needing to match the annotation
# exactly, just as we would for non-tuple annotations.
type_var_dict = {}
for element in value_set:
try:
method = element.get_annotated_class_object
except AttributeError:
# This might still happen, because the tuple name matching
# above is not 100% correct, so just catch the remaining
# cases here.
continue
py_class = method()
merge_type_var_dicts(
type_var_dict,
merge_pairwise_generics(self._class_value, py_class),
)
return type_var_dict
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]: ...
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
def indent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
"""
Indent text of a :class:`.Buffer` object.
"""
current_row = buffer.document.cursor_position_row
line_range = range(from_row, to_row)
# Apply transformation.
new_text = buffer.transform_lines(line_range, lambda l: " " * count + l)
buffer.document = Document(
new_text, Document(new_text).translate_row_col_to_index(current_row, 0)
)
# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
def unindent(buffer: Buffer, from_row: int, to_row: int, count: int = 1) -> None:
"""
Unindent text of a :class:`.Buffer` object.
"""
current_row = buffer.document.cursor_position_row
line_range = range(from_row, to_row)
def transform(text: str) -> str:
remove = " " * count
if text.startswith(remove):
return text[len(remove) :]
else:
return text.lstrip()
# Apply transformation.
new_text = buffer.transform_lines(line_range, transform)
buffer.document = Document(
new_text, Document(new_text).translate_row_col_to_index(current_row, 0)
)
# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
def reshape_text(buffer: Buffer, from_row: int, to_row: int) -> None:
"""
Reformat text, taking the width into account.
`to_row` is included.
(Vi 'gq' operator.)
"""
lines = buffer.text.splitlines(True)
lines_before = lines[:from_row]
lines_after = lines[to_row + 1 :]
lines_to_reformat = lines[from_row : to_row + 1]
if lines_to_reformat:
# Take indentation from the first line.
match = re.search(r"^\s*", lines_to_reformat[0])
length = match.end() if match else 0 # `match` can't be None, actually.
indent = lines_to_reformat[0][:length].replace("\n", "")
# Now, take all the 'words' from the lines to be reshaped.
words = "".join(lines_to_reformat).split()
# And reshape.
width = (buffer.text_width or 80) - len(indent)
reshaped_text = [indent]
current_width = 0
for w in words:
if current_width:
if len(w) + current_width + 1 > width:
reshaped_text.append("\n")
reshaped_text.append(indent)
current_width = 0
else:
reshaped_text.append(" ")
current_width += 1
reshaped_text.append(w)
current_width += len(w)
if reshaped_text[-1] != "\n":
reshaped_text.append("\n")
# Apply result.
buffer.document = Document(
text="".join(lines_before + reshaped_text + lines_after),
cursor_position=len("".join(lines_before + reshaped_text)),
)
class Document:
"""
This is a immutable class around the text and cursor position, and contains
methods for querying this data, e.g. to give the text before the cursor.
This class is usually instantiated by a :class:`~prompt_toolkit.buffer.Buffer`
object, and accessed as the `document` property of that class.
:param text: string
:param cursor_position: int
:param selection: :class:`.SelectionState`
"""
__slots__ = ("_text", "_cursor_position", "_selection", "_cache")
def __init__(
self,
text: str = "",
cursor_position: int | None = None,
selection: SelectionState | None = None,
) -> None:
# Check cursor position. It can also be right after the end. (Where we
# insert text.)
assert cursor_position is None or cursor_position <= len(text), AssertionError(
f"cursor_position={cursor_position!r}, len_text={len(text)!r}"
)
# By default, if no cursor position was given, make sure to put the
# cursor position is at the end of the document. This is what makes
# sense in most places.
if cursor_position is None:
cursor_position = len(text)
# Keep these attributes private. A `Document` really has to be
# considered to be immutable, because otherwise the caching will break
# things. Because of that, we wrap these into read-only properties.
self._text = text
self._cursor_position = cursor_position
self._selection = selection
# Cache for lines/indexes. (Shared with other Document instances that
# contain the same text.
try:
self._cache = _text_to_document_cache[self.text]
except KeyError:
self._cache = _DocumentCache()
_text_to_document_cache[self.text] = self._cache
# XX: For some reason, above, we can't use 'WeakValueDictionary.setdefault'.
# This fails in Pypy3. `self._cache` becomes None, because that's what
# 'setdefault' returns.
# self._cache = _text_to_document_cache.setdefault(self.text, _DocumentCache())
# assert self._cache
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.text!r}, {self.cursor_position!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Document):
return False
return (
self.text == other.text
and self.cursor_position == other.cursor_position
and self.selection == other.selection
)
def text(self) -> str:
"The document text."
return self._text
def cursor_position(self) -> int:
"The document cursor position."
return self._cursor_position
def selection(self) -> SelectionState | None:
":class:`.SelectionState` object."
return self._selection
def current_char(self) -> str:
"""Return character under cursor or an empty string."""
return self._get_char_relative_to_cursor(0) or ""
def char_before_cursor(self) -> str:
"""Return character before the cursor or an empty string."""
return self._get_char_relative_to_cursor(-1) or ""
def text_before_cursor(self) -> str:
return self.text[: self.cursor_position :]
def text_after_cursor(self) -> str:
return self.text[self.cursor_position :]
def current_line_before_cursor(self) -> str:
"""Text from the start of the line until the cursor."""
_, _, text = self.text_before_cursor.rpartition("\n")
return text
def current_line_after_cursor(self) -> str:
"""Text from the cursor until the end of the line."""
text, _, _ = self.text_after_cursor.partition("\n")
return text
def lines(self) -> list[str]:
"""
Array of all the lines.
"""
# Cache, because this one is reused very often.
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split("\n"))
return self._cache.lines
def _line_start_indexes(self) -> list[int]:
"""
Array pointing to the start indexes of all the lines.
"""
# Cache, because this is often reused. (If it is used, it's often used
# many times. And this has to be fast for editing big documents!)
if self._cache.line_indexes is None:
# Create list of line lengths.
line_lengths = map(len, self.lines)
# Calculate cumulative sums.
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
# Remove the last item. (This is not a new line.)
if len(indexes) > 1:
indexes.pop()
self._cache.line_indexes = indexes
return self._cache.line_indexes
def lines_from_current(self) -> list[str]:
"""
Array of the lines starting from the current line, until the last line.
"""
return self.lines[self.cursor_position_row :]
def line_count(self) -> int:
r"""Return the number of lines in this document. If the document ends
with a trailing \n, that counts as the beginning of a new line."""
return len(self.lines)
def current_line(self) -> str:
"""Return the text on the line where the cursor is. (when the input
consists of just one line, it equals `text`."""
return self.current_line_before_cursor + self.current_line_after_cursor
def leading_whitespace_in_current_line(self) -> str:
"""The leading whitespace in the left margin of the current line."""
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length]
def _get_char_relative_to_cursor(self, offset: int = 0) -> str:
"""
Return character relative to cursor position, or empty string
"""
try:
return self.text[self.cursor_position + offset]
except IndexError:
return ""
def on_first_line(self) -> bool:
"""
True when we are at the first line.
"""
return self.cursor_position_row == 0
def on_last_line(self) -> bool:
"""
True when we are at the last line.
"""
return self.cursor_position_row == self.line_count - 1
def cursor_position_row(self) -> int:
"""
Current row. (0-based.)
"""
row, _ = self._find_line_start_index(self.cursor_position)
return row
def cursor_position_col(self) -> int:
"""
Current column. (0-based.)
"""
# (Don't use self.text_before_cursor to calculate this. Creating
# substrings and doing rsplit is too expensive for getting the cursor
# position.)
_, line_start_index = self._find_line_start_index(self.cursor_position)
return self.cursor_position - line_start_index
def _find_line_start_index(self, index: int) -> tuple[int, int]:
"""
For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple.
"""
indexes = self._line_start_indexes
pos = bisect.bisect_right(indexes, index) - 1
return pos, indexes[pos]
def translate_index_to_position(self, index: int) -> tuple[int, int]:
"""
Given an index for the text, return the corresponding (row, col) tuple.
(0-based. Returns (0, 0) for index=0.)
"""
# Find start of this line.
row, row_index = self._find_line_start_index(index)
col = index - row_index
return row, col
def translate_row_col_to_index(self, row: int, col: int) -> int:
"""
Given a (row, col) tuple, return the corresponding index.
(Row and col params are 0-based.)
Negative row/col values are turned into zero.
"""
try:
result = self._line_start_indexes[row]
line = self.lines[row]
except IndexError:
if row < 0:
result = self._line_start_indexes[0]
line = self.lines[0]
else:
result = self._line_start_indexes[-1]
line = self.lines[-1]
result += max(0, min(col, len(line)))
# Keep in range. (len(self.text) is included, because the cursor can be
# right after the end of the text as well.)
result = max(0, min(result, len(self.text)))
return result
def is_cursor_at_the_end(self) -> bool:
"""True when the cursor is at the end of the text."""
return self.cursor_position == len(self.text)
def is_cursor_at_the_end_of_line(self) -> bool:
"""True when the cursor is at the end of this line."""
return self.current_char in ("\n", "")
def has_match_at_current_position(self, sub: str) -> bool:
"""
`True` when this substring is found at the cursor position.
"""
return self.text.find(sub, self.cursor_position) == self.cursor_position
def find(
self,
sub: str,
in_current_line: bool = False,
include_current_position: bool = False,
ignore_case: bool = False,
count: int = 1,
) -> int | None:
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurrence.
"""
assert isinstance(ignore_case, bool)
if in_current_line:
text = self.current_line_after_cursor
else:
text = self.text_after_cursor
if not include_current_position:
if len(text) == 0:
return None # (Otherwise, we always get a match for the empty string.)
else:
text = text[1:]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub), text, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
if include_current_position:
return match.start(0)
else:
return match.start(0) + 1
except StopIteration:
pass
return None
def find_all(self, sub: str, ignore_case: bool = False) -> list[int]:
"""
Find all occurrences of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)]
def find_backwards(
self,
sub: str,
in_current_line: bool = False,
ignore_case: bool = False,
count: int = 1,
) -> int | None:
"""
Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurrence.
"""
if in_current_line:
before_cursor = self.current_line_before_cursor[::-1]
else:
before_cursor = self.text_before_cursor[::-1]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.start(0) - len(sub)
except StopIteration:
pass
return None
def get_word_before_cursor(
self, WORD: bool = False, pattern: Pattern[str] | None = None
) -> str:
"""
Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string.
:param pattern: (None or compiled regex). When given, use this regex
pattern.
"""
if self._is_word_before_cursor_complete(WORD=WORD, pattern=pattern):
# Space before the cursor or no text before cursor.
return ""
text_before_cursor = self.text_before_cursor
start = self.find_start_of_previous_word(WORD=WORD, pattern=pattern) or 0
return text_before_cursor[len(text_before_cursor) + start :]
def _is_word_before_cursor_complete(
self, WORD: bool = False, pattern: Pattern[str] | None = None
) -> bool:
if pattern:
return self.find_start_of_previous_word(WORD=WORD, pattern=pattern) is None
else:
return (
self.text_before_cursor == "" or self.text_before_cursor[-1:].isspace()
)
def find_start_of_previous_word(
self, count: int = 1, WORD: bool = False, pattern: Pattern[str] | None = None
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found.
:param pattern: (None or compiled regex). When given, use this regex
pattern.
"""
assert not (WORD and pattern)
# Reverse the text before the cursor, in order to do an efficient
# backwards search.
text_before_cursor = self.text_before_cursor[::-1]
if pattern:
regex = pattern
elif WORD:
regex = _FIND_BIG_WORD_RE
else:
regex = _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.end(0)
except StopIteration:
pass
return None
def find_boundaries_of_current_word(
self,
WORD: bool = False,
include_leading_whitespace: bool = False,
include_trailing_whitespace: bool = False,
) -> tuple[int, int]:
"""
Return the relative boundaries (startpos, endpos) of the current word under the
cursor. (This is at the current line, because line boundaries obviously
don't belong to any word.)
If not on a word, this returns (0,0)
"""
text_before_cursor = self.current_line_before_cursor[::-1]
text_after_cursor = self.current_line_after_cursor
def get_regex(include_whitespace: bool) -> Pattern[str]:
return {
(False, False): _FIND_CURRENT_WORD_RE,
(False, True): _FIND_CURRENT_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
(True, False): _FIND_CURRENT_BIG_WORD_RE,
(True, True): _FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
}[(WORD, include_whitespace)]
match_before = get_regex(include_leading_whitespace).search(text_before_cursor)
match_after = get_regex(include_trailing_whitespace).search(text_after_cursor)
# When there is a match before and after, and we're not looking for
# WORDs, make sure that both the part before and after the cursor are
# either in the [a-zA-Z_] alphabet or not. Otherwise, drop the part
# before the cursor.
if not WORD and match_before and match_after:
c1 = self.text[self.cursor_position - 1]
c2 = self.text[self.cursor_position]
alphabet = string.ascii_letters + "0123456789_"
if (c1 in alphabet) != (c2 in alphabet):
match_before = None
return (
-match_before.end(1) if match_before else 0,
match_after.end(1) if match_after else 0,
)
def get_word_under_cursor(self, WORD: bool = False) -> str:
"""
Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region.
"""
start, end = self.find_boundaries_of_current_word(WORD=WORD)
return self.text[self.cursor_position + start : self.cursor_position + end]
def find_next_word_beginning(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_after_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return match.start(1)
except StopIteration:
pass
return None
def find_next_word_ending(
self, include_current_position: bool = False, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_ending(count=-count, WORD=WORD)
if include_current_position:
text = self.text_after_cursor
else:
text = self.text_after_cursor[1:]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterable = regex.finditer(text)
try:
for i, match in enumerate(iterable):
if i + 1 == count:
value = match.end(1)
if include_current_position:
return value
else:
return value + 1
except StopIteration:
pass
return None
def find_previous_word_beginning(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_before_cursor[::-1])
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.end(1)
except StopIteration:
pass
return None
def find_previous_word_ending(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the end
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_ending(count=-count, WORD=WORD)
text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return -match.start(1) + 1
except StopIteration:
pass
return None
def find_next_matching_line(
self, match_func: Callable[[str], bool], count: int = 1
) -> int | None:
"""
Look downwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[self.cursor_position_row + 1 :]):
if match_func(line):
result = 1 + index
count -= 1
if count == 0:
break
return result
def find_previous_matching_line(
self, match_func: Callable[[str], bool], count: int = 1
) -> int | None:
"""
Look upwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[: self.cursor_position_row][::-1]):
if match_func(line):
result = -1 - index
count -= 1
if count == 0:
break
return result
def get_cursor_left_position(self, count: int = 1) -> int:
"""
Relative position for cursor left.
"""
if count < 0:
return self.get_cursor_right_position(-count)
return -min(self.cursor_position_col, count)
def get_cursor_right_position(self, count: int = 1) -> int:
"""
Relative position for cursor_right.
"""
if count < 0:
return self.get_cursor_left_position(-count)
return min(count, len(self.current_line_after_cursor))
def get_cursor_up_position(
self, count: int = 1, preferred_column: int | None = None
) -> int:
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-up button.
:param preferred_column: When given, go to this column instead of
staying at the current column.
"""
assert count >= 1
column = (
self.cursor_position_col if preferred_column is None else preferred_column
)
return (
self.translate_row_col_to_index(
max(0, self.cursor_position_row - count), column
)
- self.cursor_position
)
def get_cursor_down_position(
self, count: int = 1, preferred_column: int | None = None
) -> int:
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-down button.
:param preferred_column: When given, go to this column instead of
staying at the current column.
"""
assert count >= 1
column = (
self.cursor_position_col if preferred_column is None else preferred_column
)
return (
self.translate_row_col_to_index(self.cursor_position_row + count, column)
- self.cursor_position
)
def find_enclosing_bracket_right(
self, left_ch: str, right_ch: str, end_pos: int | None = None
) -> int | None:
"""
Find the right bracket enclosing current position. Return the relative
position to the cursor position.
When `end_pos` is given, don't look past the position.
"""
if self.current_char == right_ch:
return 0
if end_pos is None:
end_pos = len(self.text)
else:
end_pos = min(len(self.text), end_pos)
stack = 1
# Look forward.
for i in range(self.cursor_position + 1, end_pos):
c = self.text[i]
if c == left_ch:
stack += 1
elif c == right_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position
return None
def find_enclosing_bracket_left(
self, left_ch: str, right_ch: str, start_pos: int | None = None
) -> int | None:
"""
Find the left bracket enclosing current position. Return the relative
position to the cursor position.
When `start_pos` is given, don't look past the position.
"""
if self.current_char == left_ch:
return 0
if start_pos is None:
start_pos = 0
else:
start_pos = max(0, start_pos)
stack = 1
# Look backward.
for i in range(self.cursor_position - 1, start_pos - 1, -1):
c = self.text[i]
if c == right_ch:
stack += 1
elif c == left_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position
return None
def find_matching_bracket_position(
self, start_pos: int | None = None, end_pos: int | None = None
) -> int:
"""
Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
# Look for a match.
for pair in "()", "[]", "{}", "<>":
A = pair[0]
B = pair[1]
if self.current_char == A:
return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
elif self.current_char == B:
return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
return 0
def get_start_of_document_position(self) -> int:
"""Relative position for the start of the document."""
return -self.cursor_position
def get_end_of_document_position(self) -> int:
"""Relative position for the end of the document."""
return len(self.text) - self.cursor_position
def get_start_of_line_position(self, after_whitespace: bool = False) -> int:
"""Relative position for the start of this line."""
if after_whitespace:
current_line = self.current_line
return (
len(current_line)
- len(current_line.lstrip())
- self.cursor_position_col
)
else:
return -len(self.current_line_before_cursor)
def get_end_of_line_position(self) -> int:
"""Relative position for the end of this line."""
return len(self.current_line_after_cursor)
def last_non_blank_of_current_line_position(self) -> int:
"""
Relative position for the last non blank character of this line.
"""
return len(self.current_line.rstrip()) - self.cursor_position_col - 1
def get_column_cursor_position(self, column: int) -> int:
"""
Return the relative cursor position for this column at the current
line. (It will stay between the boundaries of the line in case of a
larger number.)
"""
line_length = len(self.current_line)
current_column = self.cursor_position_col
column = max(0, min(line_length, column))
return column - current_column
def selection_range(
self,
) -> tuple[
int, int
]: # XXX: shouldn't this return `None` if there is no selection???
"""
Return (from, to) tuple of the selection.
start and end position are included.
This doesn't take the selection type into account. Use
`selection_ranges` instead.
"""
if self.selection:
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
else:
from_, to = self.cursor_position, self.cursor_position
return from_, to
def selection_ranges(self) -> Iterable[tuple[int, int]]:
"""
Return a list of `(from, to)` tuples for the selection or none if
nothing was selected. The upper boundary is not included.
This will yield several (from, to) tuples in case of a BLOCK selection.
This will return zero ranges, like (8,8) for empty lines in a block
selection.
"""
if self.selection:
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
if self.selection.type == SelectionType.BLOCK:
from_line, from_column = self.translate_index_to_position(from_)
to_line, to_column = self.translate_index_to_position(to)
from_column, to_column = sorted([from_column, to_column])
lines = self.lines
if vi_mode():
to_column += 1
for l in range(from_line, to_line + 1):
line_length = len(lines[l])
if from_column <= line_length:
yield (
self.translate_row_col_to_index(l, from_column),
self.translate_row_col_to_index(
l, min(line_length, to_column)
),
)
else:
# In case of a LINES selection, go to the start/end of the lines.
if self.selection.type == SelectionType.LINES:
from_ = max(0, self.text.rfind("\n", 0, from_) + 1)
if self.text.find("\n", to) >= 0:
to = self.text.find("\n", to)
else:
to = len(self.text) - 1
# In Vi mode, the upper boundary is always included. For Emacs,
# that's not the case.
if vi_mode():
to += 1
yield from_, to
def selection_range_at_line(self, row: int) -> tuple[int, int] | None:
"""
If the selection spans a portion of the given line, return a (from, to) tuple.
The returned upper boundary is not included in the selection, so
`(0, 0)` is an empty selection. `(0, 1)`, is a one character selection.
Returns None if the selection doesn't cover this line at all.
"""
if self.selection:
line = self.lines[row]
row_start = self.translate_row_col_to_index(row, 0)
row_end = self.translate_row_col_to_index(row, len(line))
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
# Take the intersection of the current line and the selection.
intersection_start = max(row_start, from_)
intersection_end = min(row_end, to)
if intersection_start <= intersection_end:
if self.selection.type == SelectionType.LINES:
intersection_start = row_start
intersection_end = row_end
elif self.selection.type == SelectionType.BLOCK:
_, col1 = self.translate_index_to_position(from_)
_, col2 = self.translate_index_to_position(to)
col1, col2 = sorted([col1, col2])
if col1 > len(line):
return None # Block selection doesn't cross this line.
intersection_start = self.translate_row_col_to_index(row, col1)
intersection_end = self.translate_row_col_to_index(row, col2)
_, from_column = self.translate_index_to_position(intersection_start)
_, to_column = self.translate_index_to_position(intersection_end)
# In Vi mode, the upper boundary is always included. For Emacs
# mode, that's not the case.
if vi_mode():
to_column += 1
return from_column, to_column
return None
def cut_selection(self) -> tuple[Document, ClipboardData]:
"""
Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the
document represents the new document when the selection is cut, and the
clipboard data, represents whatever has to be put on the clipboard.
"""
if self.selection:
cut_parts = []
remaining_parts = []
new_cursor_position = self.cursor_position
last_to = 0
for from_, to in self.selection_ranges():
if last_to == 0:
new_cursor_position = from_
remaining_parts.append(self.text[last_to:from_])
cut_parts.append(self.text[from_:to])
last_to = to
remaining_parts.append(self.text[last_to:])
cut_text = "\n".join(cut_parts)
remaining_text = "".join(remaining_parts)
# In case of a LINES selection, don't include the trailing newline.
if self.selection.type == SelectionType.LINES and cut_text.endswith("\n"):
cut_text = cut_text[:-1]
return (
Document(text=remaining_text, cursor_position=new_cursor_position),
ClipboardData(cut_text, self.selection.type),
)
else:
return self, ClipboardData("")
def paste_clipboard_data(
self,
data: ClipboardData,
paste_mode: PasteMode = PasteMode.EMACS,
count: int = 1,
) -> Document:
"""
Return a new :class:`.Document` instance which contains the result if
we would paste this data at the current cursor position.
:param paste_mode: Where to paste. (Before/after/emacs.)
:param count: When >1, Paste multiple times.
"""
before = paste_mode == PasteMode.VI_BEFORE
after = paste_mode == PasteMode.VI_AFTER
if data.type == SelectionType.CHARACTERS:
if after:
new_text = (
self.text[: self.cursor_position + 1]
+ data.text * count
+ self.text[self.cursor_position + 1 :]
)
else:
new_text = (
self.text_before_cursor + data.text * count + self.text_after_cursor
)
new_cursor_position = self.cursor_position + len(data.text) * count
if before:
new_cursor_position -= 1
elif data.type == SelectionType.LINES:
l = self.cursor_position_row
if before:
lines = self.lines[:l] + [data.text] * count + self.lines[l:]
new_text = "\n".join(lines)
new_cursor_position = len("".join(self.lines[:l])) + l
else:
lines = self.lines[: l + 1] + [data.text] * count + self.lines[l + 1 :]
new_cursor_position = len("".join(self.lines[: l + 1])) + l + 1
new_text = "\n".join(lines)
elif data.type == SelectionType.BLOCK:
lines = self.lines[:]
start_line = self.cursor_position_row
start_column = self.cursor_position_col + (0 if before else 1)
for i, line in enumerate(data.text.split("\n")):
index = i + start_line
if index >= len(lines):
lines.append("")
lines[index] = lines[index].ljust(start_column)
lines[index] = (
lines[index][:start_column]
+ line * count
+ lines[index][start_column:]
)
new_text = "\n".join(lines)
new_cursor_position = self.cursor_position + (0 if before else 1)
return Document(text=new_text, cursor_position=new_cursor_position)
def empty_line_count_at_the_end(self) -> int:
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count
def start_of_paragraph(self, count: int = 1, before: bool = False) -> int:
"""
Return the start of the current paragraph. (Relative cursor position.)
"""
def match_func(text: str) -> bool:
return not text or text.isspace()
line_index = self.find_previous_matching_line(
match_func=match_func, count=count
)
if line_index:
add = 0 if before else 1
return min(0, self.get_cursor_up_position(count=-line_index) + add)
else:
return -self.cursor_position
def end_of_paragraph(self, count: int = 1, after: bool = False) -> int:
"""
Return the end of the current paragraph. (Relative cursor position.)
"""
def match_func(text: str) -> bool:
return not text or text.isspace()
line_index = self.find_next_matching_line(match_func=match_func, count=count)
if line_index:
add = 0 if after else 1
return max(0, self.get_cursor_down_position(count=line_index) - add)
else:
return len(self.text_after_cursor)
# Modifiers.
def insert_after(self, text: str) -> Document:
"""
Create a new document, with this text inserted after the buffer.
It keeps selection ranges and cursor position in sync.
"""
return Document(
text=self.text + text,
cursor_position=self.cursor_position,
selection=self.selection,
)
def insert_before(self, text: str) -> Document:
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
original_cursor_position=selection_state.original_cursor_position
+ len(text),
type=selection_state.type,
)
return Document(
text=text + self.text,
cursor_position=self.cursor_position + len(text),
selection=selection_state,
)
def is_multiline() -> bool:
"""
True when the current buffer has been marked as multiline.
"""
return get_app().current_buffer.multiline()
def in_paste_mode() -> bool:
return get_app().paste_mode()
def vi_mode() -> bool:
return get_app().editing_mode == EditingMode.VI
def vi_navigation_mode() -> bool:
"""
Active when the set for Vi navigation key bindings are active.
"""
from prompt_toolkit.key_binding.vi_state import InputMode
app = get_app()
if (
app.editing_mode != EditingMode.VI
or app.vi_state.operator_func
or app.vi_state.waiting_for_digraph
or app.current_buffer.selection_state
):
return False
return (
app.vi_state.input_mode == InputMode.NAVIGATION
or app.vi_state.temporary_navigation_mode
or app.current_buffer.read_only()
)
def vi_insert_mode() -> bool:
from prompt_toolkit.key_binding.vi_state import InputMode
app = get_app()
if (
app.editing_mode != EditingMode.VI
or app.vi_state.operator_func
or app.vi_state.waiting_for_digraph
or app.current_buffer.selection_state
or app.vi_state.temporary_navigation_mode
or app.current_buffer.read_only()
):
return False
return app.vi_state.input_mode == InputMode.INSERT
def vi_insert_multiple_mode() -> bool:
from prompt_toolkit.key_binding.vi_state import InputMode
app = get_app()
if (
app.editing_mode != EditingMode.VI
or app.vi_state.operator_func
or app.vi_state.waiting_for_digraph
or app.current_buffer.selection_state
or app.vi_state.temporary_navigation_mode
or app.current_buffer.read_only()
):
return False
return app.vi_state.input_mode == InputMode.INSERT_MULTIPLE
def vi_replace_mode() -> bool:
from prompt_toolkit.key_binding.vi_state import InputMode
app = get_app()
if (
app.editing_mode != EditingMode.VI
or app.vi_state.operator_func
or app.vi_state.waiting_for_digraph
or app.current_buffer.selection_state
or app.vi_state.temporary_navigation_mode
or app.current_buffer.read_only()
):
return False
return app.vi_state.input_mode == InputMode.REPLACE
def vi_replace_single_mode() -> bool:
from prompt_toolkit.key_binding.vi_state import InputMode
app = get_app()
if (
app.editing_mode != EditingMode.VI
or app.vi_state.operator_func
or app.vi_state.waiting_for_digraph
or app.current_buffer.selection_state
or app.vi_state.temporary_navigation_mode
or app.current_buffer.read_only()
):
return False
return app.vi_state.input_mode == InputMode.REPLACE_SINGLE
def vi_selection_mode() -> bool:
app = get_app()
if app.editing_mode != EditingMode.VI:
return False
return bool(app.current_buffer.selection_state)
def vi_waiting_for_text_object_mode() -> bool:
app = get_app()
if app.editing_mode != EditingMode.VI:
return False
return app.vi_state.operator_func is not None
def vi_digraph_mode() -> bool:
app = get_app()
if app.editing_mode != EditingMode.VI:
return False
return app.vi_state.waiting_for_digraph
def vi_recording_macro() -> bool:
"When recording a Vi macro."
app = get_app()
if app.editing_mode != EditingMode.VI:
return False
return app.vi_state.recording_register is not None
class Vt100Parser:
"""
Parser for VT100 input stream.
Data can be fed through the `feed` method and the given callback will be
called with KeyPress objects.
::
def callback(key):
pass
i = Vt100Parser(callback)
i.feed('data\x01...')
:attr feed_key_callback: Function that will be called when a key is parsed.
"""
# Lookup table of ANSI escape sequences for a VT100 terminal
# Hint: in order to know what sequences your terminal writes to stdin, run
# "od -c" and start typing.
def __init__(self, feed_key_callback: Callable[[KeyPress], None]) -> None:
self.feed_key_callback = feed_key_callback
self.reset()
def reset(self, request: bool = False) -> None:
self._in_bracketed_paste = False
self._start_parser()
def _start_parser(self) -> None:
"""
Start the parser coroutine.
"""
self._input_parser = self._input_parser_generator()
self._input_parser.send(None) # type: ignore
def _get_match(self, prefix: str) -> None | Keys | tuple[Keys, ...]:
"""
Return the key (or keys) that maps to this prefix.
"""
# (hard coded) If we match a CPR response, return Keys.CPRResponse.
# (This one doesn't fit in the ANSI_SEQUENCES, because it contains
# integer variables.)
if _cpr_response_re.match(prefix):
return Keys.CPRResponse
elif _mouse_event_re.match(prefix):
return Keys.Vt100MouseEvent
# Otherwise, use the mappings.
try:
return ANSI_SEQUENCES[prefix]
except KeyError:
return None
def _input_parser_generator(self) -> Generator[None, str | _Flush, None]:
"""
Coroutine (state machine) for the input parser.
"""
prefix = ""
retry = False
flush = False
while True:
flush = False
if retry:
retry = False
else:
# Get next character.
c = yield
if isinstance(c, _Flush):
flush = True
else:
prefix += c
# If we have some data, check for matches.
if prefix:
is_prefix_of_longer_match = _IS_PREFIX_OF_LONGER_MATCH_CACHE[prefix]
match = self._get_match(prefix)
# Exact matches found, call handlers..
if (flush or not is_prefix_of_longer_match) and match:
self._call_handler(match, prefix)
prefix = ""
# No exact match found.
elif (flush or not is_prefix_of_longer_match) and not match:
found = False
retry = True
# Loop over the input, try the longest match first and
# shift.
for i in range(len(prefix), 0, -1):
match = self._get_match(prefix[:i])
if match:
self._call_handler(match, prefix[:i])
prefix = prefix[i:]
found = True
if not found:
self._call_handler(prefix[0], prefix[0])
prefix = prefix[1:]
def _call_handler(
self, key: str | Keys | tuple[Keys, ...], insert_text: str
) -> None:
"""
Callback to handler.
"""
if isinstance(key, tuple):
# Received ANSI sequence that corresponds with multiple keys
# (probably alt+something). Handle keys individually, but only pass
# data payload to first KeyPress (so that we won't insert it
# multiple times).
for i, k in enumerate(key):
self._call_handler(k, insert_text if i == 0 else "")
else:
if key == Keys.BracketedPaste:
self._in_bracketed_paste = True
self._paste_buffer = ""
else:
self.feed_key_callback(KeyPress(key, insert_text))
def feed(self, data: str) -> None:
"""
Feed the input stream.
:param data: Input string (unicode).
"""
# Handle bracketed paste. (We bypass the parser that matches all other
# key presses and keep reading input until we see the end mark.)
# This is much faster then parsing character by character.
if self._in_bracketed_paste:
self._paste_buffer += data
end_mark = "\x1b[201~"
if end_mark in self._paste_buffer:
end_index = self._paste_buffer.index(end_mark)
# Feed content to key bindings.
paste_content = self._paste_buffer[:end_index]
self.feed_key_callback(KeyPress(Keys.BracketedPaste, paste_content))
# Quit bracketed paste mode and handle remaining input.
self._in_bracketed_paste = False
remaining = self._paste_buffer[end_index + len(end_mark) :]
self._paste_buffer = ""
self.feed(remaining)
# Handle normal input character by character.
else:
for i, c in enumerate(data):
if self._in_bracketed_paste:
# Quit loop and process from this position when the parser
# entered bracketed paste.
self.feed(data[i:])
break
else:
self._input_parser.send(c)
def flush(self) -> None:
"""
Flush the buffer of the input stream.
This will allow us to handle the escape key (or maybe meta) sooner.
The input received by the escape key is actually the same as the first
characters of e.g. Arrow-Up, so without knowing what follows the escape
sequence, we don't know whether escape has been pressed, or whether
it's something else. This flush function should be called after a
timeout, and processes everything that's still in the buffer as-is, so
without assuming any characters will follow.
"""
self._input_parser.send(_Flush())
def feed_and_flush(self, data: str) -> None:
"""
Wrapper around ``feed`` and ``flush``.
"""
self.feed(data)
self.flush()
DIGRAPHS: dict[tuple[str, str], int] = {
("N", "U"): 0x00,
("S", "H"): 0x01,
("S", "X"): 0x02,
("E", "X"): 0x03,
("E", "T"): 0x04,
("E", "Q"): 0x05,
("A", "K"): 0x06,
("B", "L"): 0x07,
("B", "S"): 0x08,
("H", "T"): 0x09,
("L", "F"): 0x0A,
("V", "T"): 0x0B,
("F", "F"): 0x0C,
("C", "R"): 0x0D,
("S", "O"): 0x0E,
("S", "I"): 0x0F,
("D", "L"): 0x10,
("D", "1"): 0x11,
("D", "2"): 0x12,
("D", "3"): 0x13,
("D", "4"): 0x14,
("N", "K"): 0x15,
("S", "Y"): 0x16,
("E", "B"): 0x17,
("C", "N"): 0x18,
("E", "M"): 0x19,
("S", "B"): 0x1A,
("E", "C"): 0x1B,
("F", "S"): 0x1C,
("G", "S"): 0x1D,
("R", "S"): 0x1E,
("U", "S"): 0x1F,
("S", "P"): 0x20,
("N", "b"): 0x23,
("D", "O"): 0x24,
("A", "t"): 0x40,
("<", "("): 0x5B,
("/", "/"): 0x5C,
(")", ">"): 0x5D,
("'", ">"): 0x5E,
("'", "!"): 0x60,
("(", "!"): 0x7B,
("!", "!"): 0x7C,
("!", ")"): 0x7D,
("'", "?"): 0x7E,
("D", "T"): 0x7F,
("P", "A"): 0x80,
("H", "O"): 0x81,
("B", "H"): 0x82,
("N", "H"): 0x83,
("I", "N"): 0x84,
("N", "L"): 0x85,
("S", "A"): 0x86,
("E", "S"): 0x87,
("H", "S"): 0x88,
("H", "J"): 0x89,
("V", "S"): 0x8A,
("P", "D"): 0x8B,
("P", "U"): 0x8C,
("R", "I"): 0x8D,
("S", "2"): 0x8E,
("S", "3"): 0x8F,
("D", "C"): 0x90,
("P", "1"): 0x91,
("P", "2"): 0x92,
("T", "S"): 0x93,
("C", "C"): 0x94,
("M", "W"): 0x95,
("S", "G"): 0x96,
("E", "G"): 0x97,
("S", "S"): 0x98,
("G", "C"): 0x99,
("S", "C"): 0x9A,
("C", "I"): 0x9B,
("S", "T"): 0x9C,
("O", "C"): 0x9D,
("P", "M"): 0x9E,
("A", "C"): 0x9F,
("N", "S"): 0xA0,
("!", "I"): 0xA1,
("C", "t"): 0xA2,
("P", "d"): 0xA3,
("C", "u"): 0xA4,
("Y", "e"): 0xA5,
("B", "B"): 0xA6,
("S", "E"): 0xA7,
("'", ":"): 0xA8,
("C", "o"): 0xA9,
("-", "a"): 0xAA,
("<", "<"): 0xAB,
("N", "O"): 0xAC,
("-", "-"): 0xAD,
("R", "g"): 0xAE,
("'", "m"): 0xAF,
("D", "G"): 0xB0,
("+", "-"): 0xB1,
("2", "S"): 0xB2,
("3", "S"): 0xB3,
("'", "'"): 0xB4,
("M", "y"): 0xB5,
("P", "I"): 0xB6,
(".", "M"): 0xB7,
("'", ","): 0xB8,
("1", "S"): 0xB9,
("-", "o"): 0xBA,
(">", ">"): 0xBB,
("1", "4"): 0xBC,
("1", "2"): 0xBD,
("3", "4"): 0xBE,
("?", "I"): 0xBF,
("A", "!"): 0xC0,
("A", "'"): 0xC1,
("A", ">"): 0xC2,
("A", "?"): 0xC3,
("A", ":"): 0xC4,
("A", "A"): 0xC5,
("A", "E"): 0xC6,
("C", ","): 0xC7,
("E", "!"): 0xC8,
("E", "'"): 0xC9,
("E", ">"): 0xCA,
("E", ":"): 0xCB,
("I", "!"): 0xCC,
("I", "'"): 0xCD,
("I", ">"): 0xCE,
("I", ":"): 0xCF,
("D", "-"): 0xD0,
("N", "?"): 0xD1,
("O", "!"): 0xD2,
("O", "'"): 0xD3,
("O", ">"): 0xD4,
("O", "?"): 0xD5,
("O", ":"): 0xD6,
("*", "X"): 0xD7,
("O", "/"): 0xD8,
("U", "!"): 0xD9,
("U", "'"): 0xDA,
("U", ">"): 0xDB,
("U", ":"): 0xDC,
("Y", "'"): 0xDD,
("T", "H"): 0xDE,
("s", "s"): 0xDF,
("a", "!"): 0xE0,
("a", "'"): 0xE1,
("a", ">"): 0xE2,
("a", "?"): 0xE3,
("a", ":"): 0xE4,
("a", "a"): 0xE5,
("a", "e"): 0xE6,
("c", ","): 0xE7,
("e", "!"): 0xE8,
("e", "'"): 0xE9,
("e", ">"): 0xEA,
("e", ":"): 0xEB,
("i", "!"): 0xEC,
("i", "'"): 0xED,
("i", ">"): 0xEE,
("i", ":"): 0xEF,
("d", "-"): 0xF0,
("n", "?"): 0xF1,
("o", "!"): 0xF2,
("o", "'"): 0xF3,
("o", ">"): 0xF4,
("o", "?"): 0xF5,
("o", ":"): 0xF6,
("-", ":"): 0xF7,
("o", "/"): 0xF8,
("u", "!"): 0xF9,
("u", "'"): 0xFA,
("u", ">"): 0xFB,
("u", ":"): 0xFC,
("y", "'"): 0xFD,
("t", "h"): 0xFE,
("y", ":"): 0xFF,
("A", "-"): 0x0100,
("a", "-"): 0x0101,
("A", "("): 0x0102,
("a", "("): 0x0103,
("A", ";"): 0x0104,
("a", ";"): 0x0105,
("C", "'"): 0x0106,
("c", "'"): 0x0107,
("C", ">"): 0x0108,
("c", ">"): 0x0109,
("C", "."): 0x010A,
("c", "."): 0x010B,
("C", "<"): 0x010C,
("c", "<"): 0x010D,
("D", "<"): 0x010E,
("d", "<"): 0x010F,
("D", "/"): 0x0110,
("d", "/"): 0x0111,
("E", "-"): 0x0112,
("e", "-"): 0x0113,
("E", "("): 0x0114,
("e", "("): 0x0115,
("E", "."): 0x0116,
("e", "."): 0x0117,
("E", ";"): 0x0118,
("e", ";"): 0x0119,
("E", "<"): 0x011A,
("e", "<"): 0x011B,
("G", ">"): 0x011C,
("g", ">"): 0x011D,
("G", "("): 0x011E,
("g", "("): 0x011F,
("G", "."): 0x0120,
("g", "."): 0x0121,
("G", ","): 0x0122,
("g", ","): 0x0123,
("H", ">"): 0x0124,
("h", ">"): 0x0125,
("H", "/"): 0x0126,
("h", "/"): 0x0127,
("I", "?"): 0x0128,
("i", "?"): 0x0129,
("I", "-"): 0x012A,
("i", "-"): 0x012B,
("I", "("): 0x012C,
("i", "("): 0x012D,
("I", ";"): 0x012E,
("i", ";"): 0x012F,
("I", "."): 0x0130,
("i", "."): 0x0131,
("I", "J"): 0x0132,
("i", "j"): 0x0133,
("J", ">"): 0x0134,
("j", ">"): 0x0135,
("K", ","): 0x0136,
("k", ","): 0x0137,
("k", "k"): 0x0138,
("L", "'"): 0x0139,
("l", "'"): 0x013A,
("L", ","): 0x013B,
("l", ","): 0x013C,
("L", "<"): 0x013D,
("l", "<"): 0x013E,
("L", "."): 0x013F,
("l", "."): 0x0140,
("L", "/"): 0x0141,
("l", "/"): 0x0142,
("N", "'"): 0x0143,
("n", "'"): 0x0144,
("N", ","): 0x0145,
("n", ","): 0x0146,
("N", "<"): 0x0147,
("n", "<"): 0x0148,
("'", "n"): 0x0149,
("N", "G"): 0x014A,
("n", "g"): 0x014B,
("O", "-"): 0x014C,
("o", "-"): 0x014D,
("O", "("): 0x014E,
("o", "("): 0x014F,
("O", '"'): 0x0150,
("o", '"'): 0x0151,
("O", "E"): 0x0152,
("o", "e"): 0x0153,
("R", "'"): 0x0154,
("r", "'"): 0x0155,
("R", ","): 0x0156,
("r", ","): 0x0157,
("R", "<"): 0x0158,
("r", "<"): 0x0159,
("S", "'"): 0x015A,
("s", "'"): 0x015B,
("S", ">"): 0x015C,
("s", ">"): 0x015D,
("S", ","): 0x015E,
("s", ","): 0x015F,
("S", "<"): 0x0160,
("s", "<"): 0x0161,
("T", ","): 0x0162,
("t", ","): 0x0163,
("T", "<"): 0x0164,
("t", "<"): 0x0165,
("T", "/"): 0x0166,
("t", "/"): 0x0167,
("U", "?"): 0x0168,
("u", "?"): 0x0169,
("U", "-"): 0x016A,
("u", "-"): 0x016B,
("U", "("): 0x016C,
("u", "("): 0x016D,
("U", "0"): 0x016E,
("u", "0"): 0x016F,
("U", '"'): 0x0170,
("u", '"'): 0x0171,
("U", ";"): 0x0172,
("u", ";"): 0x0173,
("W", ">"): 0x0174,
("w", ">"): 0x0175,
("Y", ">"): 0x0176,
("y", ">"): 0x0177,
("Y", ":"): 0x0178,
("Z", "'"): 0x0179,
("z", "'"): 0x017A,
("Z", "."): 0x017B,
("z", "."): 0x017C,
("Z", "<"): 0x017D,
("z", "<"): 0x017E,
("O", "9"): 0x01A0,
("o", "9"): 0x01A1,
("O", "I"): 0x01A2,
("o", "i"): 0x01A3,
("y", "r"): 0x01A6,
("U", "9"): 0x01AF,
("u", "9"): 0x01B0,
("Z", "/"): 0x01B5,
("z", "/"): 0x01B6,
("E", "D"): 0x01B7,
("A", "<"): 0x01CD,
("a", "<"): 0x01CE,
("I", "<"): 0x01CF,
("i", "<"): 0x01D0,
("O", "<"): 0x01D1,
("o", "<"): 0x01D2,
("U", "<"): 0x01D3,
("u", "<"): 0x01D4,
("A", "1"): 0x01DE,
("a", "1"): 0x01DF,
("A", "7"): 0x01E0,
("a", "7"): 0x01E1,
("A", "3"): 0x01E2,
("a", "3"): 0x01E3,
("G", "/"): 0x01E4,
("g", "/"): 0x01E5,
("G", "<"): 0x01E6,
("g", "<"): 0x01E7,
("K", "<"): 0x01E8,
("k", "<"): 0x01E9,
("O", ";"): 0x01EA,
("o", ";"): 0x01EB,
("O", "1"): 0x01EC,
("o", "1"): 0x01ED,
("E", "Z"): 0x01EE,
("e", "z"): 0x01EF,
("j", "<"): 0x01F0,
("G", "'"): 0x01F4,
("g", "'"): 0x01F5,
(";", "S"): 0x02BF,
("'", "<"): 0x02C7,
("'", "("): 0x02D8,
("'", "."): 0x02D9,
("'", "0"): 0x02DA,
("'", ";"): 0x02DB,
("'", '"'): 0x02DD,
("A", "%"): 0x0386,
("E", "%"): 0x0388,
("Y", "%"): 0x0389,
("I", "%"): 0x038A,
("O", "%"): 0x038C,
("U", "%"): 0x038E,
("W", "%"): 0x038F,
("i", "3"): 0x0390,
("A", "*"): 0x0391,
("B", "*"): 0x0392,
("G", "*"): 0x0393,
("D", "*"): 0x0394,
("E", "*"): 0x0395,
("Z", "*"): 0x0396,
("Y", "*"): 0x0397,
("H", "*"): 0x0398,
("I", "*"): 0x0399,
("K", "*"): 0x039A,
("L", "*"): 0x039B,
("M", "*"): 0x039C,
("N", "*"): 0x039D,
("C", "*"): 0x039E,
("O", "*"): 0x039F,
("P", "*"): 0x03A0,
("R", "*"): 0x03A1,
("S", "*"): 0x03A3,
("T", "*"): 0x03A4,
("U", "*"): 0x03A5,
("F", "*"): 0x03A6,
("X", "*"): 0x03A7,
("Q", "*"): 0x03A8,
("W", "*"): 0x03A9,
("J", "*"): 0x03AA,
("V", "*"): 0x03AB,
("a", "%"): 0x03AC,
("e", "%"): 0x03AD,
("y", "%"): 0x03AE,
("i", "%"): 0x03AF,
("u", "3"): 0x03B0,
("a", "*"): 0x03B1,
("b", "*"): 0x03B2,
("g", "*"): 0x03B3,
("d", "*"): 0x03B4,
("e", "*"): 0x03B5,
("z", "*"): 0x03B6,
("y", "*"): 0x03B7,
("h", "*"): 0x03B8,
("i", "*"): 0x03B9,
("k", "*"): 0x03BA,
("l", "*"): 0x03BB,
("m", "*"): 0x03BC,
("n", "*"): 0x03BD,
("c", "*"): 0x03BE,
("o", "*"): 0x03BF,
("p", "*"): 0x03C0,
("r", "*"): 0x03C1,
("*", "s"): 0x03C2,
("s", "*"): 0x03C3,
("t", "*"): 0x03C4,
("u", "*"): 0x03C5,
("f", "*"): 0x03C6,
("x", "*"): 0x03C7,
("q", "*"): 0x03C8,
("w", "*"): 0x03C9,
("j", "*"): 0x03CA,
("v", "*"): 0x03CB,
("o", "%"): 0x03CC,
("u", "%"): 0x03CD,
("w", "%"): 0x03CE,
("'", "G"): 0x03D8,
(",", "G"): 0x03D9,
("T", "3"): 0x03DA,
("t", "3"): 0x03DB,
("M", "3"): 0x03DC,
("m", "3"): 0x03DD,
("K", "3"): 0x03DE,
("k", "3"): 0x03DF,
("P", "3"): 0x03E0,
("p", "3"): 0x03E1,
("'", "%"): 0x03F4,
("j", "3"): 0x03F5,
("I", "O"): 0x0401,
("D", "%"): 0x0402,
("G", "%"): 0x0403,
("I", "E"): 0x0404,
("D", "S"): 0x0405,
("I", "I"): 0x0406,
("Y", "I"): 0x0407,
("J", "%"): 0x0408,
("L", "J"): 0x0409,
("N", "J"): 0x040A,
("T", "s"): 0x040B,
("K", "J"): 0x040C,
("V", "%"): 0x040E,
("D", "Z"): 0x040F,
("A", "="): 0x0410,
("B", "="): 0x0411,
("V", "="): 0x0412,
("G", "="): 0x0413,
("D", "="): 0x0414,
("E", "="): 0x0415,
("Z", "%"): 0x0416,
("Z", "="): 0x0417,
("I", "="): 0x0418,
("J", "="): 0x0419,
("K", "="): 0x041A,
("L", "="): 0x041B,
("M", "="): 0x041C,
("N", "="): 0x041D,
("O", "="): 0x041E,
("P", "="): 0x041F,
("R", "="): 0x0420,
("S", "="): 0x0421,
("T", "="): 0x0422,
("U", "="): 0x0423,
("F", "="): 0x0424,
("H", "="): 0x0425,
("C", "="): 0x0426,
("C", "%"): 0x0427,
("S", "%"): 0x0428,
("S", "c"): 0x0429,
("=", '"'): 0x042A,
("Y", "="): 0x042B,
("%", '"'): 0x042C,
("J", "E"): 0x042D,
("J", "U"): 0x042E,
("J", "A"): 0x042F,
("a", "="): 0x0430,
("b", "="): 0x0431,
("v", "="): 0x0432,
("g", "="): 0x0433,
("d", "="): 0x0434,
("e", "="): 0x0435,
("z", "%"): 0x0436,
("z", "="): 0x0437,
("i", "="): 0x0438,
("j", "="): 0x0439,
("k", "="): 0x043A,
("l", "="): 0x043B,
("m", "="): 0x043C,
("n", "="): 0x043D,
("o", "="): 0x043E,
("p", "="): 0x043F,
("r", "="): 0x0440,
("s", "="): 0x0441,
("t", "="): 0x0442,
("u", "="): 0x0443,
("f", "="): 0x0444,
("h", "="): 0x0445,
("c", "="): 0x0446,
("c", "%"): 0x0447,
("s", "%"): 0x0448,
("s", "c"): 0x0449,
("=", "'"): 0x044A,
("y", "="): 0x044B,
("%", "'"): 0x044C,
("j", "e"): 0x044D,
("j", "u"): 0x044E,
("j", "a"): 0x044F,
("i", "o"): 0x0451,
("d", "%"): 0x0452,
("g", "%"): 0x0453,
("i", "e"): 0x0454,
("d", "s"): 0x0455,
("i", "i"): 0x0456,
("y", "i"): 0x0457,
("j", "%"): 0x0458,
("l", "j"): 0x0459,
("n", "j"): 0x045A,
("t", "s"): 0x045B,
("k", "j"): 0x045C,
("v", "%"): 0x045E,
("d", "z"): 0x045F,
("Y", "3"): 0x0462,
("y", "3"): 0x0463,
("O", "3"): 0x046A,
("o", "3"): 0x046B,
("F", "3"): 0x0472,
("f", "3"): 0x0473,
("V", "3"): 0x0474,
("v", "3"): 0x0475,
("C", "3"): 0x0480,
("c", "3"): 0x0481,
("G", "3"): 0x0490,
("g", "3"): 0x0491,
("A", "+"): 0x05D0,
("B", "+"): 0x05D1,
("G", "+"): 0x05D2,
("D", "+"): 0x05D3,
("H", "+"): 0x05D4,
("W", "+"): 0x05D5,
("Z", "+"): 0x05D6,
("X", "+"): 0x05D7,
("T", "j"): 0x05D8,
("J", "+"): 0x05D9,
("K", "%"): 0x05DA,
("K", "+"): 0x05DB,
("L", "+"): 0x05DC,
("M", "%"): 0x05DD,
("M", "+"): 0x05DE,
("N", "%"): 0x05DF,
("N", "+"): 0x05E0,
("S", "+"): 0x05E1,
("E", "+"): 0x05E2,
("P", "%"): 0x05E3,
("P", "+"): 0x05E4,
("Z", "j"): 0x05E5,
("Z", "J"): 0x05E6,
("Q", "+"): 0x05E7,
("R", "+"): 0x05E8,
("S", "h"): 0x05E9,
("T", "+"): 0x05EA,
(",", "+"): 0x060C,
(";", "+"): 0x061B,
("?", "+"): 0x061F,
("H", "'"): 0x0621,
("a", "M"): 0x0622,
("a", "H"): 0x0623,
("w", "H"): 0x0624,
("a", "h"): 0x0625,
("y", "H"): 0x0626,
("a", "+"): 0x0627,
("b", "+"): 0x0628,
("t", "m"): 0x0629,
("t", "+"): 0x062A,
("t", "k"): 0x062B,
("g", "+"): 0x062C,
("h", "k"): 0x062D,
("x", "+"): 0x062E,
("d", "+"): 0x062F,
("d", "k"): 0x0630,
("r", "+"): 0x0631,
("z", "+"): 0x0632,
("s", "+"): 0x0633,
("s", "n"): 0x0634,
("c", "+"): 0x0635,
("d", "d"): 0x0636,
("t", "j"): 0x0637,
("z", "H"): 0x0638,
("e", "+"): 0x0639,
("i", "+"): 0x063A,
("+", "+"): 0x0640,
("f", "+"): 0x0641,
("q", "+"): 0x0642,
("k", "+"): 0x0643,
("l", "+"): 0x0644,
("m", "+"): 0x0645,
("n", "+"): 0x0646,
("h", "+"): 0x0647,
("w", "+"): 0x0648,
("j", "+"): 0x0649,
("y", "+"): 0x064A,
(":", "+"): 0x064B,
('"', "+"): 0x064C,
("=", "+"): 0x064D,
("/", "+"): 0x064E,
("'", "+"): 0x064F,
("1", "+"): 0x0650,
("3", "+"): 0x0651,
("0", "+"): 0x0652,
("a", "S"): 0x0670,
("p", "+"): 0x067E,
("v", "+"): 0x06A4,
("g", "f"): 0x06AF,
("0", "a"): 0x06F0,
("1", "a"): 0x06F1,
("2", "a"): 0x06F2,
("3", "a"): 0x06F3,
("4", "a"): 0x06F4,
("5", "a"): 0x06F5,
("6", "a"): 0x06F6,
("7", "a"): 0x06F7,
("8", "a"): 0x06F8,
("9", "a"): 0x06F9,
("B", "."): 0x1E02,
("b", "."): 0x1E03,
("B", "_"): 0x1E06,
("b", "_"): 0x1E07,
("D", "."): 0x1E0A,
("d", "."): 0x1E0B,
("D", "_"): 0x1E0E,
("d", "_"): 0x1E0F,
("D", ","): 0x1E10,
("d", ","): 0x1E11,
("F", "."): 0x1E1E,
("f", "."): 0x1E1F,
("G", "-"): 0x1E20,
("g", "-"): 0x1E21,
("H", "."): 0x1E22,
("h", "."): 0x1E23,
("H", ":"): 0x1E26,
("h", ":"): 0x1E27,
("H", ","): 0x1E28,
("h", ","): 0x1E29,
("K", "'"): 0x1E30,
("k", "'"): 0x1E31,
("K", "_"): 0x1E34,
("k", "_"): 0x1E35,
("L", "_"): 0x1E3A,
("l", "_"): 0x1E3B,
("M", "'"): 0x1E3E,
("m", "'"): 0x1E3F,
("M", "."): 0x1E40,
("m", "."): 0x1E41,
("N", "."): 0x1E44,
("n", "."): 0x1E45,
("N", "_"): 0x1E48,
("n", "_"): 0x1E49,
("P", "'"): 0x1E54,
("p", "'"): 0x1E55,
("P", "."): 0x1E56,
("p", "."): 0x1E57,
("R", "."): 0x1E58,
("r", "."): 0x1E59,
("R", "_"): 0x1E5E,
("r", "_"): 0x1E5F,
("S", "."): 0x1E60,
("s", "."): 0x1E61,
("T", "."): 0x1E6A,
("t", "."): 0x1E6B,
("T", "_"): 0x1E6E,
("t", "_"): 0x1E6F,
("V", "?"): 0x1E7C,
("v", "?"): 0x1E7D,
("W", "!"): 0x1E80,
("w", "!"): 0x1E81,
("W", "'"): 0x1E82,
("w", "'"): 0x1E83,
("W", ":"): 0x1E84,
("w", ":"): 0x1E85,
("W", "."): 0x1E86,
("w", "."): 0x1E87,
("X", "."): 0x1E8A,
("x", "."): 0x1E8B,
("X", ":"): 0x1E8C,
("x", ":"): 0x1E8D,
("Y", "."): 0x1E8E,
("y", "."): 0x1E8F,
("Z", ">"): 0x1E90,
("z", ">"): 0x1E91,
("Z", "_"): 0x1E94,
("z", "_"): 0x1E95,
("h", "_"): 0x1E96,
("t", ":"): 0x1E97,
("w", "0"): 0x1E98,
("y", "0"): 0x1E99,
("A", "2"): 0x1EA2,
("a", "2"): 0x1EA3,
("E", "2"): 0x1EBA,
("e", "2"): 0x1EBB,
("E", "?"): 0x1EBC,
("e", "?"): 0x1EBD,
("I", "2"): 0x1EC8,
("i", "2"): 0x1EC9,
("O", "2"): 0x1ECE,
("o", "2"): 0x1ECF,
("U", "2"): 0x1EE6,
("u", "2"): 0x1EE7,
("Y", "!"): 0x1EF2,
("y", "!"): 0x1EF3,
("Y", "2"): 0x1EF6,
("y", "2"): 0x1EF7,
("Y", "?"): 0x1EF8,
("y", "?"): 0x1EF9,
(";", "'"): 0x1F00,
(",", "'"): 0x1F01,
(";", "!"): 0x1F02,
(",", "!"): 0x1F03,
("?", ";"): 0x1F04,
("?", ","): 0x1F05,
("!", ":"): 0x1F06,
("?", ":"): 0x1F07,
("1", "N"): 0x2002,
("1", "M"): 0x2003,
("3", "M"): 0x2004,
("4", "M"): 0x2005,
("6", "M"): 0x2006,
("1", "T"): 0x2009,
("1", "H"): 0x200A,
("-", "1"): 0x2010,
("-", "N"): 0x2013,
("-", "M"): 0x2014,
("-", "3"): 0x2015,
("!", "2"): 0x2016,
("=", "2"): 0x2017,
("'", "6"): 0x2018,
("'", "9"): 0x2019,
(".", "9"): 0x201A,
("9", "'"): 0x201B,
('"', "6"): 0x201C,
('"', "9"): 0x201D,
(":", "9"): 0x201E,
("9", '"'): 0x201F,
("/", "-"): 0x2020,
("/", "="): 0x2021,
(".", "."): 0x2025,
("%", "0"): 0x2030,
("1", "'"): 0x2032,
("2", "'"): 0x2033,
("3", "'"): 0x2034,
("1", '"'): 0x2035,
("2", '"'): 0x2036,
("3", '"'): 0x2037,
("C", "a"): 0x2038,
("<", "1"): 0x2039,
(">", "1"): 0x203A,
(":", "X"): 0x203B,
("'", "-"): 0x203E,
("/", "f"): 0x2044,
("0", "S"): 0x2070,
("4", "S"): 0x2074,
("5", "S"): 0x2075,
("6", "S"): 0x2076,
("7", "S"): 0x2077,
("8", "S"): 0x2078,
("9", "S"): 0x2079,
("+", "S"): 0x207A,
("-", "S"): 0x207B,
("=", "S"): 0x207C,
("(", "S"): 0x207D,
(")", "S"): 0x207E,
("n", "S"): 0x207F,
("0", "s"): 0x2080,
("1", "s"): 0x2081,
("2", "s"): 0x2082,
("3", "s"): 0x2083,
("4", "s"): 0x2084,
("5", "s"): 0x2085,
("6", "s"): 0x2086,
("7", "s"): 0x2087,
("8", "s"): 0x2088,
("9", "s"): 0x2089,
("+", "s"): 0x208A,
("-", "s"): 0x208B,
("=", "s"): 0x208C,
("(", "s"): 0x208D,
(")", "s"): 0x208E,
("L", "i"): 0x20A4,
("P", "t"): 0x20A7,
("W", "="): 0x20A9,
("=", "e"): 0x20AC, # euro
("E", "u"): 0x20AC, # euro
("=", "R"): 0x20BD, # rouble
("=", "P"): 0x20BD, # rouble
("o", "C"): 0x2103,
("c", "o"): 0x2105,
("o", "F"): 0x2109,
("N", "0"): 0x2116,
("P", "O"): 0x2117,
("R", "x"): 0x211E,
("S", "M"): 0x2120,
("T", "M"): 0x2122,
("O", "m"): 0x2126,
("A", "O"): 0x212B,
("1", "3"): 0x2153,
("2", "3"): 0x2154,
("1", "5"): 0x2155,
("2", "5"): 0x2156,
("3", "5"): 0x2157,
("4", "5"): 0x2158,
("1", "6"): 0x2159,
("5", "6"): 0x215A,
("1", "8"): 0x215B,
("3", "8"): 0x215C,
("5", "8"): 0x215D,
("7", "8"): 0x215E,
("1", "R"): 0x2160,
("2", "R"): 0x2161,
("3", "R"): 0x2162,
("4", "R"): 0x2163,
("5", "R"): 0x2164,
("6", "R"): 0x2165,
("7", "R"): 0x2166,
("8", "R"): 0x2167,
("9", "R"): 0x2168,
("a", "R"): 0x2169,
("b", "R"): 0x216A,
("c", "R"): 0x216B,
("1", "r"): 0x2170,
("2", "r"): 0x2171,
("3", "r"): 0x2172,
("4", "r"): 0x2173,
("5", "r"): 0x2174,
("6", "r"): 0x2175,
("7", "r"): 0x2176,
("8", "r"): 0x2177,
("9", "r"): 0x2178,
("a", "r"): 0x2179,
("b", "r"): 0x217A,
("c", "r"): 0x217B,
("<", "-"): 0x2190,
("-", "!"): 0x2191,
("-", ">"): 0x2192,
("-", "v"): 0x2193,
("<", ">"): 0x2194,
("U", "D"): 0x2195,
("<", "="): 0x21D0,
("=", ">"): 0x21D2,
("=", "="): 0x21D4,
("F", "A"): 0x2200,
("d", "P"): 0x2202,
("T", "E"): 0x2203,
("/", "0"): 0x2205,
("D", "E"): 0x2206,
("N", "B"): 0x2207,
("(", "-"): 0x2208,
("-", ")"): 0x220B,
("*", "P"): 0x220F,
("+", "Z"): 0x2211,
("-", "2"): 0x2212,
("-", "+"): 0x2213,
("*", "-"): 0x2217,
("O", "b"): 0x2218,
("S", "b"): 0x2219,
("R", "T"): 0x221A,
("0", "("): 0x221D,
("0", "0"): 0x221E,
("-", "L"): 0x221F,
("-", "V"): 0x2220,
("P", "P"): 0x2225,
("A", "N"): 0x2227,
("O", "R"): 0x2228,
("(", "U"): 0x2229,
(")", "U"): 0x222A,
("I", "n"): 0x222B,
("D", "I"): 0x222C,
("I", "o"): 0x222E,
(".", ":"): 0x2234,
(":", "."): 0x2235,
(":", "R"): 0x2236,
(":", ":"): 0x2237,
("?", "1"): 0x223C,
("C", "G"): 0x223E,
("?", "-"): 0x2243,
("?", "="): 0x2245,
("?", "2"): 0x2248,
("=", "?"): 0x224C,
("H", "I"): 0x2253,
("!", "="): 0x2260,
("=", "3"): 0x2261,
("=", "<"): 0x2264,
(">", "="): 0x2265,
("<", "*"): 0x226A,
("*", ">"): 0x226B,
("!", "<"): 0x226E,
("!", ">"): 0x226F,
("(", "C"): 0x2282,
(")", "C"): 0x2283,
("(", "_"): 0x2286,
(")", "_"): 0x2287,
("0", "."): 0x2299,
("0", "2"): 0x229A,
("-", "T"): 0x22A5,
(".", "P"): 0x22C5,
(":", "3"): 0x22EE,
(".", "3"): 0x22EF,
("E", "h"): 0x2302,
("<", "7"): 0x2308,
(">", "7"): 0x2309,
("7", "<"): 0x230A,
("7", ">"): 0x230B,
("N", "I"): 0x2310,
("(", "A"): 0x2312,
("T", "R"): 0x2315,
("I", "u"): 0x2320,
("I", "l"): 0x2321,
("<", "/"): 0x2329,
("/", ">"): 0x232A,
("V", "s"): 0x2423,
("1", "h"): 0x2440,
("3", "h"): 0x2441,
("2", "h"): 0x2442,
("4", "h"): 0x2443,
("1", "j"): 0x2446,
("2", "j"): 0x2447,
("3", "j"): 0x2448,
("4", "j"): 0x2449,
("1", "."): 0x2488,
("2", "."): 0x2489,
("3", "."): 0x248A,
("4", "."): 0x248B,
("5", "."): 0x248C,
("6", "."): 0x248D,
("7", "."): 0x248E,
("8", "."): 0x248F,
("9", "."): 0x2490,
("h", "h"): 0x2500,
("H", "H"): 0x2501,
("v", "v"): 0x2502,
("V", "V"): 0x2503,
("3", "-"): 0x2504,
("3", "_"): 0x2505,
("3", "!"): 0x2506,
("3", "/"): 0x2507,
("4", "-"): 0x2508,
("4", "_"): 0x2509,
("4", "!"): 0x250A,
("4", "/"): 0x250B,
("d", "r"): 0x250C,
("d", "R"): 0x250D,
("D", "r"): 0x250E,
("D", "R"): 0x250F,
("d", "l"): 0x2510,
("d", "L"): 0x2511,
("D", "l"): 0x2512,
("L", "D"): 0x2513,
("u", "r"): 0x2514,
("u", "R"): 0x2515,
("U", "r"): 0x2516,
("U", "R"): 0x2517,
("u", "l"): 0x2518,
("u", "L"): 0x2519,
("U", "l"): 0x251A,
("U", "L"): 0x251B,
("v", "r"): 0x251C,
("v", "R"): 0x251D,
("V", "r"): 0x2520,
("V", "R"): 0x2523,
("v", "l"): 0x2524,
("v", "L"): 0x2525,
("V", "l"): 0x2528,
("V", "L"): 0x252B,
("d", "h"): 0x252C,
("d", "H"): 0x252F,
("D", "h"): 0x2530,
("D", "H"): 0x2533,
("u", "h"): 0x2534,
("u", "H"): 0x2537,
("U", "h"): 0x2538,
("U", "H"): 0x253B,
("v", "h"): 0x253C,
("v", "H"): 0x253F,
("V", "h"): 0x2542,
("V", "H"): 0x254B,
("F", "D"): 0x2571,
("B", "D"): 0x2572,
("T", "B"): 0x2580,
("L", "B"): 0x2584,
("F", "B"): 0x2588,
("l", "B"): 0x258C,
("R", "B"): 0x2590,
(".", "S"): 0x2591,
(":", "S"): 0x2592,
("?", "S"): 0x2593,
("f", "S"): 0x25A0,
("O", "S"): 0x25A1,
("R", "O"): 0x25A2,
("R", "r"): 0x25A3,
("R", "F"): 0x25A4,
("R", "Y"): 0x25A5,
("R", "H"): 0x25A6,
("R", "Z"): 0x25A7,
("R", "K"): 0x25A8,
("R", "X"): 0x25A9,
("s", "B"): 0x25AA,
("S", "R"): 0x25AC,
("O", "r"): 0x25AD,
("U", "T"): 0x25B2,
("u", "T"): 0x25B3,
("P", "R"): 0x25B6,
("T", "r"): 0x25B7,
("D", "t"): 0x25BC,
("d", "T"): 0x25BD,
("P", "L"): 0x25C0,
("T", "l"): 0x25C1,
("D", "b"): 0x25C6,
("D", "w"): 0x25C7,
("L", "Z"): 0x25CA,
("0", "m"): 0x25CB,
("0", "o"): 0x25CE,
("0", "M"): 0x25CF,
("0", "L"): 0x25D0,
("0", "R"): 0x25D1,
("S", "n"): 0x25D8,
("I", "c"): 0x25D9,
("F", "d"): 0x25E2,
("B", "d"): 0x25E3,
("*", "2"): 0x2605,
("*", "1"): 0x2606,
("<", "H"): 0x261C,
(">", "H"): 0x261E,
("0", "u"): 0x263A,
("0", "U"): 0x263B,
("S", "U"): 0x263C,
("F", "m"): 0x2640,
("M", "l"): 0x2642,
("c", "S"): 0x2660,
("c", "H"): 0x2661,
("c", "D"): 0x2662,
("c", "C"): 0x2663,
("M", "d"): 0x2669,
("M", "8"): 0x266A,
("M", "2"): 0x266B,
("M", "b"): 0x266D,
("M", "x"): 0x266E,
("M", "X"): 0x266F,
("O", "K"): 0x2713,
("X", "X"): 0x2717,
("-", "X"): 0x2720,
("I", "S"): 0x3000,
(",", "_"): 0x3001,
(".", "_"): 0x3002,
("+", '"'): 0x3003,
("+", "_"): 0x3004,
("*", "_"): 0x3005,
(";", "_"): 0x3006,
("0", "_"): 0x3007,
("<", "+"): 0x300A,
(">", "+"): 0x300B,
("<", "'"): 0x300C,
(">", "'"): 0x300D,
("<", '"'): 0x300E,
(">", '"'): 0x300F,
("(", '"'): 0x3010,
(")", '"'): 0x3011,
("=", "T"): 0x3012,
("=", "_"): 0x3013,
("(", "'"): 0x3014,
(")", "'"): 0x3015,
("(", "I"): 0x3016,
(")", "I"): 0x3017,
("-", "?"): 0x301C,
("A", "5"): 0x3041,
("a", "5"): 0x3042,
("I", "5"): 0x3043,
("i", "5"): 0x3044,
("U", "5"): 0x3045,
("u", "5"): 0x3046,
("E", "5"): 0x3047,
("e", "5"): 0x3048,
("O", "5"): 0x3049,
("o", "5"): 0x304A,
("k", "a"): 0x304B,
("g", "a"): 0x304C,
("k", "i"): 0x304D,
("g", "i"): 0x304E,
("k", "u"): 0x304F,
("g", "u"): 0x3050,
("k", "e"): 0x3051,
("g", "e"): 0x3052,
("k", "o"): 0x3053,
("g", "o"): 0x3054,
("s", "a"): 0x3055,
("z", "a"): 0x3056,
("s", "i"): 0x3057,
("z", "i"): 0x3058,
("s", "u"): 0x3059,
("z", "u"): 0x305A,
("s", "e"): 0x305B,
("z", "e"): 0x305C,
("s", "o"): 0x305D,
("z", "o"): 0x305E,
("t", "a"): 0x305F,
("d", "a"): 0x3060,
("t", "i"): 0x3061,
("d", "i"): 0x3062,
("t", "U"): 0x3063,
("t", "u"): 0x3064,
("d", "u"): 0x3065,
("t", "e"): 0x3066,
("d", "e"): 0x3067,
("t", "o"): 0x3068,
("d", "o"): 0x3069,
("n", "a"): 0x306A,
("n", "i"): 0x306B,
("n", "u"): 0x306C,
("n", "e"): 0x306D,
("n", "o"): 0x306E,
("h", "a"): 0x306F,
("b", "a"): 0x3070,
("p", "a"): 0x3071,
("h", "i"): 0x3072,
("b", "i"): 0x3073,
("p", "i"): 0x3074,
("h", "u"): 0x3075,
("b", "u"): 0x3076,
("p", "u"): 0x3077,
("h", "e"): 0x3078,
("b", "e"): 0x3079,
("p", "e"): 0x307A,
("h", "o"): 0x307B,
("b", "o"): 0x307C,
("p", "o"): 0x307D,
("m", "a"): 0x307E,
("m", "i"): 0x307F,
("m", "u"): 0x3080,
("m", "e"): 0x3081,
("m", "o"): 0x3082,
("y", "A"): 0x3083,
("y", "a"): 0x3084,
("y", "U"): 0x3085,
("y", "u"): 0x3086,
("y", "O"): 0x3087,
("y", "o"): 0x3088,
("r", "a"): 0x3089,
("r", "i"): 0x308A,
("r", "u"): 0x308B,
("r", "e"): 0x308C,
("r", "o"): 0x308D,
("w", "A"): 0x308E,
("w", "a"): 0x308F,
("w", "i"): 0x3090,
("w", "e"): 0x3091,
("w", "o"): 0x3092,
("n", "5"): 0x3093,
("v", "u"): 0x3094,
('"', "5"): 0x309B,
("0", "5"): 0x309C,
("*", "5"): 0x309D,
("+", "5"): 0x309E,
("a", "6"): 0x30A1,
("A", "6"): 0x30A2,
("i", "6"): 0x30A3,
("I", "6"): 0x30A4,
("u", "6"): 0x30A5,
("U", "6"): 0x30A6,
("e", "6"): 0x30A7,
("E", "6"): 0x30A8,
("o", "6"): 0x30A9,
("O", "6"): 0x30AA,
("K", "a"): 0x30AB,
("G", "a"): 0x30AC,
("K", "i"): 0x30AD,
("G", "i"): 0x30AE,
("K", "u"): 0x30AF,
("G", "u"): 0x30B0,
("K", "e"): 0x30B1,
("G", "e"): 0x30B2,
("K", "o"): 0x30B3,
("G", "o"): 0x30B4,
("S", "a"): 0x30B5,
("Z", "a"): 0x30B6,
("S", "i"): 0x30B7,
("Z", "i"): 0x30B8,
("S", "u"): 0x30B9,
("Z", "u"): 0x30BA,
("S", "e"): 0x30BB,
("Z", "e"): 0x30BC,
("S", "o"): 0x30BD,
("Z", "o"): 0x30BE,
("T", "a"): 0x30BF,
("D", "a"): 0x30C0,
("T", "i"): 0x30C1,
("D", "i"): 0x30C2,
("T", "U"): 0x30C3,
("T", "u"): 0x30C4,
("D", "u"): 0x30C5,
("T", "e"): 0x30C6,
("D", "e"): 0x30C7,
("T", "o"): 0x30C8,
("D", "o"): 0x30C9,
("N", "a"): 0x30CA,
("N", "i"): 0x30CB,
("N", "u"): 0x30CC,
("N", "e"): 0x30CD,
("N", "o"): 0x30CE,
("H", "a"): 0x30CF,
("B", "a"): 0x30D0,
("P", "a"): 0x30D1,
("H", "i"): 0x30D2,
("B", "i"): 0x30D3,
("P", "i"): 0x30D4,
("H", "u"): 0x30D5,
("B", "u"): 0x30D6,
("P", "u"): 0x30D7,
("H", "e"): 0x30D8,
("B", "e"): 0x30D9,
("P", "e"): 0x30DA,
("H", "o"): 0x30DB,
("B", "o"): 0x30DC,
("P", "o"): 0x30DD,
("M", "a"): 0x30DE,
("M", "i"): 0x30DF,
("M", "u"): 0x30E0,
("M", "e"): 0x30E1,
("M", "o"): 0x30E2,
("Y", "A"): 0x30E3,
("Y", "a"): 0x30E4,
("Y", "U"): 0x30E5,
("Y", "u"): 0x30E6,
("Y", "O"): 0x30E7,
("Y", "o"): 0x30E8,
("R", "a"): 0x30E9,
("R", "i"): 0x30EA,
("R", "u"): 0x30EB,
("R", "e"): 0x30EC,
("R", "o"): 0x30ED,
("W", "A"): 0x30EE,
("W", "a"): 0x30EF,
("W", "i"): 0x30F0,
("W", "e"): 0x30F1,
("W", "o"): 0x30F2,
("N", "6"): 0x30F3,
("V", "u"): 0x30F4,
("K", "A"): 0x30F5,
("K", "E"): 0x30F6,
("V", "a"): 0x30F7,
("V", "i"): 0x30F8,
("V", "e"): 0x30F9,
("V", "o"): 0x30FA,
(".", "6"): 0x30FB,
("-", "6"): 0x30FC,
("*", "6"): 0x30FD,
("+", "6"): 0x30FE,
("b", "4"): 0x3105,
("p", "4"): 0x3106,
("m", "4"): 0x3107,
("f", "4"): 0x3108,
("d", "4"): 0x3109,
("t", "4"): 0x310A,
("n", "4"): 0x310B,
("l", "4"): 0x310C,
("g", "4"): 0x310D,
("k", "4"): 0x310E,
("h", "4"): 0x310F,
("j", "4"): 0x3110,
("q", "4"): 0x3111,
("x", "4"): 0x3112,
("z", "h"): 0x3113,
("c", "h"): 0x3114,
("s", "h"): 0x3115,
("r", "4"): 0x3116,
("z", "4"): 0x3117,
("c", "4"): 0x3118,
("s", "4"): 0x3119,
("a", "4"): 0x311A,
("o", "4"): 0x311B,
("e", "4"): 0x311C,
("a", "i"): 0x311E,
("e", "i"): 0x311F,
("a", "u"): 0x3120,
("o", "u"): 0x3121,
("a", "n"): 0x3122,
("e", "n"): 0x3123,
("a", "N"): 0x3124,
("e", "N"): 0x3125,
("e", "r"): 0x3126,
("i", "4"): 0x3127,
("u", "4"): 0x3128,
("i", "u"): 0x3129,
("v", "4"): 0x312A,
("n", "G"): 0x312B,
("g", "n"): 0x312C,
("1", "c"): 0x3220,
("2", "c"): 0x3221,
("3", "c"): 0x3222,
("4", "c"): 0x3223,
("5", "c"): 0x3224,
("6", "c"): 0x3225,
("7", "c"): 0x3226,
("8", "c"): 0x3227,
("9", "c"): 0x3228,
# code points 0xe000 - 0xefff excluded, they have no assigned
# characters, only used in proposals.
("f", "f"): 0xFB00,
("f", "i"): 0xFB01,
("f", "l"): 0xFB02,
("f", "t"): 0xFB05,
("s", "t"): 0xFB06,
# Vim 5.x compatible digraphs that don't conflict with the above
("~", "!"): 161,
("c", "|"): 162,
("$", "$"): 163,
("o", "x"): 164, # currency symbol in ISO 8859-1
("Y", "-"): 165,
("|", "|"): 166,
("c", "O"): 169,
("-", ","): 172,
("-", "="): 175,
("~", "o"): 176,
("2", "2"): 178,
("3", "3"): 179,
("p", "p"): 182,
("~", "."): 183,
("1", "1"): 185,
("~", "?"): 191,
("A", "`"): 192,
("A", "^"): 194,
("A", "~"): 195,
("A", '"'): 196,
("A", "@"): 197,
("E", "`"): 200,
("E", "^"): 202,
("E", '"'): 203,
("I", "`"): 204,
("I", "^"): 206,
("I", '"'): 207,
("N", "~"): 209,
("O", "`"): 210,
("O", "^"): 212,
("O", "~"): 213,
("/", "\\"): 215, # multiplication symbol in ISO 8859-1
("U", "`"): 217,
("U", "^"): 219,
("I", "p"): 222,
("a", "`"): 224,
("a", "^"): 226,
("a", "~"): 227,
("a", '"'): 228,
("a", "@"): 229,
("e", "`"): 232,
("e", "^"): 234,
("e", '"'): 235,
("i", "`"): 236,
("i", "^"): 238,
("n", "~"): 241,
("o", "`"): 242,
("o", "^"): 244,
("o", "~"): 245,
("u", "`"): 249,
("u", "^"): 251,
("y", '"'): 255,
}
class KeyPress:
"""
:param key: A `Keys` instance or text (one character).
:param data: The received string on stdin. (Often vt100 escape codes.)
"""
def __init__(self, key: Keys | str, data: str | None = None) -> None:
assert isinstance(key, Keys) or len(key) == 1
if data is None:
if isinstance(key, Keys):
data = key.value
else:
data = key # 'key' is a one character string.
self.key = key
self.data = data
def __repr__(self) -> str:
return f"{self.__class__.__name__}(key={self.key!r}, data={self.data!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, KeyPress):
return False
return self.key == other.key and self.data == other.data
class InputMode(str, Enum):
value: str
INSERT = "vi-insert"
INSERT_MULTIPLE = "vi-insert-multiple"
NAVIGATION = "vi-navigation" # Normal mode.
REPLACE = "vi-replace"
REPLACE_SINGLE = "vi-replace-single"
class CharacterFind:
def __init__(self, character: str, backwards: bool = False) -> None:
self.character = character
self.backwards = backwards
class Keys(str, Enum):
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
value: str
Escape = "escape" # Also Control-[
ShiftEscape = "s-escape"
ControlAt = "c-@" # Also Control-Space.
ControlA = "c-a"
ControlB = "c-b"
ControlC = "c-c"
ControlD = "c-d"
ControlE = "c-e"
ControlF = "c-f"
ControlG = "c-g"
ControlH = "c-h"
ControlI = "c-i" # Tab
ControlJ = "c-j" # Newline
ControlK = "c-k"
ControlL = "c-l"
ControlM = "c-m" # Carriage return
ControlN = "c-n"
ControlO = "c-o"
ControlP = "c-p"
ControlQ = "c-q"
ControlR = "c-r"
ControlS = "c-s"
ControlT = "c-t"
ControlU = "c-u"
ControlV = "c-v"
ControlW = "c-w"
ControlX = "c-x"
ControlY = "c-y"
ControlZ = "c-z"
Control1 = "c-1"
Control2 = "c-2"
Control3 = "c-3"
Control4 = "c-4"
Control5 = "c-5"
Control6 = "c-6"
Control7 = "c-7"
Control8 = "c-8"
Control9 = "c-9"
Control0 = "c-0"
ControlShift1 = "c-s-1"
ControlShift2 = "c-s-2"
ControlShift3 = "c-s-3"
ControlShift4 = "c-s-4"
ControlShift5 = "c-s-5"
ControlShift6 = "c-s-6"
ControlShift7 = "c-s-7"
ControlShift8 = "c-s-8"
ControlShift9 = "c-s-9"
ControlShift0 = "c-s-0"
ControlBackslash = "c-\\"
ControlSquareClose = "c-]"
ControlCircumflex = "c-^"
ControlUnderscore = "c-_"
Left = "left"
Right = "right"
Up = "up"
Down = "down"
Home = "home"
End = "end"
Insert = "insert"
Delete = "delete"
PageUp = "pageup"
PageDown = "pagedown"
ControlLeft = "c-left"
ControlRight = "c-right"
ControlUp = "c-up"
ControlDown = "c-down"
ControlHome = "c-home"
ControlEnd = "c-end"
ControlInsert = "c-insert"
ControlDelete = "c-delete"
ControlPageUp = "c-pageup"
ControlPageDown = "c-pagedown"
ShiftLeft = "s-left"
ShiftRight = "s-right"
ShiftUp = "s-up"
ShiftDown = "s-down"
ShiftHome = "s-home"
ShiftEnd = "s-end"
ShiftInsert = "s-insert"
ShiftDelete = "s-delete"
ShiftPageUp = "s-pageup"
ShiftPageDown = "s-pagedown"
ControlShiftLeft = "c-s-left"
ControlShiftRight = "c-s-right"
ControlShiftUp = "c-s-up"
ControlShiftDown = "c-s-down"
ControlShiftHome = "c-s-home"
ControlShiftEnd = "c-s-end"
ControlShiftInsert = "c-s-insert"
ControlShiftDelete = "c-s-delete"
ControlShiftPageUp = "c-s-pageup"
ControlShiftPageDown = "c-s-pagedown"
BackTab = "s-tab" # shift + tab
F1 = "f1"
F2 = "f2"
F3 = "f3"
F4 = "f4"
F5 = "f5"
F6 = "f6"
F7 = "f7"
F8 = "f8"
F9 = "f9"
F10 = "f10"
F11 = "f11"
F12 = "f12"
F13 = "f13"
F14 = "f14"
F15 = "f15"
F16 = "f16"
F17 = "f17"
F18 = "f18"
F19 = "f19"
F20 = "f20"
F21 = "f21"
F22 = "f22"
F23 = "f23"
F24 = "f24"
ControlF1 = "c-f1"
ControlF2 = "c-f2"
ControlF3 = "c-f3"
ControlF4 = "c-f4"
ControlF5 = "c-f5"
ControlF6 = "c-f6"
ControlF7 = "c-f7"
ControlF8 = "c-f8"
ControlF9 = "c-f9"
ControlF10 = "c-f10"
ControlF11 = "c-f11"
ControlF12 = "c-f12"
ControlF13 = "c-f13"
ControlF14 = "c-f14"
ControlF15 = "c-f15"
ControlF16 = "c-f16"
ControlF17 = "c-f17"
ControlF18 = "c-f18"
ControlF19 = "c-f19"
ControlF20 = "c-f20"
ControlF21 = "c-f21"
ControlF22 = "c-f22"
ControlF23 = "c-f23"
ControlF24 = "c-f24"
# Matches any key.
Any = "<any>"
# Special.
ScrollUp = "<scroll-up>"
ScrollDown = "<scroll-down>"
CPRResponse = "<cursor-position-response>"
Vt100MouseEvent = "<vt100-mouse-event>"
WindowsMouseEvent = "<windows-mouse-event>"
BracketedPaste = "<bracketed-paste>"
SIGINT = "<sigint>"
# For internal use: key which is ignored.
# (The key binding for this key should not do anything.)
Ignore = "<ignore>"
# Some 'Key' aliases (for backwards-compatibility).
ControlSpace = ControlAt
Tab = ControlI
Enter = ControlM
Backspace = ControlH
# ShiftControl was renamed to ControlShift in
# 888fcb6fa4efea0de8333177e1bbc792f3ff3c24 (20 Feb 2020).
ShiftControlLeft = ControlShiftLeft
ShiftControlRight = ControlShiftRight
ShiftControlHome = ControlShiftHome
ShiftControlEnd = ControlShiftEnd
class SearchDirection(Enum):
FORWARD = "FORWARD"
BACKWARD = "BACKWARD"
class SelectionType(Enum):
"""
Type of selection.
"""
#: Characters. (Visual in Vi.)
CHARACTERS = "CHARACTERS"
#: Whole lines. (Visual-Line in Vi.)
LINES = "LINES"
#: A block selection. (Visual-Block in Vi.)
BLOCK = "BLOCK"
class PasteMode(Enum):
EMACS = "EMACS" # Yank like emacs.
VI_AFTER = "VI_AFTER" # When pressing 'p' in Vi.
VI_BEFORE = "VI_BEFORE" # When pressing 'P' in Vi.
class KeyBindingsBase(metaclass=ABCMeta):
"""
Interface for a KeyBindings.
"""
def _version(self) -> Hashable:
"""
For cache invalidation. - This should increase every time that
something changes.
"""
return 0
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle these keys.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
return []
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
return []
def bindings(self) -> list[Binding]:
"""
List of `Binding` objects.
(These need to be exposed, so that `KeyBindings` objects can be merged
together.)
"""
return []
# `add` and `remove` don't have to be part of this interface.
class KeyBindings(KeyBindingsBase):
"""
A container for a set of key bindings.
Example usage::
kb = KeyBindings()
def _(event):
print('Control-T pressed')
def _(event):
print('Control-A pressed, followed by Control-B')
def _(event):
print('Control-X pressed') # Works only if we are searching.
"""
def __init__(self) -> None:
self._bindings: list[Binding] = []
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)
self.__version = 0 # For cache invalidation.
def _clear_cache(self) -> None:
self.__version += 1
self._get_bindings_for_keys_cache.clear()
self._get_bindings_starting_with_keys_cache.clear()
def bindings(self) -> list[Binding]:
return self._bindings
def _version(self) -> Hashable:
return self.__version
def add(
self,
*keys: Keys | str,
filter: FilterOrBool = True,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
record_in_macro: FilterOrBool = True,
) -> Callable[[T], T]:
"""
Decorator for adding a key bindings.
:param filter: :class:`~prompt_toolkit.filters.Filter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param is_global: When this key bindings is added to a `Container` or
`Control`, make it a global (always active) binding.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.)
:param record_in_macro: Record these key bindings when a macro is
being recorded. (True by default.)
"""
assert keys
keys = tuple(_parse_key(k) for k in keys)
if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that
# case don't bother putting it in the key bindings. It will slow
# down every key press otherwise.
def decorator(func: T) -> T:
return func
else:
def decorator(func: T) -> T:
if isinstance(func, Binding):
# We're adding an existing Binding object.
self.bindings.append(
Binding(
keys,
func.handler,
filter=func.filter & to_filter(filter),
eager=to_filter(eager) | func.eager,
is_global=to_filter(is_global) | func.is_global,
save_before=func.save_before,
record_in_macro=func.record_in_macro,
)
)
else:
self.bindings.append(
Binding(
keys,
cast(KeyHandlerCallable, func),
filter=filter,
eager=eager,
is_global=is_global,
save_before=save_before,
record_in_macro=record_in_macro,
)
)
self._clear_cache()
return func
return decorator
def remove(self, *args: Keys | str | KeyHandlerCallable) -> None:
"""
Remove a key binding.
This expects either a function that was given to `add` method as
parameter or a sequence of key bindings.
Raises `ValueError` when no bindings was found.
Usage::
remove(handler) # Pass handler.
remove('c-x', 'c-a') # Or pass the key bindings.
"""
found = False
if callable(args[0]):
assert len(args) == 1
function = args[0]
# Remove the given function.
for b in self.bindings:
if b.handler == function:
self.bindings.remove(b)
found = True
else:
assert len(args) > 0
args = cast(Tuple[Union[Keys, str]], args)
# Remove this sequence of key bindings.
keys = tuple(_parse_key(k) for k in args)
for b in self.bindings:
if b.keys == keys:
self.bindings.remove(b)
found = True
if found:
self._clear_cache()
else:
# No key binding found for this function. Raise ValueError.
raise ValueError(f"Binding not found: {function!r}")
# For backwards-compatibility.
add_binding = add
remove_binding = remove
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle this key.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result: list[tuple[int, Binding]] = []
for b in self.bindings:
if len(keys) == len(b.keys):
match = True
any_count = 0
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if i == Keys.Any:
any_count += 1
if match:
result.append((any_count, b))
# Place bindings that have more 'Any' occurrences in them at the end.
result = sorted(result, key=lambda item: -item[0])
return [item[1] for item in result]
return self._get_bindings_for_keys_cache.get(keys, get)
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result = []
for b in self.bindings:
if len(keys) < len(b.keys):
match = True
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if match:
result.append(b)
return result
return self._get_bindings_starting_with_keys_cache.get(keys, get)
class ConditionalKeyBindings(_Proxy):
"""
Wraps around a `KeyBindings`. Disable/enable all the key bindings according to
the given (additional) filter.::
def setting_is_true():
return True # or False
registry = ConditionalKeyBindings(key_bindings, setting_is_true)
When new key bindings are added to this object. They are also
enable/disabled according to the given `filter`.
:param registries: List of :class:`.KeyBindings` objects.
:param filter: :class:`~prompt_toolkit.filters.Filter` object.
"""
def __init__(
self, key_bindings: KeyBindingsBase, filter: FilterOrBool = True
) -> None:
_Proxy.__init__(self)
self.key_bindings = key_bindings
self.filter = to_filter(filter)
def _update_cache(self) -> None:
"If the original key bindings was changed. Update our copy version."
expected_version = self.key_bindings._version
if self._last_version != expected_version:
bindings2 = KeyBindings()
# Copy all bindings from `self.key_bindings`, adding our condition.
for b in self.key_bindings.bindings:
bindings2.bindings.append(
Binding(
keys=b.keys,
handler=b.handler,
filter=self.filter & b.filter,
eager=b.eager,
is_global=b.is_global,
save_before=b.save_before,
record_in_macro=b.record_in_macro,
)
)
self._bindings2 = bindings2
self._last_version = expected_version
def get_by_name(name: str) -> Binding:
"""
Return the handler for the (Readline) command with the given name.
"""
try:
return _readline_commands[name]
except KeyError as e:
raise KeyError("Unknown Readline command: %r" % name) from e
The provided code snippet includes necessary dependencies for implementing the `load_vi_bindings` function. Write a Python function `def load_vi_bindings() -> KeyBindingsBase` to solve the following problem:
Vi extensions. # Overview of Readline Vi commands: # http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
Here is the function:
def load_vi_bindings() -> KeyBindingsBase:
"""
Vi extensions.
# Overview of Readline Vi commands:
# http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
"""
# Note: Some key bindings have the "~IsReadOnly()" filter added. This
# prevents the handler to be executed when the focus is on a
# read-only buffer.
# This is however only required for those that change the ViState to
# INSERT mode. The `Buffer` class itself throws the
# `EditReadOnlyBuffer` exception for any text operations which is
# handled correctly. There is no need to add "~IsReadOnly" to all key
# bindings that do text manipulation.
key_bindings = KeyBindings()
handle = key_bindings.add
# (Note: Always take the navigation bindings in read-only mode, even when
# ViState says different.)
TransformFunction = Tuple[Tuple[str, ...], Filter, Callable[[str], str]]
vi_transform_functions: list[TransformFunction] = [
# Rot 13 transformation
(
("g", "?"),
Always(),
lambda string: codecs.encode(string, "rot_13"),
),
# To lowercase
(("g", "u"), Always(), lambda string: string.lower()),
# To uppercase.
(("g", "U"), Always(), lambda string: string.upper()),
# Swap case.
(("g", "~"), Always(), lambda string: string.swapcase()),
(
("~",),
Condition(lambda: get_app().vi_state.tilde_operator),
lambda string: string.swapcase(),
),
]
# Insert a character literally (quoted insert).
handle("c-v", filter=vi_insert_mode)(get_by_name("quoted-insert"))
@handle("escape")
def _back_to_navigation(event: E) -> None:
"""
Escape goes to vi navigation mode.
"""
buffer = event.current_buffer
vi_state = event.app.vi_state
if vi_state.input_mode in (InputMode.INSERT, InputMode.REPLACE):
buffer.cursor_position += buffer.document.get_cursor_left_position()
vi_state.input_mode = InputMode.NAVIGATION
if bool(buffer.selection_state):
buffer.exit_selection()
@handle("k", filter=vi_selection_mode)
def _up_in_selection(event: E) -> None:
"""
Arrow up in selection mode.
"""
event.current_buffer.cursor_up(count=event.arg)
@handle("j", filter=vi_selection_mode)
def _down_in_selection(event: E) -> None:
"""
Arrow down in selection mode.
"""
event.current_buffer.cursor_down(count=event.arg)
@handle("up", filter=vi_navigation_mode)
@handle("c-p", filter=vi_navigation_mode)
def _up_in_navigation(event: E) -> None:
"""
Arrow up and ControlP in navigation mode go up.
"""
event.current_buffer.auto_up(count=event.arg)
@handle("k", filter=vi_navigation_mode)
def _go_up(event: E) -> None:
"""
Go up, but if we enter a new history entry, move to the start of the
line.
"""
event.current_buffer.auto_up(
count=event.arg, go_to_start_of_line_if_history_changes=True
)
@handle("down", filter=vi_navigation_mode)
@handle("c-n", filter=vi_navigation_mode)
def _go_down(event: E) -> None:
"""
Arrow down and Control-N in navigation mode.
"""
event.current_buffer.auto_down(count=event.arg)
@handle("j", filter=vi_navigation_mode)
def _go_down2(event: E) -> None:
"""
Go down, but if we enter a new history entry, go to the start of the line.
"""
event.current_buffer.auto_down(
count=event.arg, go_to_start_of_line_if_history_changes=True
)
@handle("backspace", filter=vi_navigation_mode)
def _go_left(event: E) -> None:
"""
In navigation-mode, move cursor.
"""
event.current_buffer.cursor_position += (
event.current_buffer.document.get_cursor_left_position(count=event.arg)
)
@handle("c-n", filter=vi_insert_mode)
def _complete_next(event: E) -> None:
b = event.current_buffer
if b.complete_state:
b.complete_next()
else:
b.start_completion(select_first=True)
@handle("c-p", filter=vi_insert_mode)
def _complete_prev(event: E) -> None:
"""
Control-P: To previous completion.
"""
b = event.current_buffer
if b.complete_state:
b.complete_previous()
else:
b.start_completion(select_last=True)
@handle("c-g", filter=vi_insert_mode)
@handle("c-y", filter=vi_insert_mode)
def _accept_completion(event: E) -> None:
"""
Accept current completion.
"""
event.current_buffer.complete_state = None
@handle("c-e", filter=vi_insert_mode)
def _cancel_completion(event: E) -> None:
"""
Cancel completion. Go back to originally typed text.
"""
event.current_buffer.cancel_completion()
@Condition
def is_returnable() -> bool:
return get_app().current_buffer.is_returnable
# In navigation mode, pressing enter will always return the input.
handle("enter", filter=vi_navigation_mode & is_returnable)(
get_by_name("accept-line")
)
# In insert mode, also accept input when enter is pressed, and the buffer
# has been marked as single line.
handle("enter", filter=is_returnable & ~is_multiline)(get_by_name("accept-line"))
@handle("enter", filter=~is_returnable & vi_navigation_mode)
def _start_of_next_line(event: E) -> None:
"""
Go to the beginning of next line.
"""
b = event.current_buffer
b.cursor_down(count=event.arg)
b.cursor_position += b.document.get_start_of_line_position(
after_whitespace=True
)
# ** In navigation mode **
# List of navigation commands: http://hea-www.harvard.edu/~fine/Tech/vi.html
@handle("insert", filter=vi_navigation_mode)
def _insert_mode(event: E) -> None:
"""
Pressing the Insert key.
"""
event.app.vi_state.input_mode = InputMode.INSERT
@handle("insert", filter=vi_insert_mode)
def _navigation_mode(event: E) -> None:
"""
Pressing the Insert key.
"""
event.app.vi_state.input_mode = InputMode.NAVIGATION
@handle("a", filter=vi_navigation_mode & ~is_read_only)
# ~IsReadOnly, because we want to stay in navigation mode for
# read-only buffers.
def _a(event: E) -> None:
event.current_buffer.cursor_position += (
event.current_buffer.document.get_cursor_right_position()
)
event.app.vi_state.input_mode = InputMode.INSERT
@handle("A", filter=vi_navigation_mode & ~is_read_only)
def _A(event: E) -> None:
event.current_buffer.cursor_position += (
event.current_buffer.document.get_end_of_line_position()
)
event.app.vi_state.input_mode = InputMode.INSERT
@handle("C", filter=vi_navigation_mode & ~is_read_only)
def _change_until_end_of_line(event: E) -> None:
"""
Change to end of line.
Same as 'c$' (which is implemented elsewhere.)
"""
buffer = event.current_buffer
deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
event.app.clipboard.set_text(deleted)
event.app.vi_state.input_mode = InputMode.INSERT
@handle("c", "c", filter=vi_navigation_mode & ~is_read_only)
@handle("S", filter=vi_navigation_mode & ~is_read_only)
def _change_current_line(event: E) -> None: # TODO: implement 'arg'
"""
Change current line
"""
buffer = event.current_buffer
# We copy the whole line.
data = ClipboardData(buffer.document.current_line, SelectionType.LINES)
event.app.clipboard.set_data(data)
# But we delete after the whitespace
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
buffer.delete(count=buffer.document.get_end_of_line_position())
event.app.vi_state.input_mode = InputMode.INSERT
@handle("D", filter=vi_navigation_mode)
def _delete_until_end_of_line(event: E) -> None:
"""
Delete from cursor position until the end of the line.
"""
buffer = event.current_buffer
deleted = buffer.delete(count=buffer.document.get_end_of_line_position())
event.app.clipboard.set_text(deleted)
@handle("d", "d", filter=vi_navigation_mode)
def _delete_line(event: E) -> None:
"""
Delete line. (Or the following 'n' lines.)
"""
buffer = event.current_buffer
# Split string in before/deleted/after text.
lines = buffer.document.lines
before = "\n".join(lines[: buffer.document.cursor_position_row])
deleted = "\n".join(
lines[
buffer.document.cursor_position_row : buffer.document.cursor_position_row
+ event.arg
]
)
after = "\n".join(lines[buffer.document.cursor_position_row + event.arg :])
# Set new text.
if before and after:
before = before + "\n"
# Set text and cursor position.
buffer.document = Document(
text=before + after,
# Cursor At the start of the first 'after' line, after the leading whitespace.
cursor_position=len(before) + len(after) - len(after.lstrip(" ")),
)
# Set clipboard data
event.app.clipboard.set_data(ClipboardData(deleted, SelectionType.LINES))
@handle("x", filter=vi_selection_mode)
def _cut(event: E) -> None:
"""
Cut selection.
('x' is not an operator.)
"""
clipboard_data = event.current_buffer.cut_selection()
event.app.clipboard.set_data(clipboard_data)
@handle("i", filter=vi_navigation_mode & ~is_read_only)
def _i(event: E) -> None:
event.app.vi_state.input_mode = InputMode.INSERT
@handle("I", filter=vi_navigation_mode & ~is_read_only)
def _I(event: E) -> None:
event.app.vi_state.input_mode = InputMode.INSERT
event.current_buffer.cursor_position += (
event.current_buffer.document.get_start_of_line_position(
after_whitespace=True
)
)
@Condition
def in_block_selection() -> bool:
buff = get_app().current_buffer
return bool(
buff.selection_state and buff.selection_state.type == SelectionType.BLOCK
)
@handle("I", filter=in_block_selection & ~is_read_only)
def insert_in_block_selection(event: E, after: bool = False) -> None:
"""
Insert in block selection mode.
"""
buff = event.current_buffer
# Store all cursor positions.
positions = []
if after:
def get_pos(from_to: tuple[int, int]) -> int:
return from_to[1]
else:
def get_pos(from_to: tuple[int, int]) -> int:
return from_to[0]
for i, from_to in enumerate(buff.document.selection_ranges()):
positions.append(get_pos(from_to))
if i == 0:
buff.cursor_position = get_pos(from_to)
buff.multiple_cursor_positions = positions
# Go to 'INSERT_MULTIPLE' mode.
event.app.vi_state.input_mode = InputMode.INSERT_MULTIPLE
buff.exit_selection()
@handle("A", filter=in_block_selection & ~is_read_only)
def _append_after_block(event: E) -> None:
insert_in_block_selection(event, after=True)
@handle("J", filter=vi_navigation_mode & ~is_read_only)
def _join(event: E) -> None:
"""
Join lines.
"""
for i in range(event.arg):
event.current_buffer.join_next_line()
@handle("g", "J", filter=vi_navigation_mode & ~is_read_only)
def _join_nospace(event: E) -> None:
"""
Join lines without space.
"""
for i in range(event.arg):
event.current_buffer.join_next_line(separator="")
@handle("J", filter=vi_selection_mode & ~is_read_only)
def _join_selection(event: E) -> None:
"""
Join selected lines.
"""
event.current_buffer.join_selected_lines()
@handle("g", "J", filter=vi_selection_mode & ~is_read_only)
def _join_selection_nospace(event: E) -> None:
"""
Join selected lines without space.
"""
event.current_buffer.join_selected_lines(separator="")
@handle("p", filter=vi_navigation_mode)
def _paste(event: E) -> None:
"""
Paste after
"""
event.current_buffer.paste_clipboard_data(
event.app.clipboard.get_data(),
count=event.arg,
paste_mode=PasteMode.VI_AFTER,
)
@handle("P", filter=vi_navigation_mode)
def _paste_before(event: E) -> None:
"""
Paste before
"""
event.current_buffer.paste_clipboard_data(
event.app.clipboard.get_data(),
count=event.arg,
paste_mode=PasteMode.VI_BEFORE,
)
@handle('"', Keys.Any, "p", filter=vi_navigation_mode)
def _paste_register(event: E) -> None:
"""
Paste from named register.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
data = event.app.vi_state.named_registers.get(c)
if data:
event.current_buffer.paste_clipboard_data(
data, count=event.arg, paste_mode=PasteMode.VI_AFTER
)
@handle('"', Keys.Any, "P", filter=vi_navigation_mode)
def _paste_register_before(event: E) -> None:
"""
Paste (before) from named register.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
data = event.app.vi_state.named_registers.get(c)
if data:
event.current_buffer.paste_clipboard_data(
data, count=event.arg, paste_mode=PasteMode.VI_BEFORE
)
@handle("r", filter=vi_navigation_mode)
def _replace(event: E) -> None:
"""
Go to 'replace-single'-mode.
"""
event.app.vi_state.input_mode = InputMode.REPLACE_SINGLE
@handle("R", filter=vi_navigation_mode)
def _replace_mode(event: E) -> None:
"""
Go to 'replace'-mode.
"""
event.app.vi_state.input_mode = InputMode.REPLACE
@handle("s", filter=vi_navigation_mode & ~is_read_only)
def _substitute(event: E) -> None:
"""
Substitute with new text
(Delete character(s) and go to insert mode.)
"""
text = event.current_buffer.delete(count=event.arg)
event.app.clipboard.set_text(text)
event.app.vi_state.input_mode = InputMode.INSERT
@handle("u", filter=vi_navigation_mode, save_before=(lambda e: False))
def _undo(event: E) -> None:
for i in range(event.arg):
event.current_buffer.undo()
@handle("V", filter=vi_navigation_mode)
def _visual_line(event: E) -> None:
"""
Start lines selection.
"""
event.current_buffer.start_selection(selection_type=SelectionType.LINES)
@handle("c-v", filter=vi_navigation_mode)
def _visual_block(event: E) -> None:
"""
Enter block selection mode.
"""
event.current_buffer.start_selection(selection_type=SelectionType.BLOCK)
@handle("V", filter=vi_selection_mode)
def _visual_line2(event: E) -> None:
"""
Exit line selection mode, or go from non line selection mode to line
selection mode.
"""
selection_state = event.current_buffer.selection_state
if selection_state is not None:
if selection_state.type != SelectionType.LINES:
selection_state.type = SelectionType.LINES
else:
event.current_buffer.exit_selection()
@handle("v", filter=vi_navigation_mode)
def _visual(event: E) -> None:
"""
Enter character selection mode.
"""
event.current_buffer.start_selection(selection_type=SelectionType.CHARACTERS)
@handle("v", filter=vi_selection_mode)
def _visual2(event: E) -> None:
"""
Exit character selection mode, or go from non-character-selection mode
to character selection mode.
"""
selection_state = event.current_buffer.selection_state
if selection_state is not None:
if selection_state.type != SelectionType.CHARACTERS:
selection_state.type = SelectionType.CHARACTERS
else:
event.current_buffer.exit_selection()
@handle("c-v", filter=vi_selection_mode)
def _visual_block2(event: E) -> None:
"""
Exit block selection mode, or go from non block selection mode to block
selection mode.
"""
selection_state = event.current_buffer.selection_state
if selection_state is not None:
if selection_state.type != SelectionType.BLOCK:
selection_state.type = SelectionType.BLOCK
else:
event.current_buffer.exit_selection()
@handle("a", "w", filter=vi_selection_mode)
@handle("a", "W", filter=vi_selection_mode)
def _visual_auto_word(event: E) -> None:
"""
Switch from visual linewise mode to visual characterwise mode.
"""
buffer = event.current_buffer
if (
buffer.selection_state
and buffer.selection_state.type == SelectionType.LINES
):
buffer.selection_state.type = SelectionType.CHARACTERS
@handle("x", filter=vi_navigation_mode)
def _delete(event: E) -> None:
"""
Delete character.
"""
buff = event.current_buffer
count = min(event.arg, len(buff.document.current_line_after_cursor))
if count:
text = event.current_buffer.delete(count=count)
event.app.clipboard.set_text(text)
@handle("X", filter=vi_navigation_mode)
def _delete_before_cursor(event: E) -> None:
buff = event.current_buffer
count = min(event.arg, len(buff.document.current_line_before_cursor))
if count:
text = event.current_buffer.delete_before_cursor(count=count)
event.app.clipboard.set_text(text)
@handle("y", "y", filter=vi_navigation_mode)
@handle("Y", filter=vi_navigation_mode)
def _yank_line(event: E) -> None:
"""
Yank the whole line.
"""
text = "\n".join(event.current_buffer.document.lines_from_current[: event.arg])
event.app.clipboard.set_data(ClipboardData(text, SelectionType.LINES))
@handle("+", filter=vi_navigation_mode)
def _next_line(event: E) -> None:
"""
Move to first non whitespace of next line
"""
buffer = event.current_buffer
buffer.cursor_position += buffer.document.get_cursor_down_position(
count=event.arg
)
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
@handle("-", filter=vi_navigation_mode)
def _prev_line(event: E) -> None:
"""
Move to first non whitespace of previous line
"""
buffer = event.current_buffer
buffer.cursor_position += buffer.document.get_cursor_up_position(
count=event.arg
)
buffer.cursor_position += buffer.document.get_start_of_line_position(
after_whitespace=True
)
@handle(">", ">", filter=vi_navigation_mode)
def _indent(event: E) -> None:
"""
Indent lines.
"""
buffer = event.current_buffer
current_row = buffer.document.cursor_position_row
indent(buffer, current_row, current_row + event.arg)
@handle("<", "<", filter=vi_navigation_mode)
def _unindent(event: E) -> None:
"""
Unindent lines.
"""
current_row = event.current_buffer.document.cursor_position_row
unindent(event.current_buffer, current_row, current_row + event.arg)
@handle("O", filter=vi_navigation_mode & ~is_read_only)
def _open_above(event: E) -> None:
"""
Open line above and enter insertion mode
"""
event.current_buffer.insert_line_above(copy_margin=not in_paste_mode())
event.app.vi_state.input_mode = InputMode.INSERT
@handle("o", filter=vi_navigation_mode & ~is_read_only)
def _open_below(event: E) -> None:
"""
Open line below and enter insertion mode
"""
event.current_buffer.insert_line_below(copy_margin=not in_paste_mode())
event.app.vi_state.input_mode = InputMode.INSERT
@handle("~", filter=vi_navigation_mode)
def _reverse_case(event: E) -> None:
"""
Reverse case of current character and move cursor forward.
"""
buffer = event.current_buffer
c = buffer.document.current_char
if c is not None and c != "\n":
buffer.insert_text(c.swapcase(), overwrite=True)
@handle("g", "u", "u", filter=vi_navigation_mode & ~is_read_only)
def _lowercase_line(event: E) -> None:
"""
Lowercase current line.
"""
buff = event.current_buffer
buff.transform_current_line(lambda s: s.lower())
@handle("g", "U", "U", filter=vi_navigation_mode & ~is_read_only)
def _uppercase_line(event: E) -> None:
"""
Uppercase current line.
"""
buff = event.current_buffer
buff.transform_current_line(lambda s: s.upper())
@handle("g", "~", "~", filter=vi_navigation_mode & ~is_read_only)
def _swapcase_line(event: E) -> None:
"""
Swap case of the current line.
"""
buff = event.current_buffer
buff.transform_current_line(lambda s: s.swapcase())
@handle("#", filter=vi_navigation_mode)
def _prev_occurence(event: E) -> None:
"""
Go to previous occurrence of this word.
"""
b = event.current_buffer
search_state = event.app.current_search_state
search_state.text = b.document.get_word_under_cursor()
search_state.direction = SearchDirection.BACKWARD
b.apply_search(search_state, count=event.arg, include_current_position=False)
@handle("*", filter=vi_navigation_mode)
def _next_occurance(event: E) -> None:
"""
Go to next occurrence of this word.
"""
b = event.current_buffer
search_state = event.app.current_search_state
search_state.text = b.document.get_word_under_cursor()
search_state.direction = SearchDirection.FORWARD
b.apply_search(search_state, count=event.arg, include_current_position=False)
@handle("(", filter=vi_navigation_mode)
def _begin_of_sentence(event: E) -> None:
# TODO: go to begin of sentence.
# XXX: should become text_object.
pass
@handle(")", filter=vi_navigation_mode)
def _end_of_sentence(event: E) -> None:
# TODO: go to end of sentence.
# XXX: should become text_object.
pass
operator = create_operator_decorator(key_bindings)
text_object = create_text_object_decorator(key_bindings)
@handle(Keys.Any, filter=vi_waiting_for_text_object_mode)
def _unknown_text_object(event: E) -> None:
"""
Unknown key binding while waiting for a text object.
"""
event.app.output.bell()
#
# *** Operators ***
#
def create_delete_and_change_operators(
delete_only: bool, with_register: bool = False
) -> None:
"""
Delete and change operators.
:param delete_only: Create an operator that deletes, but doesn't go to insert mode.
:param with_register: Copy the deleted text to this named register instead of the clipboard.
"""
handler_keys: Iterable[str]
if with_register:
handler_keys = ('"', Keys.Any, "cd"[delete_only])
else:
handler_keys = "cd"[delete_only]
@operator(*handler_keys, filter=~is_read_only)
def delete_or_change_operator(event: E, text_object: TextObject) -> None:
clipboard_data = None
buff = event.current_buffer
if text_object:
new_document, clipboard_data = text_object.cut(buff)
buff.document = new_document
# Set deleted/changed text to clipboard or named register.
if clipboard_data and clipboard_data.text:
if with_register:
reg_name = event.key_sequence[1].data
if reg_name in vi_register_names:
event.app.vi_state.named_registers[reg_name] = clipboard_data
else:
event.app.clipboard.set_data(clipboard_data)
# Only go back to insert mode in case of 'change'.
if not delete_only:
event.app.vi_state.input_mode = InputMode.INSERT
create_delete_and_change_operators(False, False)
create_delete_and_change_operators(False, True)
create_delete_and_change_operators(True, False)
create_delete_and_change_operators(True, True)
def create_transform_handler(
filter: Filter, transform_func: Callable[[str], str], *a: str
) -> None:
@operator(*a, filter=filter & ~is_read_only)
def _(event: E, text_object: TextObject) -> None:
"""
Apply transformation (uppercase, lowercase, rot13, swap case).
"""
buff = event.current_buffer
start, end = text_object.operator_range(buff.document)
if start < end:
# Transform.
buff.transform_region(
buff.cursor_position + start,
buff.cursor_position + end,
transform_func,
)
# Move cursor
buff.cursor_position += text_object.end or text_object.start
for k, f, func in vi_transform_functions:
create_transform_handler(f, func, *k)
@operator("y")
def _yank(event: E, text_object: TextObject) -> None:
"""
Yank operator. (Copy text.)
"""
_, clipboard_data = text_object.cut(event.current_buffer)
if clipboard_data.text:
event.app.clipboard.set_data(clipboard_data)
@operator('"', Keys.Any, "y")
def _yank_to_register(event: E, text_object: TextObject) -> None:
"""
Yank selection to named register.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
_, clipboard_data = text_object.cut(event.current_buffer)
event.app.vi_state.named_registers[c] = clipboard_data
@operator(">")
def _indent_text_object(event: E, text_object: TextObject) -> None:
"""
Indent.
"""
buff = event.current_buffer
from_, to = text_object.get_line_numbers(buff)
indent(buff, from_, to + 1, count=event.arg)
@operator("<")
def _unindent_text_object(event: E, text_object: TextObject) -> None:
"""
Unindent.
"""
buff = event.current_buffer
from_, to = text_object.get_line_numbers(buff)
unindent(buff, from_, to + 1, count=event.arg)
@operator("g", "q")
def _reshape(event: E, text_object: TextObject) -> None:
"""
Reshape text.
"""
buff = event.current_buffer
from_, to = text_object.get_line_numbers(buff)
reshape_text(buff, from_, to)
#
# *** Text objects ***
#
@text_object("b")
def _b(event: E) -> TextObject:
"""
Move one word or token left.
"""
return TextObject(
event.current_buffer.document.find_start_of_previous_word(count=event.arg)
or 0
)
@text_object("B")
def _B(event: E) -> TextObject:
"""
Move one non-blank word left
"""
return TextObject(
event.current_buffer.document.find_start_of_previous_word(
count=event.arg, WORD=True
)
or 0
)
@text_object("$")
def _dollar(event: E) -> TextObject:
"""
'c$', 'd$' and '$': Delete/change/move until end of line.
"""
return TextObject(event.current_buffer.document.get_end_of_line_position())
@text_object("w")
def _word_forward(event: E) -> TextObject:
"""
'word' forward. 'cw', 'dw', 'w': Delete/change/move one word.
"""
return TextObject(
event.current_buffer.document.find_next_word_beginning(count=event.arg)
or event.current_buffer.document.get_end_of_document_position()
)
@text_object("W")
def _WORD_forward(event: E) -> TextObject:
"""
'WORD' forward. 'cW', 'dW', 'W': Delete/change/move one WORD.
"""
return TextObject(
event.current_buffer.document.find_next_word_beginning(
count=event.arg, WORD=True
)
or event.current_buffer.document.get_end_of_document_position()
)
@text_object("e")
def _end_of_word(event: E) -> TextObject:
"""
End of 'word': 'ce', 'de', 'e'
"""
end = event.current_buffer.document.find_next_word_ending(count=event.arg)
return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
@text_object("E")
def _end_of_WORD(event: E) -> TextObject:
"""
End of 'WORD': 'cE', 'dE', 'E'
"""
end = event.current_buffer.document.find_next_word_ending(
count=event.arg, WORD=True
)
return TextObject(end - 1 if end else 0, type=TextObjectType.INCLUSIVE)
@text_object("i", "w", no_move_handler=True)
def _inner_word(event: E) -> TextObject:
"""
Inner 'word': ciw and diw
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word()
return TextObject(start, end)
@text_object("a", "w", no_move_handler=True)
def _a_word(event: E) -> TextObject:
"""
A 'word': caw and daw
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word(
include_trailing_whitespace=True
)
return TextObject(start, end)
@text_object("i", "W", no_move_handler=True)
def _inner_WORD(event: E) -> TextObject:
"""
Inner 'WORD': ciW and diW
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word(
WORD=True
)
return TextObject(start, end)
@text_object("a", "W", no_move_handler=True)
def _a_WORD(event: E) -> TextObject:
"""
A 'WORD': caw and daw
"""
start, end = event.current_buffer.document.find_boundaries_of_current_word(
WORD=True, include_trailing_whitespace=True
)
return TextObject(start, end)
@text_object("a", "p", no_move_handler=True)
def _paragraph(event: E) -> TextObject:
"""
Auto paragraph.
"""
start = event.current_buffer.document.start_of_paragraph()
end = event.current_buffer.document.end_of_paragraph(count=event.arg)
return TextObject(start, end)
@text_object("^")
def _start_of_line(event: E) -> TextObject:
"""'c^', 'd^' and '^': Soft start of line, after whitespace."""
return TextObject(
event.current_buffer.document.get_start_of_line_position(
after_whitespace=True
)
)
@text_object("0")
def _hard_start_of_line(event: E) -> TextObject:
"""
'c0', 'd0': Hard start of line, before whitespace.
(The move '0' key is implemented elsewhere, because a '0' could also change the `arg`.)
"""
return TextObject(
event.current_buffer.document.get_start_of_line_position(
after_whitespace=False
)
)
def create_ci_ca_handles(
ci_start: str, ci_end: str, inner: bool, key: str | None = None
) -> None:
# TODO: 'dat', 'dit', (tags (like xml)
"""
Delete/Change string between this start and stop character. But keep these characters.
This implements all the ci", ci<, ci{, ci(, di", di<, ca", ca<, ... combinations.
"""
def handler(event: E) -> TextObject:
if ci_start == ci_end:
# Quotes
start = event.current_buffer.document.find_backwards(
ci_start, in_current_line=False
)
end = event.current_buffer.document.find(ci_end, in_current_line=False)
else:
# Brackets
start = event.current_buffer.document.find_enclosing_bracket_left(
ci_start, ci_end
)
end = event.current_buffer.document.find_enclosing_bracket_right(
ci_start, ci_end
)
if start is not None and end is not None:
offset = 0 if inner else 1
return TextObject(start + 1 - offset, end + offset)
else:
# Nothing found.
return TextObject(0)
if key is None:
text_object("ai"[inner], ci_start, no_move_handler=True)(handler)
text_object("ai"[inner], ci_end, no_move_handler=True)(handler)
else:
text_object("ai"[inner], key, no_move_handler=True)(handler)
for inner in (False, True):
for ci_start, ci_end in [
('"', '"'),
("'", "'"),
("`", "`"),
("[", "]"),
("<", ">"),
("{", "}"),
("(", ")"),
]:
create_ci_ca_handles(ci_start, ci_end, inner)
create_ci_ca_handles("(", ")", inner, "b") # 'dab', 'dib'
create_ci_ca_handles("{", "}", inner, "B") # 'daB', 'diB'
@text_object("{")
def _previous_section(event: E) -> TextObject:
"""
Move to previous blank-line separated section.
Implements '{', 'c{', 'd{', 'y{'
"""
index = event.current_buffer.document.start_of_paragraph(
count=event.arg, before=True
)
return TextObject(index)
@text_object("}")
def _next_section(event: E) -> TextObject:
"""
Move to next blank-line separated section.
Implements '}', 'c}', 'd}', 'y}'
"""
index = event.current_buffer.document.end_of_paragraph(
count=event.arg, after=True
)
return TextObject(index)
@text_object("f", Keys.Any)
def _next_occurence(event: E) -> TextObject:
"""
Go to next occurrence of character. Typing 'fx' will move the
cursor to the next occurrence of character. 'x'.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, False)
match = event.current_buffer.document.find(
event.data, in_current_line=True, count=event.arg
)
if match:
return TextObject(match, type=TextObjectType.INCLUSIVE)
else:
return TextObject(0)
@text_object("F", Keys.Any)
def _previous_occurance(event: E) -> TextObject:
"""
Go to previous occurrence of character. Typing 'Fx' will move the
cursor to the previous occurrence of character. 'x'.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, True)
return TextObject(
event.current_buffer.document.find_backwards(
event.data, in_current_line=True, count=event.arg
)
or 0
)
@text_object("t", Keys.Any)
def _t(event: E) -> TextObject:
"""
Move right to the next occurrence of c, then one char backward.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, False)
match = event.current_buffer.document.find(
event.data, in_current_line=True, count=event.arg
)
if match:
return TextObject(match - 1, type=TextObjectType.INCLUSIVE)
else:
return TextObject(0)
@text_object("T", Keys.Any)
def _T(event: E) -> TextObject:
"""
Move left to the previous occurrence of c, then one char forward.
"""
event.app.vi_state.last_character_find = CharacterFind(event.data, True)
match = event.current_buffer.document.find_backwards(
event.data, in_current_line=True, count=event.arg
)
return TextObject(match + 1 if match else 0)
def repeat(reverse: bool) -> None:
"""
Create ',' and ';' commands.
"""
@text_object("," if reverse else ";")
def _(event: E) -> TextObject:
"""
Repeat the last 'f'/'F'/'t'/'T' command.
"""
pos: int | None = 0
vi_state = event.app.vi_state
type = TextObjectType.EXCLUSIVE
if vi_state.last_character_find:
char = vi_state.last_character_find.character
backwards = vi_state.last_character_find.backwards
if reverse:
backwards = not backwards
if backwards:
pos = event.current_buffer.document.find_backwards(
char, in_current_line=True, count=event.arg
)
else:
pos = event.current_buffer.document.find(
char, in_current_line=True, count=event.arg
)
type = TextObjectType.INCLUSIVE
if pos:
return TextObject(pos, type=type)
else:
return TextObject(0)
repeat(True)
repeat(False)
@text_object("h")
@text_object("left")
def _left(event: E) -> TextObject:
"""
Implements 'ch', 'dh', 'h': Cursor left.
"""
return TextObject(
event.current_buffer.document.get_cursor_left_position(count=event.arg)
)
@text_object("j", no_move_handler=True, no_selection_handler=True)
# Note: We also need `no_selection_handler`, because we in
# selection mode, we prefer the other 'j' binding that keeps
# `buffer.preferred_column`.
def _down(event: E) -> TextObject:
"""
Implements 'cj', 'dj', 'j', ... Cursor up.
"""
return TextObject(
event.current_buffer.document.get_cursor_down_position(count=event.arg),
type=TextObjectType.LINEWISE,
)
@text_object("k", no_move_handler=True, no_selection_handler=True)
def _up(event: E) -> TextObject:
"""
Implements 'ck', 'dk', 'k', ... Cursor up.
"""
return TextObject(
event.current_buffer.document.get_cursor_up_position(count=event.arg),
type=TextObjectType.LINEWISE,
)
@text_object("l")
@text_object(" ")
@text_object("right")
def _right(event: E) -> TextObject:
"""
Implements 'cl', 'dl', 'l', 'c ', 'd ', ' '. Cursor right.
"""
return TextObject(
event.current_buffer.document.get_cursor_right_position(count=event.arg)
)
@text_object("H")
def _top_of_screen(event: E) -> TextObject:
"""
Moves to the start of the visible region. (Below the scroll offset.)
Implements 'cH', 'dH', 'H'.
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the start of the visible area.
pos = (
b.document.translate_row_col_to_index(
w.render_info.first_visible_line(after_scroll_offset=True), 0
)
- b.cursor_position
)
else:
# Otherwise, move to the start of the input.
pos = -len(b.document.text_before_cursor)
return TextObject(pos, type=TextObjectType.LINEWISE)
@text_object("M")
def _middle_of_screen(event: E) -> TextObject:
"""
Moves cursor to the vertical center of the visible region.
Implements 'cM', 'dM', 'M'.
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the center of the visible area.
pos = (
b.document.translate_row_col_to_index(
w.render_info.center_visible_line(), 0
)
- b.cursor_position
)
else:
# Otherwise, move to the start of the input.
pos = -len(b.document.text_before_cursor)
return TextObject(pos, type=TextObjectType.LINEWISE)
@text_object("L")
def _end_of_screen(event: E) -> TextObject:
"""
Moves to the end of the visible region. (Above the scroll offset.)
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
# When we find a Window that has BufferControl showing this window,
# move to the end of the visible area.
pos = (
b.document.translate_row_col_to_index(
w.render_info.last_visible_line(before_scroll_offset=True), 0
)
- b.cursor_position
)
else:
# Otherwise, move to the end of the input.
pos = len(b.document.text_after_cursor)
return TextObject(pos, type=TextObjectType.LINEWISE)
@text_object("n", no_move_handler=True)
def _search_next(event: E) -> TextObject:
"""
Search next.
"""
buff = event.current_buffer
search_state = event.app.current_search_state
cursor_position = buff.get_search_position(
search_state, include_current_position=False, count=event.arg
)
return TextObject(cursor_position - buff.cursor_position)
@handle("n", filter=vi_navigation_mode)
def _search_next2(event: E) -> None:
"""
Search next in navigation mode. (This goes through the history.)
"""
search_state = event.app.current_search_state
event.current_buffer.apply_search(
search_state, include_current_position=False, count=event.arg
)
@text_object("N", no_move_handler=True)
def _search_previous(event: E) -> TextObject:
"""
Search previous.
"""
buff = event.current_buffer
search_state = event.app.current_search_state
cursor_position = buff.get_search_position(
~search_state, include_current_position=False, count=event.arg
)
return TextObject(cursor_position - buff.cursor_position)
@handle("N", filter=vi_navigation_mode)
def _search_previous2(event: E) -> None:
"""
Search previous in navigation mode. (This goes through the history.)
"""
search_state = event.app.current_search_state
event.current_buffer.apply_search(
~search_state, include_current_position=False, count=event.arg
)
@handle("z", "+", filter=vi_navigation_mode | vi_selection_mode)
@handle("z", "t", filter=vi_navigation_mode | vi_selection_mode)
@handle("z", "enter", filter=vi_navigation_mode | vi_selection_mode)
def _scroll_top(event: E) -> None:
"""
Scrolls the window to makes the current line the first line in the visible region.
"""
b = event.current_buffer
event.app.layout.current_window.vertical_scroll = b.document.cursor_position_row
@handle("z", "-", filter=vi_navigation_mode | vi_selection_mode)
@handle("z", "b", filter=vi_navigation_mode | vi_selection_mode)
def _scroll_bottom(event: E) -> None:
"""
Scrolls the window to makes the current line the last line in the visible region.
"""
# We can safely set the scroll offset to zero; the Window will make
# sure that it scrolls at least enough to make the cursor visible
# again.
event.app.layout.current_window.vertical_scroll = 0
@handle("z", "z", filter=vi_navigation_mode | vi_selection_mode)
def _scroll_center(event: E) -> None:
"""
Center Window vertically around cursor.
"""
w = event.app.layout.current_window
b = event.current_buffer
if w and w.render_info:
info = w.render_info
# Calculate the offset that we need in order to position the row
# containing the cursor in the center.
scroll_height = info.window_height // 2
y = max(0, b.document.cursor_position_row - 1)
height = 0
while y > 0:
line_height = info.get_height_for_line(y)
if height + line_height < scroll_height:
height += line_height
y -= 1
else:
break
w.vertical_scroll = y
@text_object("%")
def _goto_corresponding_bracket(event: E) -> TextObject:
"""
Implements 'c%', 'd%', '%, 'y%' (Move to corresponding bracket.)
If an 'arg' has been given, go this this % position in the file.
"""
buffer = event.current_buffer
if event._arg:
# If 'arg' has been given, the meaning of % is to go to the 'x%'
# row in the file.
if 0 < event.arg <= 100:
absolute_index = buffer.document.translate_row_col_to_index(
int((event.arg * buffer.document.line_count - 1) / 100), 0
)
return TextObject(
absolute_index - buffer.document.cursor_position,
type=TextObjectType.LINEWISE,
)
else:
return TextObject(0) # Do nothing.
else:
# Move to the corresponding opening/closing bracket (()'s, []'s and {}'s).
match = buffer.document.find_matching_bracket_position()
if match:
return TextObject(match, type=TextObjectType.INCLUSIVE)
else:
return TextObject(0)
@text_object("|")
def _to_column(event: E) -> TextObject:
"""
Move to the n-th column (you may specify the argument n by typing it on
number keys, for example, 20|).
"""
return TextObject(
event.current_buffer.document.get_column_cursor_position(event.arg - 1)
)
@text_object("g", "g")
def _goto_first_line(event: E) -> TextObject:
"""
Go to the start of the very first line.
Implements 'gg', 'cgg', 'ygg'
"""
d = event.current_buffer.document
if event._arg:
# Move to the given line.
return TextObject(
d.translate_row_col_to_index(event.arg - 1, 0) - d.cursor_position,
type=TextObjectType.LINEWISE,
)
else:
# Move to the top of the input.
return TextObject(
d.get_start_of_document_position(), type=TextObjectType.LINEWISE
)
@text_object("g", "_")
def _goto_last_line(event: E) -> TextObject:
"""
Go to last non-blank of line.
'g_', 'cg_', 'yg_', etc..
"""
return TextObject(
event.current_buffer.document.last_non_blank_of_current_line_position(),
type=TextObjectType.INCLUSIVE,
)
@text_object("g", "e")
def _ge(event: E) -> TextObject:
"""
Go to last character of previous word.
'ge', 'cge', 'yge', etc..
"""
prev_end = event.current_buffer.document.find_previous_word_ending(
count=event.arg
)
return TextObject(
prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE
)
@text_object("g", "E")
def _gE(event: E) -> TextObject:
"""
Go to last character of previous WORD.
'gE', 'cgE', 'ygE', etc..
"""
prev_end = event.current_buffer.document.find_previous_word_ending(
count=event.arg, WORD=True
)
return TextObject(
prev_end - 1 if prev_end is not None else 0, type=TextObjectType.INCLUSIVE
)
@text_object("g", "m")
def _gm(event: E) -> TextObject:
"""
Like g0, but half a screenwidth to the right. (Or as much as possible.)
"""
w = event.app.layout.current_window
buff = event.current_buffer
if w and w.render_info:
width = w.render_info.window_width
start = buff.document.get_start_of_line_position(after_whitespace=False)
start += int(min(width / 2, len(buff.document.current_line)))
return TextObject(start, type=TextObjectType.INCLUSIVE)
return TextObject(0)
@text_object("G")
def _last_line(event: E) -> TextObject:
"""
Go to the end of the document. (If no arg has been given.)
"""
buf = event.current_buffer
return TextObject(
buf.document.translate_row_col_to_index(buf.document.line_count - 1, 0)
- buf.cursor_position,
type=TextObjectType.LINEWISE,
)
#
# *** Other ***
#
@handle("G", filter=has_arg)
def _to_nth_history_line(event: E) -> None:
"""
If an argument is given, move to this line in the history. (for
example, 15G)
"""
event.current_buffer.go_to_history(event.arg - 1)
for n in "123456789":
@handle(
n,
filter=vi_navigation_mode
| vi_selection_mode
| vi_waiting_for_text_object_mode,
)
def _arg(event: E) -> None:
"""
Always handle numerics in navigation mode as arg.
"""
event.append_to_arg_count(event.data)
@handle(
"0",
filter=(
vi_navigation_mode | vi_selection_mode | vi_waiting_for_text_object_mode
)
& has_arg,
)
def _0_arg(event: E) -> None:
"""
Zero when an argument was already give.
"""
event.append_to_arg_count(event.data)
@handle(Keys.Any, filter=vi_replace_mode)
def _insert_text(event: E) -> None:
"""
Insert data at cursor position.
"""
event.current_buffer.insert_text(event.data, overwrite=True)
@handle(Keys.Any, filter=vi_replace_single_mode)
def _replace_single(event: E) -> None:
"""
Replace single character at cursor position.
"""
event.current_buffer.insert_text(event.data, overwrite=True)
event.current_buffer.cursor_position -= 1
event.app.vi_state.input_mode = InputMode.NAVIGATION
@handle(
Keys.Any,
filter=vi_insert_multiple_mode,
save_before=(lambda e: not e.is_repeat),
)
def _insert_text_multiple_cursors(event: E) -> None:
"""
Insert data at multiple cursor positions at once.
(Usually a result of pressing 'I' or 'A' in block-selection mode.)
"""
buff = event.current_buffer
original_text = buff.text
# Construct new text.
text = []
p = 0
for p2 in buff.multiple_cursor_positions:
text.append(original_text[p:p2])
text.append(event.data)
p = p2
text.append(original_text[p:])
# Shift all cursor positions.
new_cursor_positions = [
pos + i + 1 for i, pos in enumerate(buff.multiple_cursor_positions)
]
# Set result.
buff.text = "".join(text)
buff.multiple_cursor_positions = new_cursor_positions
buff.cursor_position += 1
@handle("backspace", filter=vi_insert_multiple_mode)
def _delete_before_multiple_cursors(event: E) -> None:
"""
Backspace, using multiple cursors.
"""
buff = event.current_buffer
original_text = buff.text
# Construct new text.
deleted_something = False
text = []
p = 0
for p2 in buff.multiple_cursor_positions:
if p2 > 0 and original_text[p2 - 1] != "\n": # Don't delete across lines.
text.append(original_text[p : p2 - 1])
deleted_something = True
else:
text.append(original_text[p:p2])
p = p2
text.append(original_text[p:])
if deleted_something:
# Shift all cursor positions.
lengths = [len(part) for part in text[:-1]]
new_cursor_positions = list(accumulate(lengths))
# Set result.
buff.text = "".join(text)
buff.multiple_cursor_positions = new_cursor_positions
buff.cursor_position -= 1
else:
event.app.output.bell()
@handle("delete", filter=vi_insert_multiple_mode)
def _delete_after_multiple_cursors(event: E) -> None:
"""
Delete, using multiple cursors.
"""
buff = event.current_buffer
original_text = buff.text
# Construct new text.
deleted_something = False
text = []
new_cursor_positions = []
p = 0
for p2 in buff.multiple_cursor_positions:
text.append(original_text[p:p2])
if p2 >= len(original_text) or original_text[p2] == "\n":
# Don't delete across lines.
p = p2
else:
p = p2 + 1
deleted_something = True
text.append(original_text[p:])
if deleted_something:
# Shift all cursor positions.
lengths = [len(part) for part in text[:-1]]
new_cursor_positions = list(accumulate(lengths))
# Set result.
buff.text = "".join(text)
buff.multiple_cursor_positions = new_cursor_positions
else:
event.app.output.bell()
@handle("left", filter=vi_insert_multiple_mode)
def _left_multiple(event: E) -> None:
"""
Move all cursors to the left.
(But keep all cursors on the same line.)
"""
buff = event.current_buffer
new_positions = []
for p in buff.multiple_cursor_positions:
if buff.document.translate_index_to_position(p)[1] > 0:
p -= 1
new_positions.append(p)
buff.multiple_cursor_positions = new_positions
if buff.document.cursor_position_col > 0:
buff.cursor_position -= 1
@handle("right", filter=vi_insert_multiple_mode)
def _right_multiple(event: E) -> None:
"""
Move all cursors to the right.
(But keep all cursors on the same line.)
"""
buff = event.current_buffer
new_positions = []
for p in buff.multiple_cursor_positions:
row, column = buff.document.translate_index_to_position(p)
if column < len(buff.document.lines[row]):
p += 1
new_positions.append(p)
buff.multiple_cursor_positions = new_positions
if not buff.document.is_cursor_at_the_end_of_line:
buff.cursor_position += 1
@handle("up", filter=vi_insert_multiple_mode)
@handle("down", filter=vi_insert_multiple_mode)
def _updown_multiple(event: E) -> None:
"""
Ignore all up/down key presses when in multiple cursor mode.
"""
@handle("c-x", "c-l", filter=vi_insert_mode)
def _complete_line(event: E) -> None:
"""
Pressing the ControlX - ControlL sequence in Vi mode does line
completion based on the other lines in the document and the history.
"""
event.current_buffer.start_history_lines_completion()
@handle("c-x", "c-f", filter=vi_insert_mode)
def _complete_filename(event: E) -> None:
"""
Complete file names.
"""
# TODO
pass
@handle("c-k", filter=vi_insert_mode | vi_replace_mode)
def _digraph(event: E) -> None:
"""
Go into digraph mode.
"""
event.app.vi_state.waiting_for_digraph = True
@Condition
def digraph_symbol_1_given() -> bool:
return get_app().vi_state.digraph_symbol1 is not None
@handle(Keys.Any, filter=vi_digraph_mode & ~digraph_symbol_1_given)
def _digraph1(event: E) -> None:
"""
First digraph symbol.
"""
event.app.vi_state.digraph_symbol1 = event.data
@handle(Keys.Any, filter=vi_digraph_mode & digraph_symbol_1_given)
def _create_digraph(event: E) -> None:
"""
Insert digraph.
"""
try:
# Lookup.
code: tuple[str, str] = (
event.app.vi_state.digraph_symbol1 or "",
event.data,
)
if code not in DIGRAPHS:
code = code[::-1] # Try reversing.
symbol = DIGRAPHS[code]
except KeyError:
# Unknown digraph.
event.app.output.bell()
else:
# Insert digraph.
overwrite = event.app.vi_state.input_mode == InputMode.REPLACE
event.current_buffer.insert_text(chr(symbol), overwrite=overwrite)
event.app.vi_state.waiting_for_digraph = False
finally:
event.app.vi_state.waiting_for_digraph = False
event.app.vi_state.digraph_symbol1 = None
@handle("c-o", filter=vi_insert_mode | vi_replace_mode)
def _quick_normal_mode(event: E) -> None:
"""
Go into normal mode for one single action.
"""
event.app.vi_state.temporary_navigation_mode = True
@handle("q", Keys.Any, filter=vi_navigation_mode & ~vi_recording_macro)
def _start_macro(event: E) -> None:
"""
Start recording macro.
"""
c = event.key_sequence[1].data
if c in vi_register_names:
vi_state = event.app.vi_state
vi_state.recording_register = c
vi_state.current_recording = ""
@handle("q", filter=vi_navigation_mode & vi_recording_macro)
def _stop_macro(event: E) -> None:
"""
Stop recording macro.
"""
vi_state = event.app.vi_state
# Store and stop recording.
if vi_state.recording_register:
vi_state.named_registers[vi_state.recording_register] = ClipboardData(
vi_state.current_recording
)
vi_state.recording_register = None
vi_state.current_recording = ""
@handle("@", Keys.Any, filter=vi_navigation_mode, record_in_macro=False)
def _execute_macro(event: E) -> None:
"""
Execute macro.
Notice that we pass `record_in_macro=False`. This ensures that the `@x`
keys don't appear in the recording itself. This function inserts the
body of the called macro back into the KeyProcessor, so these keys will
be added later on to the macro of their handlers have
`record_in_macro=True`.
"""
# Retrieve macro.
c = event.key_sequence[1].data
try:
macro = event.app.vi_state.named_registers[c]
except KeyError:
return
# Expand macro (which is a string in the register), in individual keys.
# Use vt100 parser for this.
keys: list[KeyPress] = []
parser = Vt100Parser(keys.append)
parser.feed(macro.text)
parser.flush()
# Now feed keys back to the input processor.
for _ in range(event.arg):
event.app.key_processor.feed_multiple(keys, first=True)
return ConditionalKeyBindings(key_bindings, vi_mode) | Vi extensions. # Overview of Readline Vi commands: # http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf |
172,114 | from __future__ import annotations
import codecs
import string
from enum import Enum
from itertools import accumulate
from typing import Callable, Iterable, List, Optional, Tuple, TypeVar, Union
from prompt_toolkit.application.current import get_app
from prompt_toolkit.buffer import Buffer, indent, reshape_text, unindent
from prompt_toolkit.clipboard import ClipboardData
from prompt_toolkit.document import Document
from prompt_toolkit.filters import (
Always,
Condition,
Filter,
has_arg,
is_read_only,
is_searching,
)
from prompt_toolkit.filters.app import (
in_paste_mode,
is_multiline,
vi_digraph_mode,
vi_insert_mode,
vi_insert_multiple_mode,
vi_mode,
vi_navigation_mode,
vi_recording_macro,
vi_replace_mode,
vi_replace_single_mode,
vi_search_direction_reversed,
vi_selection_mode,
vi_waiting_for_text_object_mode,
)
from prompt_toolkit.input.vt100_parser import Vt100Parser
from prompt_toolkit.key_binding.digraphs import DIGRAPHS
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.key_binding.vi_state import CharacterFind, InputMode
from prompt_toolkit.keys import Keys
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.selection import PasteMode, SelectionState, SelectionType
from ..key_bindings import ConditionalKeyBindings, KeyBindings, KeyBindingsBase
from .named_commands import get_by_name
def load_vi_bindings() -> KeyBindingsBase:
"""
Vi extensions.
# Overview of Readline Vi commands:
# http://www.catonmat.net/download/bash-vi-editing-mode-cheat-sheet.pdf
"""
# Note: Some key bindings have the "~IsReadOnly()" filter added. This
# prevents the handler to be executed when the focus is on a
# read-only buffer.
# This is however only required for those that change the ViState to
# INSERT mode. The `Buffer` class itself throws the
# `EditReadOnlyBuffer` exception for any text operations which is
# handled correctly. There is no need to add "~IsReadOnly" to all key
# bindings that do text manipulation.
key_bindings = KeyBindings()
handle = key_bindings.add
# (Note: Always take the navigation bindings in read-only mode, even when
# ViState says different.)
TransformFunction = Tuple[Tuple[str, ...], Filter, Callable[[str], str]]
vi_transform_functions: list[TransformFunction] = [
# Rot 13 transformation
(
("g", "?"),
Always(),
lambda string: codecs.encode(string, "rot_13"),
),
# To lowercase
(("g", "u"), Always(), lambda string: string.lower()),
# To uppercase.
(("g", "U"), Always(), lambda string: string.upper()),
# Swap case.
(("g", "~"), Always(), lambda string: string.swapcase()),
(
("~",),
Condition(lambda: get_app().vi_state.tilde_operator),
lambda string: string.swapcase(),
),
]
# Insert a character literally (quoted insert).
handle("c-v", filter=vi_insert_mode)(get_by_name("quoted-insert"))
# In navigation mode, pressing enter will always return the input.
handle("enter", filter=vi_navigation_mode & is_returnable)(
get_by_name("accept-line")
)
# In insert mode, also accept input when enter is pressed, and the buffer
# has been marked as single line.
handle("enter", filter=is_returnable & ~is_multiline)(get_by_name("accept-line"))
# ** In navigation mode **
# List of navigation commands: http://hea-www.harvard.edu/~fine/Tech/vi.html
# ~IsReadOnly, because we want to stay in navigation mode for
# read-only buffers.
operator = create_operator_decorator(key_bindings)
text_object = create_text_object_decorator(key_bindings)
#
# *** Operators ***
#
create_delete_and_change_operators(False, False)
create_delete_and_change_operators(False, True)
create_delete_and_change_operators(True, False)
create_delete_and_change_operators(True, True)
for k, f, func in vi_transform_functions:
create_transform_handler(f, func, *k)
#
# *** Text objects ***
#
for inner in (False, True):
for ci_start, ci_end in [
('"', '"'),
("'", "'"),
("`", "`"),
("[", "]"),
("<", ">"),
("{", "}"),
("(", ")"),
]:
create_ci_ca_handles(ci_start, ci_end, inner)
create_ci_ca_handles("(", ")", inner, "b") # 'dab', 'dib'
create_ci_ca_handles("{", "}", inner, "B") # 'daB', 'diB'
repeat(True)
repeat(False)
# Note: We also need `no_selection_handler`, because we in
# selection mode, we prefer the other 'j' binding that keeps
# `buffer.preferred_column`.
#
# *** Other ***
#
for n in "123456789":
n,
filter=vi_navigation_mode
| vi_selection_mode
| vi_waiting_for_text_object_mode,
)
"0",
filter=(
vi_navigation_mode | vi_selection_mode | vi_waiting_for_text_object_mode
)
& has_arg,
)
)
return ConditionalKeyBindings(key_bindings, vi_mode)
def load_vi_search_bindings() -> KeyBindingsBase:
key_bindings = KeyBindings()
handle = key_bindings.add
from . import search
def search_buffer_is_empty() -> bool:
"Returns True when the search buffer is empty."
return get_app().current_buffer.text == ""
# Vi-style forward search.
handle(
"/",
filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
)(search.start_forward_incremental_search)
handle(
"?",
filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
)(search.start_forward_incremental_search)
handle("c-s")(search.start_forward_incremental_search)
# Vi-style backward search.
handle(
"?",
filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
)(search.start_reverse_incremental_search)
handle(
"/",
filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
)(search.start_reverse_incremental_search)
handle("c-r")(search.start_reverse_incremental_search)
# Apply the search. (At the / or ? prompt.)
handle("enter", filter=is_searching)(search.accept_search)
handle("c-r", filter=is_searching)(search.reverse_incremental_search)
handle("c-s", filter=is_searching)(search.forward_incremental_search)
handle("c-c")(search.abort_search)
handle("c-g")(search.abort_search)
handle("backspace", filter=search_buffer_is_empty)(search.abort_search)
# Handle escape. This should accept the search, just like readline.
# `abort_search` would be a meaningful alternative.
handle("escape")(search.accept_search)
return ConditionalKeyBindings(key_bindings, vi_mode)
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
def vi_mode() -> bool:
return get_app().editing_mode == EditingMode.VI
def vi_navigation_mode() -> bool:
"""
Active when the set for Vi navigation key bindings are active.
"""
from prompt_toolkit.key_binding.vi_state import InputMode
app = get_app()
if (
app.editing_mode != EditingMode.VI
or app.vi_state.operator_func
or app.vi_state.waiting_for_digraph
or app.current_buffer.selection_state
):
return False
return (
app.vi_state.input_mode == InputMode.NAVIGATION
or app.vi_state.temporary_navigation_mode
or app.current_buffer.read_only()
)
def vi_selection_mode() -> bool:
app = get_app()
if app.editing_mode != EditingMode.VI:
return False
return bool(app.current_buffer.selection_state)
def vi_search_direction_reversed() -> bool:
"When the '/' and '?' key bindings for Vi-style searching have been reversed."
return get_app().reverse_vi_search_direction()
class KeyBindingsBase(metaclass=ABCMeta):
"""
Interface for a KeyBindings.
"""
def _version(self) -> Hashable:
"""
For cache invalidation. - This should increase every time that
something changes.
"""
return 0
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle these keys.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
return []
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
return []
def bindings(self) -> list[Binding]:
"""
List of `Binding` objects.
(These need to be exposed, so that `KeyBindings` objects can be merged
together.)
"""
return []
# `add` and `remove` don't have to be part of this interface.
class KeyBindings(KeyBindingsBase):
"""
A container for a set of key bindings.
Example usage::
kb = KeyBindings()
def _(event):
print('Control-T pressed')
def _(event):
print('Control-A pressed, followed by Control-B')
def _(event):
print('Control-X pressed') # Works only if we are searching.
"""
def __init__(self) -> None:
self._bindings: list[Binding] = []
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)
self.__version = 0 # For cache invalidation.
def _clear_cache(self) -> None:
self.__version += 1
self._get_bindings_for_keys_cache.clear()
self._get_bindings_starting_with_keys_cache.clear()
def bindings(self) -> list[Binding]:
return self._bindings
def _version(self) -> Hashable:
return self.__version
def add(
self,
*keys: Keys | str,
filter: FilterOrBool = True,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
record_in_macro: FilterOrBool = True,
) -> Callable[[T], T]:
"""
Decorator for adding a key bindings.
:param filter: :class:`~prompt_toolkit.filters.Filter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param is_global: When this key bindings is added to a `Container` or
`Control`, make it a global (always active) binding.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.)
:param record_in_macro: Record these key bindings when a macro is
being recorded. (True by default.)
"""
assert keys
keys = tuple(_parse_key(k) for k in keys)
if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that
# case don't bother putting it in the key bindings. It will slow
# down every key press otherwise.
def decorator(func: T) -> T:
return func
else:
def decorator(func: T) -> T:
if isinstance(func, Binding):
# We're adding an existing Binding object.
self.bindings.append(
Binding(
keys,
func.handler,
filter=func.filter & to_filter(filter),
eager=to_filter(eager) | func.eager,
is_global=to_filter(is_global) | func.is_global,
save_before=func.save_before,
record_in_macro=func.record_in_macro,
)
)
else:
self.bindings.append(
Binding(
keys,
cast(KeyHandlerCallable, func),
filter=filter,
eager=eager,
is_global=is_global,
save_before=save_before,
record_in_macro=record_in_macro,
)
)
self._clear_cache()
return func
return decorator
def remove(self, *args: Keys | str | KeyHandlerCallable) -> None:
"""
Remove a key binding.
This expects either a function that was given to `add` method as
parameter or a sequence of key bindings.
Raises `ValueError` when no bindings was found.
Usage::
remove(handler) # Pass handler.
remove('c-x', 'c-a') # Or pass the key bindings.
"""
found = False
if callable(args[0]):
assert len(args) == 1
function = args[0]
# Remove the given function.
for b in self.bindings:
if b.handler == function:
self.bindings.remove(b)
found = True
else:
assert len(args) > 0
args = cast(Tuple[Union[Keys, str]], args)
# Remove this sequence of key bindings.
keys = tuple(_parse_key(k) for k in args)
for b in self.bindings:
if b.keys == keys:
self.bindings.remove(b)
found = True
if found:
self._clear_cache()
else:
# No key binding found for this function. Raise ValueError.
raise ValueError(f"Binding not found: {function!r}")
# For backwards-compatibility.
add_binding = add
remove_binding = remove
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle this key.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result: list[tuple[int, Binding]] = []
for b in self.bindings:
if len(keys) == len(b.keys):
match = True
any_count = 0
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if i == Keys.Any:
any_count += 1
if match:
result.append((any_count, b))
# Place bindings that have more 'Any' occurrences in them at the end.
result = sorted(result, key=lambda item: -item[0])
return [item[1] for item in result]
return self._get_bindings_for_keys_cache.get(keys, get)
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result = []
for b in self.bindings:
if len(keys) < len(b.keys):
match = True
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if match:
result.append(b)
return result
return self._get_bindings_starting_with_keys_cache.get(keys, get)
class ConditionalKeyBindings(_Proxy):
"""
Wraps around a `KeyBindings`. Disable/enable all the key bindings according to
the given (additional) filter.::
def setting_is_true():
return True # or False
registry = ConditionalKeyBindings(key_bindings, setting_is_true)
When new key bindings are added to this object. They are also
enable/disabled according to the given `filter`.
:param registries: List of :class:`.KeyBindings` objects.
:param filter: :class:`~prompt_toolkit.filters.Filter` object.
"""
def __init__(
self, key_bindings: KeyBindingsBase, filter: FilterOrBool = True
) -> None:
_Proxy.__init__(self)
self.key_bindings = key_bindings
self.filter = to_filter(filter)
def _update_cache(self) -> None:
"If the original key bindings was changed. Update our copy version."
expected_version = self.key_bindings._version
if self._last_version != expected_version:
bindings2 = KeyBindings()
# Copy all bindings from `self.key_bindings`, adding our condition.
for b in self.key_bindings.bindings:
bindings2.bindings.append(
Binding(
keys=b.keys,
handler=b.handler,
filter=self.filter & b.filter,
eager=b.eager,
is_global=b.is_global,
save_before=b.save_before,
record_in_macro=b.record_in_macro,
)
)
self._bindings2 = bindings2
self._last_version = expected_version
def load_vi_search_bindings() -> KeyBindingsBase:
key_bindings = KeyBindings()
handle = key_bindings.add
from . import search
@Condition
def search_buffer_is_empty() -> bool:
"Returns True when the search buffer is empty."
return get_app().current_buffer.text == ""
# Vi-style forward search.
handle(
"/",
filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
)(search.start_forward_incremental_search)
handle(
"?",
filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
)(search.start_forward_incremental_search)
handle("c-s")(search.start_forward_incremental_search)
# Vi-style backward search.
handle(
"?",
filter=(vi_navigation_mode | vi_selection_mode) & ~vi_search_direction_reversed,
)(search.start_reverse_incremental_search)
handle(
"/",
filter=(vi_navigation_mode | vi_selection_mode) & vi_search_direction_reversed,
)(search.start_reverse_incremental_search)
handle("c-r")(search.start_reverse_incremental_search)
# Apply the search. (At the / or ? prompt.)
handle("enter", filter=is_searching)(search.accept_search)
handle("c-r", filter=is_searching)(search.reverse_incremental_search)
handle("c-s", filter=is_searching)(search.forward_incremental_search)
handle("c-c")(search.abort_search)
handle("c-g")(search.abort_search)
handle("backspace", filter=search_buffer_is_empty)(search.abort_search)
# Handle escape. This should accept the search, just like readline.
# `abort_search` would be a meaningful alternative.
handle("escape")(search.accept_search)
return ConditionalKeyBindings(key_bindings, vi_mode) | null |
172,115 | from __future__ import annotations
import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition, emacs_mode
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
E = KeyPressEvent
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class KeyBindings(KeyBindingsBase):
"""
A container for a set of key bindings.
Example usage::
kb = KeyBindings()
def _(event):
print('Control-T pressed')
def _(event):
print('Control-A pressed, followed by Control-B')
def _(event):
print('Control-X pressed') # Works only if we are searching.
"""
def __init__(self) -> None:
self._bindings: list[Binding] = []
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)
self.__version = 0 # For cache invalidation.
def _clear_cache(self) -> None:
self.__version += 1
self._get_bindings_for_keys_cache.clear()
self._get_bindings_starting_with_keys_cache.clear()
def bindings(self) -> list[Binding]:
return self._bindings
def _version(self) -> Hashable:
return self.__version
def add(
self,
*keys: Keys | str,
filter: FilterOrBool = True,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
record_in_macro: FilterOrBool = True,
) -> Callable[[T], T]:
"""
Decorator for adding a key bindings.
:param filter: :class:`~prompt_toolkit.filters.Filter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param is_global: When this key bindings is added to a `Container` or
`Control`, make it a global (always active) binding.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.)
:param record_in_macro: Record these key bindings when a macro is
being recorded. (True by default.)
"""
assert keys
keys = tuple(_parse_key(k) for k in keys)
if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that
# case don't bother putting it in the key bindings. It will slow
# down every key press otherwise.
def decorator(func: T) -> T:
return func
else:
def decorator(func: T) -> T:
if isinstance(func, Binding):
# We're adding an existing Binding object.
self.bindings.append(
Binding(
keys,
func.handler,
filter=func.filter & to_filter(filter),
eager=to_filter(eager) | func.eager,
is_global=to_filter(is_global) | func.is_global,
save_before=func.save_before,
record_in_macro=func.record_in_macro,
)
)
else:
self.bindings.append(
Binding(
keys,
cast(KeyHandlerCallable, func),
filter=filter,
eager=eager,
is_global=is_global,
save_before=save_before,
record_in_macro=record_in_macro,
)
)
self._clear_cache()
return func
return decorator
def remove(self, *args: Keys | str | KeyHandlerCallable) -> None:
"""
Remove a key binding.
This expects either a function that was given to `add` method as
parameter or a sequence of key bindings.
Raises `ValueError` when no bindings was found.
Usage::
remove(handler) # Pass handler.
remove('c-x', 'c-a') # Or pass the key bindings.
"""
found = False
if callable(args[0]):
assert len(args) == 1
function = args[0]
# Remove the given function.
for b in self.bindings:
if b.handler == function:
self.bindings.remove(b)
found = True
else:
assert len(args) > 0
args = cast(Tuple[Union[Keys, str]], args)
# Remove this sequence of key bindings.
keys = tuple(_parse_key(k) for k in args)
for b in self.bindings:
if b.keys == keys:
self.bindings.remove(b)
found = True
if found:
self._clear_cache()
else:
# No key binding found for this function. Raise ValueError.
raise ValueError(f"Binding not found: {function!r}")
# For backwards-compatibility.
add_binding = add
remove_binding = remove
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle this key.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result: list[tuple[int, Binding]] = []
for b in self.bindings:
if len(keys) == len(b.keys):
match = True
any_count = 0
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if i == Keys.Any:
any_count += 1
if match:
result.append((any_count, b))
# Place bindings that have more 'Any' occurrences in them at the end.
result = sorted(result, key=lambda item: -item[0])
return [item[1] for item in result]
return self._get_bindings_for_keys_cache.get(keys, get)
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result = []
for b in self.bindings:
if len(keys) < len(b.keys):
match = True
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if match:
result.append(b)
return result
return self._get_bindings_starting_with_keys_cache.get(keys, get)
The provided code snippet includes necessary dependencies for implementing the `load_auto_suggest_bindings` function. Write a Python function `def load_auto_suggest_bindings() -> KeyBindings` to solve the following problem:
Key bindings for accepting auto suggestion text. (This has to come after the Vi bindings, because they also have an implementation for the "right arrow", but we really want the suggestion binding when a suggestion is available.)
Here is the function:
def load_auto_suggest_bindings() -> KeyBindings:
"""
Key bindings for accepting auto suggestion text.
(This has to come after the Vi bindings, because they also have an
implementation for the "right arrow", but we really want the suggestion
binding when a suggestion is available.)
"""
key_bindings = KeyBindings()
handle = key_bindings.add
@Condition
def suggestion_available() -> bool:
app = get_app()
return (
app.current_buffer.suggestion is not None
and len(app.current_buffer.suggestion.text) > 0
and app.current_buffer.document.is_cursor_at_the_end
)
@handle("c-f", filter=suggestion_available)
@handle("c-e", filter=suggestion_available)
@handle("right", filter=suggestion_available)
def _accept(event: E) -> None:
"""
Accept suggestion.
"""
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
@handle("escape", "f", filter=suggestion_available & emacs_mode)
def _fill(event: E) -> None:
"""
Fill partial suggestion.
"""
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
t = re.split(r"(\S+\s+)", suggestion.text)
b.insert_text(next(x for x in t if x))
return key_bindings | Key bindings for accepting auto suggestion text. (This has to come after the Vi bindings, because they also have an implementation for the "right arrow", but we really want the suggestion binding when a suggestion is available.) |
172,116 | from __future__ import annotations
from abc import ABCMeta, abstractmethod, abstractproperty
from inspect import isawaitable
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Hashable,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.filters import FilterOrBool, Never, to_filter
from prompt_toolkit.keys import KEY_ALIASES, Keys
class Keys(str, Enum):
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
value: str
Escape = "escape" # Also Control-[
ShiftEscape = "s-escape"
ControlAt = "c-@" # Also Control-Space.
ControlA = "c-a"
ControlB = "c-b"
ControlC = "c-c"
ControlD = "c-d"
ControlE = "c-e"
ControlF = "c-f"
ControlG = "c-g"
ControlH = "c-h"
ControlI = "c-i" # Tab
ControlJ = "c-j" # Newline
ControlK = "c-k"
ControlL = "c-l"
ControlM = "c-m" # Carriage return
ControlN = "c-n"
ControlO = "c-o"
ControlP = "c-p"
ControlQ = "c-q"
ControlR = "c-r"
ControlS = "c-s"
ControlT = "c-t"
ControlU = "c-u"
ControlV = "c-v"
ControlW = "c-w"
ControlX = "c-x"
ControlY = "c-y"
ControlZ = "c-z"
Control1 = "c-1"
Control2 = "c-2"
Control3 = "c-3"
Control4 = "c-4"
Control5 = "c-5"
Control6 = "c-6"
Control7 = "c-7"
Control8 = "c-8"
Control9 = "c-9"
Control0 = "c-0"
ControlShift1 = "c-s-1"
ControlShift2 = "c-s-2"
ControlShift3 = "c-s-3"
ControlShift4 = "c-s-4"
ControlShift5 = "c-s-5"
ControlShift6 = "c-s-6"
ControlShift7 = "c-s-7"
ControlShift8 = "c-s-8"
ControlShift9 = "c-s-9"
ControlShift0 = "c-s-0"
ControlBackslash = "c-\\"
ControlSquareClose = "c-]"
ControlCircumflex = "c-^"
ControlUnderscore = "c-_"
Left = "left"
Right = "right"
Up = "up"
Down = "down"
Home = "home"
End = "end"
Insert = "insert"
Delete = "delete"
PageUp = "pageup"
PageDown = "pagedown"
ControlLeft = "c-left"
ControlRight = "c-right"
ControlUp = "c-up"
ControlDown = "c-down"
ControlHome = "c-home"
ControlEnd = "c-end"
ControlInsert = "c-insert"
ControlDelete = "c-delete"
ControlPageUp = "c-pageup"
ControlPageDown = "c-pagedown"
ShiftLeft = "s-left"
ShiftRight = "s-right"
ShiftUp = "s-up"
ShiftDown = "s-down"
ShiftHome = "s-home"
ShiftEnd = "s-end"
ShiftInsert = "s-insert"
ShiftDelete = "s-delete"
ShiftPageUp = "s-pageup"
ShiftPageDown = "s-pagedown"
ControlShiftLeft = "c-s-left"
ControlShiftRight = "c-s-right"
ControlShiftUp = "c-s-up"
ControlShiftDown = "c-s-down"
ControlShiftHome = "c-s-home"
ControlShiftEnd = "c-s-end"
ControlShiftInsert = "c-s-insert"
ControlShiftDelete = "c-s-delete"
ControlShiftPageUp = "c-s-pageup"
ControlShiftPageDown = "c-s-pagedown"
BackTab = "s-tab" # shift + tab
F1 = "f1"
F2 = "f2"
F3 = "f3"
F4 = "f4"
F5 = "f5"
F6 = "f6"
F7 = "f7"
F8 = "f8"
F9 = "f9"
F10 = "f10"
F11 = "f11"
F12 = "f12"
F13 = "f13"
F14 = "f14"
F15 = "f15"
F16 = "f16"
F17 = "f17"
F18 = "f18"
F19 = "f19"
F20 = "f20"
F21 = "f21"
F22 = "f22"
F23 = "f23"
F24 = "f24"
ControlF1 = "c-f1"
ControlF2 = "c-f2"
ControlF3 = "c-f3"
ControlF4 = "c-f4"
ControlF5 = "c-f5"
ControlF6 = "c-f6"
ControlF7 = "c-f7"
ControlF8 = "c-f8"
ControlF9 = "c-f9"
ControlF10 = "c-f10"
ControlF11 = "c-f11"
ControlF12 = "c-f12"
ControlF13 = "c-f13"
ControlF14 = "c-f14"
ControlF15 = "c-f15"
ControlF16 = "c-f16"
ControlF17 = "c-f17"
ControlF18 = "c-f18"
ControlF19 = "c-f19"
ControlF20 = "c-f20"
ControlF21 = "c-f21"
ControlF22 = "c-f22"
ControlF23 = "c-f23"
ControlF24 = "c-f24"
# Matches any key.
Any = "<any>"
# Special.
ScrollUp = "<scroll-up>"
ScrollDown = "<scroll-down>"
CPRResponse = "<cursor-position-response>"
Vt100MouseEvent = "<vt100-mouse-event>"
WindowsMouseEvent = "<windows-mouse-event>"
BracketedPaste = "<bracketed-paste>"
SIGINT = "<sigint>"
# For internal use: key which is ignored.
# (The key binding for this key should not do anything.)
Ignore = "<ignore>"
# Some 'Key' aliases (for backwards-compatibility).
ControlSpace = ControlAt
Tab = ControlI
Enter = ControlM
Backspace = ControlH
# ShiftControl was renamed to ControlShift in
# 888fcb6fa4efea0de8333177e1bbc792f3ff3c24 (20 Feb 2020).
ShiftControlLeft = ControlShiftLeft
ShiftControlRight = ControlShiftRight
ShiftControlHome = ControlShiftHome
ShiftControlEnd = ControlShiftEnd
KEY_ALIASES: dict[str, str] = {
"backspace": "c-h",
"c-space": "c-@",
"enter": "c-m",
"tab": "c-i",
# ShiftControl was renamed to ControlShift.
"s-c-left": "c-s-left",
"s-c-right": "c-s-right",
"s-c-home": "c-s-home",
"s-c-end": "c-s-end",
}
The provided code snippet includes necessary dependencies for implementing the `_parse_key` function. Write a Python function `def _parse_key(key: Keys | str) -> str | Keys` to solve the following problem:
Replace key by alias and verify whether it's a valid one.
Here is the function:
def _parse_key(key: Keys | str) -> str | Keys:
"""
Replace key by alias and verify whether it's a valid one.
"""
# Already a parse key? -> Return it.
if isinstance(key, Keys):
return key
# Lookup aliases.
key = KEY_ALIASES.get(key, key)
# Replace 'space' by ' '
if key == "space":
key = " "
# Return as `Key` object when it's a special key.
try:
return Keys(key)
except ValueError:
pass
# Final validation.
if len(key) != 1:
raise ValueError(f"Invalid key: {key}")
return key | Replace key by alias and verify whether it's a valid one. |
172,117 | from __future__ import annotations
import sys
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator, Optional
_current_app_session: ContextVar[AppSession] = ContextVar(
"_current_app_session", default=AppSession()
)
Any = object()
class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
def __next__(self) -> _T_co: ...
def send(self, __value: _T_contra) -> _T_co: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> _T_co: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ...
def close(self) -> None: ...
def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ...
def gi_code(self) -> CodeType: ...
def gi_frame(self) -> FrameType: ...
def gi_running(self) -> bool: ...
def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ...
class Application(Generic[_AppResult]):
"""
The main Application class!
This glues everything together.
:param layout: A :class:`~prompt_toolkit.layout.Layout` instance.
:param key_bindings:
:class:`~prompt_toolkit.key_binding.KeyBindingsBase` instance for
the key bindings.
:param clipboard: :class:`~prompt_toolkit.clipboard.Clipboard` to use.
:param full_screen: When True, run the application on the alternate screen buffer.
:param color_depth: Any :class:`~.ColorDepth` value, a callable that
returns a :class:`~.ColorDepth` or `None` for default.
:param erase_when_done: (bool) Clear the application output when it finishes.
:param reverse_vi_search_direction: Normally, in Vi mode, a '/' searches
forward and a '?' searches backward. In Readline mode, this is usually
reversed.
:param min_redraw_interval: Number of seconds to wait between redraws. Use
this for applications where `invalidate` is called a lot. This could cause
a lot of terminal output, which some terminals are not able to process.
`None` means that every `invalidate` will be scheduled right away
(which is usually fine).
When one `invalidate` is called, but a scheduled redraw of a previous
`invalidate` call has not been executed yet, nothing will happen in any
case.
:param max_render_postpone_time: When there is high CPU (a lot of other
scheduled calls), postpone the rendering max x seconds. '0' means:
don't postpone. '.5' means: try to draw at least twice a second.
:param refresh_interval: Automatically invalidate the UI every so many
seconds. When `None` (the default), only invalidate when `invalidate`
has been called.
:param terminal_size_polling_interval: Poll the terminal size every so many
seconds. Useful if the applications runs in a thread other then then
main thread where SIGWINCH can't be handled, or on Windows.
Filters:
:param mouse_support: (:class:`~prompt_toolkit.filters.Filter` or
boolean). When True, enable mouse support.
:param paste_mode: :class:`~prompt_toolkit.filters.Filter` or boolean.
:param editing_mode: :class:`~prompt_toolkit.enums.EditingMode`.
:param enable_page_navigation_bindings: When `True`, enable the page
navigation key bindings. These include both Emacs and Vi bindings like
page-up, page-down and so on to scroll through pages. Mostly useful for
creating an editor or other full screen applications. Probably, you
don't want this for the implementation of a REPL. By default, this is
enabled if `full_screen` is set.
Callbacks (all of these should accept an
:class:`~prompt_toolkit.application.Application` object as input.)
:param on_reset: Called during reset.
:param on_invalidate: Called when the UI has been invalidated.
:param before_render: Called right before rendering.
:param after_render: Called right after rendering.
I/O:
(Note that the preferred way to change the input/output is by creating an
`AppSession` with the required input/output objects. If you need multiple
applications running at the same time, you have to create a separate
`AppSession` using a `with create_app_session():` block.
:param input: :class:`~prompt_toolkit.input.Input` instance.
:param output: :class:`~prompt_toolkit.output.Output` instance. (Probably
Vt100_Output or Win32Output.)
Usage:
app = Application(...)
app.run()
# Or
await app.run_async()
"""
def __init__(
self,
layout: Layout | None = None,
style: BaseStyle | None = None,
include_default_pygments_style: FilterOrBool = True,
style_transformation: StyleTransformation | None = None,
key_bindings: KeyBindingsBase | None = None,
clipboard: Clipboard | None = None,
full_screen: bool = False,
color_depth: (ColorDepth | Callable[[], ColorDepth | None] | None) = None,
mouse_support: FilterOrBool = False,
enable_page_navigation_bindings: None
| (FilterOrBool) = None, # Can be None, True or False.
paste_mode: FilterOrBool = False,
editing_mode: EditingMode = EditingMode.EMACS,
erase_when_done: bool = False,
reverse_vi_search_direction: FilterOrBool = False,
min_redraw_interval: float | int | None = None,
max_render_postpone_time: float | int | None = 0.01,
refresh_interval: float | None = None,
terminal_size_polling_interval: float | None = 0.5,
cursor: AnyCursorShapeConfig = None,
on_reset: ApplicationEventHandler[_AppResult] | None = None,
on_invalidate: ApplicationEventHandler[_AppResult] | None = None,
before_render: ApplicationEventHandler[_AppResult] | None = None,
after_render: ApplicationEventHandler[_AppResult] | None = None,
# I/O.
input: Input | None = None,
output: Output | None = None,
) -> None:
# If `enable_page_navigation_bindings` is not specified, enable it in
# case of full screen applications only. This can be overridden by the user.
if enable_page_navigation_bindings is None:
enable_page_navigation_bindings = Condition(lambda: self.full_screen)
paste_mode = to_filter(paste_mode)
mouse_support = to_filter(mouse_support)
reverse_vi_search_direction = to_filter(reverse_vi_search_direction)
enable_page_navigation_bindings = to_filter(enable_page_navigation_bindings)
include_default_pygments_style = to_filter(include_default_pygments_style)
if layout is None:
layout = create_dummy_layout()
if style_transformation is None:
style_transformation = DummyStyleTransformation()
self.style = style
self.style_transformation = style_transformation
# Key bindings.
self.key_bindings = key_bindings
self._default_bindings = load_key_bindings()
self._page_navigation_bindings = load_page_navigation_bindings()
self.layout = layout
self.clipboard = clipboard or InMemoryClipboard()
self.full_screen: bool = full_screen
self._color_depth = color_depth
self.mouse_support = mouse_support
self.paste_mode = paste_mode
self.editing_mode = editing_mode
self.erase_when_done = erase_when_done
self.reverse_vi_search_direction = reverse_vi_search_direction
self.enable_page_navigation_bindings = enable_page_navigation_bindings
self.min_redraw_interval = min_redraw_interval
self.max_render_postpone_time = max_render_postpone_time
self.refresh_interval = refresh_interval
self.terminal_size_polling_interval = terminal_size_polling_interval
self.cursor = to_cursor_shape_config(cursor)
# Events.
self.on_invalidate = Event(self, on_invalidate)
self.on_reset = Event(self, on_reset)
self.before_render = Event(self, before_render)
self.after_render = Event(self, after_render)
# I/O.
session = get_app_session()
self.output = output or session.output
self.input = input or session.input
# List of 'extra' functions to execute before a Application.run.
self.pre_run_callables: list[Callable[[], None]] = []
self._is_running = False
self.future: Future[_AppResult] | None = None
self.loop: AbstractEventLoop | None = None
self.context: contextvars.Context | None = None
#: Quoted insert. This flag is set if we go into quoted insert mode.
self.quoted_insert = False
#: Vi state. (For Vi key bindings.)
self.vi_state = ViState()
self.emacs_state = EmacsState()
#: When to flush the input (For flushing escape keys.) This is important
#: on terminals that use vt100 input. We can't distinguish the escape
#: key from for instance the left-arrow key, if we don't know what follows
#: after "\x1b". This little timer will consider "\x1b" to be escape if
#: nothing did follow in this time span.
#: This seems to work like the `ttimeoutlen` option in Vim.
self.ttimeoutlen = 0.5 # Seconds.
#: Like Vim's `timeoutlen` option. This can be `None` or a float. For
#: instance, suppose that we have a key binding AB and a second key
#: binding A. If the uses presses A and then waits, we don't handle
#: this binding yet (unless it was marked 'eager'), because we don't
#: know what will follow. This timeout is the maximum amount of time
#: that we wait until we call the handlers anyway. Pass `None` to
#: disable this timeout.
self.timeoutlen = 1.0
#: The `Renderer` instance.
# Make sure that the same stdout is used, when a custom renderer has been passed.
self._merged_style = self._create_merged_style(include_default_pygments_style)
self.renderer = Renderer(
self._merged_style,
self.output,
full_screen=full_screen,
mouse_support=mouse_support,
cpr_not_supported_callback=self.cpr_not_supported_callback,
)
#: Render counter. This one is increased every time the UI is rendered.
#: It can be used as a key for caching certain information during one
#: rendering.
self.render_counter = 0
# Invalidate flag. When 'True', a repaint has been scheduled.
self._invalidated = False
self._invalidate_events: list[
Event[object]
] = [] # Collection of 'invalidate' Event objects.
self._last_redraw_time = 0.0 # Unix timestamp of last redraw. Used when
# `min_redraw_interval` is given.
#: The `InputProcessor` instance.
self.key_processor = KeyProcessor(_CombinedRegistry(self))
# If `run_in_terminal` was called. This will point to a `Future` what will be
# set at the point when the previous run finishes.
self._running_in_terminal = False
self._running_in_terminal_f: Future[None] | None = None
# Trigger initialize callback.
self.reset()
def _create_merged_style(self, include_default_pygments_style: Filter) -> BaseStyle:
"""
Create a `Style` object that merges the default UI style, the default
pygments style, and the custom user style.
"""
dummy_style = DummyStyle()
pygments_style = default_pygments_style()
def conditional_pygments_style() -> BaseStyle:
if include_default_pygments_style():
return pygments_style
else:
return dummy_style
return merge_styles(
[
default_ui_style(),
conditional_pygments_style,
DynamicStyle(lambda: self.style),
]
)
def color_depth(self) -> ColorDepth:
"""
The active :class:`.ColorDepth`.
The current value is determined as follows:
- If a color depth was given explicitly to this application, use that
value.
- Otherwise, fall back to the color depth that is reported by the
:class:`.Output` implementation. If the :class:`.Output` class was
created using `output.defaults.create_output`, then this value is
coming from the $PROMPT_TOOLKIT_COLOR_DEPTH environment variable.
"""
depth = self._color_depth
if callable(depth):
depth = depth()
if depth is None:
depth = self.output.get_default_color_depth()
return depth
def current_buffer(self) -> Buffer:
"""
The currently focused :class:`~.Buffer`.
(This returns a dummy :class:`.Buffer` when none of the actual buffers
has the focus. In this case, it's really not practical to check for
`None` values or catch exceptions every time.)
"""
return self.layout.current_buffer or Buffer(
name="dummy-buffer"
) # Dummy buffer.
def current_search_state(self) -> SearchState:
"""
Return the current :class:`.SearchState`. (The one for the focused
:class:`.BufferControl`.)
"""
ui_control = self.layout.current_control
if isinstance(ui_control, BufferControl):
return ui_control.search_state
else:
return SearchState() # Dummy search state. (Don't return None!)
def reset(self) -> None:
"""
Reset everything, for reading the next input.
"""
# Notice that we don't reset the buffers. (This happens just before
# returning, and when we have multiple buffers, we clearly want the
# content in the other buffers to remain unchanged between several
# calls of `run`. (And the same is true for the focus stack.)
self.exit_style = ""
self._background_tasks: set[Task[None]] = set()
self.renderer.reset()
self.key_processor.reset()
self.layout.reset()
self.vi_state.reset()
self.emacs_state.reset()
# Trigger reset event.
self.on_reset.fire()
# Make sure that we have a 'focusable' widget focused.
# (The `Layout` class can't determine this.)
layout = self.layout
if not layout.current_control.is_focusable():
for w in layout.find_all_windows():
if w.content.is_focusable():
layout.current_window = w
break
def invalidate(self) -> None:
"""
Thread safe way of sending a repaint trigger to the input event loop.
"""
if not self._is_running:
# Don't schedule a redraw if we're not running.
# Otherwise, `get_running_loop()` in `call_soon_threadsafe` can fail.
# See: https://github.com/dbcli/mycli/issues/797
return
# `invalidate()` called if we don't have a loop yet (not running?), or
# after the event loop was closed.
if self.loop is None or self.loop.is_closed():
return
# Never schedule a second redraw, when a previous one has not yet been
# executed. (This should protect against other threads calling
# 'invalidate' many times, resulting in 100% CPU.)
if self._invalidated:
return
else:
self._invalidated = True
# Trigger event.
self.loop.call_soon_threadsafe(self.on_invalidate.fire)
def redraw() -> None:
self._invalidated = False
self._redraw()
def schedule_redraw() -> None:
call_soon_threadsafe(
redraw, max_postpone_time=self.max_render_postpone_time, loop=self.loop
)
if self.min_redraw_interval:
# When a minimum redraw interval is set, wait minimum this amount
# of time between redraws.
diff = time.time() - self._last_redraw_time
if diff < self.min_redraw_interval:
async def redraw_in_future() -> None:
await sleep(cast(float, self.min_redraw_interval) - diff)
schedule_redraw()
self.loop.call_soon_threadsafe(
lambda: self.create_background_task(redraw_in_future())
)
else:
schedule_redraw()
else:
schedule_redraw()
def invalidated(self) -> bool:
"True when a redraw operation has been scheduled."
return self._invalidated
def _redraw(self, render_as_done: bool = False) -> None:
"""
Render the command line again. (Not thread safe!) (From other threads,
or if unsure, use :meth:`.Application.invalidate`.)
:param render_as_done: make sure to put the cursor after the UI.
"""
def run_in_context() -> None:
# Only draw when no sub application was started.
if self._is_running and not self._running_in_terminal:
if self.min_redraw_interval:
self._last_redraw_time = time.time()
# Render
self.render_counter += 1
self.before_render.fire()
if render_as_done:
if self.erase_when_done:
self.renderer.erase()
else:
# Draw in 'done' state and reset renderer.
self.renderer.render(self, self.layout, is_done=render_as_done)
else:
self.renderer.render(self, self.layout)
self.layout.update_parents_relations()
# Fire render event.
self.after_render.fire()
self._update_invalidate_events()
# NOTE: We want to make sure this Application is the active one. The
# invalidate function is often called from a context where this
# application is not the active one. (Like the
# `PromptSession._auto_refresh_context`).
# We copy the context in case the context was already active, to
# prevent RuntimeErrors. (The rendering is not supposed to change
# any context variables.)
if self.context is not None:
self.context.copy().run(run_in_context)
def _start_auto_refresh_task(self) -> None:
"""
Start a while/true loop in the background for automatic invalidation of
the UI.
"""
if self.refresh_interval is not None and self.refresh_interval != 0:
async def auto_refresh(refresh_interval: float) -> None:
while True:
await sleep(refresh_interval)
self.invalidate()
self.create_background_task(auto_refresh(self.refresh_interval))
def _update_invalidate_events(self) -> None:
"""
Make sure to attach 'invalidate' handlers to all invalidate events in
the UI.
"""
# Remove all the original event handlers. (Components can be removed
# from the UI.)
for ev in self._invalidate_events:
ev -= self._invalidate_handler
# Gather all new events.
# (All controls are able to invalidate themselves.)
def gather_events() -> Iterable[Event[object]]:
for c in self.layout.find_all_controls():
yield from c.get_invalidate_events()
self._invalidate_events = list(gather_events())
for ev in self._invalidate_events:
ev += self._invalidate_handler
def _invalidate_handler(self, sender: object) -> None:
"""
Handler for invalidate events coming from UIControls.
(This handles the difference in signature between event handler and
`self.invalidate`. It also needs to be a method -not a nested
function-, so that we can remove it again .)
"""
self.invalidate()
def _on_resize(self) -> None:
"""
When the window size changes, we erase the current output and request
again the cursor position. When the CPR answer arrives, the output is
drawn again.
"""
# Erase, request position (when cursor is at the start position)
# and redraw again. -- The order is important.
self.renderer.erase(leave_alternate_screen=False)
self._request_absolute_cursor_position()
self._redraw()
def _pre_run(self, pre_run: Callable[[], None] | None = None) -> None:
"""
Called during `run`.
`self.future` should be set to the new future at the point where this
is called in order to avoid data races. `pre_run` can be used to set a
`threading.Event` to synchronize with UI termination code, running in
another thread that would call `Application.exit`. (See the progress
bar code for an example.)
"""
if pre_run:
pre_run()
# Process registered "pre_run_callables" and clear list.
for c in self.pre_run_callables:
c()
del self.pre_run_callables[:]
async def run_async(
self,
pre_run: Callable[[], None] | None = None,
set_exception_handler: bool = True,
handle_sigint: bool = True,
slow_callback_duration: float = 0.5,
) -> _AppResult:
"""
Run the prompt_toolkit :class:`~prompt_toolkit.application.Application`
until :meth:`~prompt_toolkit.application.Application.exit` has been
called. Return the value that was passed to
:meth:`~prompt_toolkit.application.Application.exit`.
This is the main entry point for a prompt_toolkit
:class:`~prompt_toolkit.application.Application` and usually the only
place where the event loop is actually running.
:param pre_run: Optional callable, which is called right after the
"reset" of the application.
:param set_exception_handler: When set, in case of an exception, go out
of the alternate screen and hide the application, display the
exception, and wait for the user to press ENTER.
:param handle_sigint: Handle SIGINT signal if possible. This will call
the `<sigint>` key binding when a SIGINT is received. (This only
works in the main thread.)
:param slow_callback_duration: Display warnings if code scheduled in
the asyncio event loop takes more time than this. The asyncio
default of `0.1` is sometimes not sufficient on a slow system,
because exceptionally, the drawing of the app, which happens in the
event loop, can take a bit longer from time to time.
"""
assert not self._is_running, "Application is already running."
if not in_main_thread() or sys.platform == "win32":
# Handling signals in other threads is not supported.
# Also on Windows, `add_signal_handler(signal.SIGINT, ...)` raises
# `NotImplementedError`.
# See: https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1553
handle_sigint = False
async def _run_async(f: "asyncio.Future[_AppResult]") -> _AppResult:
self.context = contextvars.copy_context()
# Counter for cancelling 'flush' timeouts. Every time when a key is
# pressed, we start a 'flush' timer for flushing our escape key. But
# when any subsequent input is received, a new timer is started and
# the current timer will be ignored.
flush_task: asyncio.Task[None] | None = None
# Reset.
# (`self.future` needs to be set when `pre_run` is called.)
self.reset()
self._pre_run(pre_run)
# Feed type ahead input first.
self.key_processor.feed_multiple(get_typeahead(self.input))
self.key_processor.process_keys()
def read_from_input() -> None:
nonlocal flush_task
# Ignore when we aren't running anymore. This callback will
# removed from the loop next time. (It could be that it was
# still in the 'tasks' list of the loop.)
# Except: if we need to process incoming CPRs.
if not self._is_running and not self.renderer.waiting_for_cpr:
return
# Get keys from the input object.
keys = self.input.read_keys()
# Feed to key processor.
self.key_processor.feed_multiple(keys)
self.key_processor.process_keys()
# Quit when the input stream was closed.
if self.input.closed:
if not f.done():
f.set_exception(EOFError)
else:
# Automatically flush keys.
if flush_task:
flush_task.cancel()
flush_task = self.create_background_task(auto_flush_input())
async def auto_flush_input() -> None:
# Flush input after timeout.
# (Used for flushing the enter key.)
# This sleep can be cancelled, in that case we won't flush yet.
await sleep(self.ttimeoutlen)
flush_input()
def flush_input() -> None:
if not self.is_done:
# Get keys, and feed to key processor.
keys = self.input.flush_keys()
self.key_processor.feed_multiple(keys)
self.key_processor.process_keys()
if self.input.closed:
f.set_exception(EOFError)
# Enter raw mode, attach input and attach WINCH event handler.
with self.input.raw_mode(), self.input.attach(
read_from_input
), attach_winch_signal_handler(self._on_resize):
# Draw UI.
self._request_absolute_cursor_position()
self._redraw()
self._start_auto_refresh_task()
self.create_background_task(self._poll_output_size())
# Wait for UI to finish.
try:
result = await f
finally:
# In any case, when the application finishes.
# (Successful, or because of an error.)
try:
self._redraw(render_as_done=True)
finally:
# _redraw has a good chance to fail if it calls widgets
# with bad code. Make sure to reset the renderer
# anyway.
self.renderer.reset()
# Unset `is_running`, this ensures that possibly
# scheduled draws won't paint during the following
# yield.
self._is_running = False
# Detach event handlers for invalidate events.
# (Important when a UIControl is embedded in multiple
# applications, like ptterm in pymux. An invalidate
# should not trigger a repaint in terminated
# applications.)
for ev in self._invalidate_events:
ev -= self._invalidate_handler
self._invalidate_events = []
# Wait for CPR responses.
if self.output.responds_to_cpr:
await self.renderer.wait_for_cpr_responses()
# Wait for the run-in-terminals to terminate.
previous_run_in_terminal_f = self._running_in_terminal_f
if previous_run_in_terminal_f:
await previous_run_in_terminal_f
# Store unprocessed input as typeahead for next time.
store_typeahead(self.input, self.key_processor.empty_queue())
return result
def get_loop() -> Iterator[AbstractEventLoop]:
loop = get_running_loop()
self.loop = loop
try:
yield loop
finally:
self.loop = None
def set_is_running() -> Iterator[None]:
self._is_running = True
try:
yield
finally:
self._is_running = False
def set_handle_sigint(loop: AbstractEventLoop) -> Iterator[None]:
if handle_sigint:
loop.add_signal_handler(
signal.SIGINT,
lambda *_: loop.call_soon_threadsafe(
self.key_processor.send_sigint
),
)
try:
yield
finally:
loop.remove_signal_handler(signal.SIGINT)
else:
yield
def set_exception_handler_ctx(loop: AbstractEventLoop) -> Iterator[None]:
if set_exception_handler:
previous_exc_handler = loop.get_exception_handler()
loop.set_exception_handler(self._handle_exception)
try:
yield
finally:
loop.set_exception_handler(previous_exc_handler)
else:
yield
def set_callback_duration(loop: AbstractEventLoop) -> Iterator[None]:
# Set slow_callback_duration.
original_slow_callback_duration = loop.slow_callback_duration
loop.slow_callback_duration = slow_callback_duration
try:
yield
finally:
# Reset slow_callback_duration.
loop.slow_callback_duration = original_slow_callback_duration
def create_future(
loop: AbstractEventLoop,
) -> Iterator[asyncio.Future[_AppResult]]:
f = loop.create_future()
self.future = f # XXX: make sure to set this before calling '_redraw'.
try:
yield f
finally:
# Also remove the Future again. (This brings the
# application back to its initial state, where it also
# doesn't have a Future.)
self.future = None
with ExitStack() as stack:
stack.enter_context(set_is_running())
# Make sure to set `_invalidated` to `False` to begin with,
# otherwise we're not going to paint anything. This can happen if
# this application had run before on a different event loop, and a
# paint was scheduled using `call_soon_threadsafe` with
# `max_postpone_time`.
self._invalidated = False
loop = stack.enter_context(get_loop())
stack.enter_context(set_handle_sigint(loop))
stack.enter_context(set_exception_handler_ctx(loop))
stack.enter_context(set_callback_duration(loop))
stack.enter_context(set_app(self))
stack.enter_context(self._enable_breakpointhook())
f = stack.enter_context(create_future(loop))
try:
return await _run_async(f)
finally:
# Wait for the background tasks to be done. This needs to
# go in the finally! If `_run_async` raises
# `KeyboardInterrupt`, we still want to wait for the
# background tasks.
await self.cancel_and_wait_for_background_tasks()
# The `ExitStack` above is defined in typeshed in a way that it can
# swallow exceptions. Without next line, mypy would think that there's
# a possibility we don't return here. See:
# https://github.com/python/mypy/issues/7726
assert False, "unreachable"
def run(
self,
pre_run: Callable[[], None] | None = None,
set_exception_handler: bool = True,
handle_sigint: bool = True,
in_thread: bool = False,
) -> _AppResult:
"""
A blocking 'run' call that waits until the UI is finished.
This will start the current asyncio event loop. If no loop is set for
the current thread, then it will create a new loop. If a new loop was
created, this won't close the new loop (if `in_thread=False`).
:param pre_run: Optional callable, which is called right after the
"reset" of the application.
:param set_exception_handler: When set, in case of an exception, go out
of the alternate screen and hide the application, display the
exception, and wait for the user to press ENTER.
:param in_thread: When true, run the application in a background
thread, and block the current thread until the application
terminates. This is useful if we need to be sure the application
won't use the current event loop (asyncio does not support nested
event loops). A new event loop will be created in this background
thread, and that loop will also be closed when the background
thread terminates. When this is used, it's especially important to
make sure that all asyncio background tasks are managed through
`get_appp().create_background_task()`, so that unfinished tasks are
properly cancelled before the event loop is closed. This is used
for instance in ptpython.
:param handle_sigint: Handle SIGINT signal. Call the key binding for
`Keys.SIGINT`. (This only works in the main thread.)
"""
if in_thread:
result: _AppResult
exception: BaseException | None = None
def run_in_thread() -> None:
nonlocal result, exception
try:
result = self.run(
pre_run=pre_run,
set_exception_handler=set_exception_handler,
# Signal handling only works in the main thread.
handle_sigint=False,
)
except BaseException as e:
exception = e
thread = threading.Thread(target=run_in_thread)
thread.start()
thread.join()
if exception is not None:
raise exception
return result
coro = self.run_async(
pre_run=pre_run,
set_exception_handler=set_exception_handler,
handle_sigint=handle_sigint,
)
try:
# See whether a loop was installed already. If so, use that. That's
# required for the input hooks to work, they are installed using
# `set_event_loop`.
loop = asyncio.get_event_loop()
except RuntimeError:
# No loop installed. Run like usual.
return asyncio.run(coro)
else:
# Use existing loop.
return loop.run_until_complete(coro)
def _handle_exception(
self, loop: AbstractEventLoop, context: dict[str, Any]
) -> None:
"""
Handler for event loop exceptions.
This will print the exception, using run_in_terminal.
"""
# For Python 2: we have to get traceback at this point, because
# we're still in the 'except:' block of the event loop where the
# traceback is still available. Moving this code in the
# 'print_exception' coroutine will loose the exception.
tb = get_traceback_from_context(context)
formatted_tb = "".join(format_tb(tb))
async def in_term() -> None:
async with in_terminal():
# Print output. Similar to 'loop.default_exception_handler',
# but don't use logger. (This works better on Python 2.)
print("\nUnhandled exception in event loop:")
print(formatted_tb)
print("Exception {}".format(context.get("exception")))
await _do_wait_for_enter("Press ENTER to continue...")
ensure_future(in_term())
def _enable_breakpointhook(self) -> Generator[None, None, None]:
"""
Install our custom breakpointhook for the duration of this context
manager. (We will only install the hook if no other custom hook was
set.)
"""
if sys.version_info >= (3, 7) and sys.breakpointhook == sys.__breakpointhook__:
sys.breakpointhook = self._breakpointhook
try:
yield
finally:
sys.breakpointhook = sys.__breakpointhook__
else:
yield
def _breakpointhook(self, *a: object, **kw: object) -> None:
"""
Breakpointhook which uses PDB, but ensures that the application is
hidden and input echoing is restored during each debugger dispatch.
"""
app = self
# Inline import on purpose. We don't want to import pdb, if not needed.
import pdb
from types import FrameType
TraceDispatch = Callable[[FrameType, str, Any], Any]
class CustomPdb(pdb.Pdb):
def trace_dispatch(
self, frame: FrameType, event: str, arg: Any
) -> TraceDispatch:
# Hide application.
app.renderer.erase()
# Detach input and dispatch to debugger.
with app.input.detach():
with app.input.cooked_mode():
return super().trace_dispatch(frame, event, arg)
# Note: we don't render the application again here, because
# there's a good chance that there's a breakpoint on the next
# line. This paint/erase cycle would move the PDB prompt back
# to the middle of the screen.
frame = sys._getframe().f_back
CustomPdb(stdout=sys.__stdout__).set_trace(frame)
def create_background_task(
self, coroutine: Coroutine[Any, Any, None]
) -> asyncio.Task[None]:
"""
Start a background task (coroutine) for the running application. When
the `Application` terminates, unfinished background tasks will be
cancelled.
Given that we still support Python versions before 3.11, we can't use
task groups (and exception groups), because of that, these background
tasks are not allowed to raise exceptions. If they do, we'll call the
default exception handler from the event loop.
If at some point, we have Python 3.11 as the minimum supported Python
version, then we can use a `TaskGroup` (with the lifetime of
`Application.run_async()`, and run run the background tasks in there.
This is not threadsafe.
"""
loop = self.loop or get_running_loop()
task: asyncio.Task[None] = loop.create_task(coroutine)
self._background_tasks.add(task)
task.add_done_callback(self._on_background_task_done)
return task
def _on_background_task_done(self, task: asyncio.Task[None]) -> None:
"""
Called when a background task completes. Remove it from
`_background_tasks`, and handle exceptions if any.
"""
self._background_tasks.discard(task)
if task.cancelled():
return
exc = task.exception()
if exc is not None:
get_running_loop().call_exception_handler(
{
"message": f"prompt_toolkit.Application background task {task!r} "
"raised an unexpected exception.",
"exception": exc,
"task": task,
}
)
async def cancel_and_wait_for_background_tasks(self) -> None:
"""
Cancel all background tasks, and wait for the cancellation to complete.
If any of the background tasks raised an exception, this will also
propagate the exception.
(If we had nurseries like Trio, this would be the `__aexit__` of a
nursery.)
"""
for task in self._background_tasks:
task.cancel()
# Wait until the cancellation of the background tasks completes.
# `asyncio.wait()` does not propagate exceptions raised within any of
# these tasks, which is what we want. Otherwise, we can't distinguish
# between a `CancelledError` raised in this task because it got
# cancelled, and a `CancelledError` raised on this `await` checkpoint,
# because *we* got cancelled during the teardown of the application.
# (If we get cancelled here, then it's important to not suppress the
# `CancelledError`, and have it propagate.)
# NOTE: Currently, if we get cancelled at this point then we can't wait
# for the cancellation to complete (in the future, we should be
# using anyio or Python's 3.11 TaskGroup.)
# Also, if we had exception groups, we could propagate an
# `ExceptionGroup` if something went wrong here. Right now, we
# don't propagate exceptions, but have them printed in
# `_on_background_task_done`.
if len(self._background_tasks) > 0:
await asyncio.wait(
self._background_tasks, timeout=None, return_when=asyncio.ALL_COMPLETED
)
async def _poll_output_size(self) -> None:
"""
Coroutine for polling the terminal dimensions.
Useful for situations where `attach_winch_signal_handler` is not sufficient:
- If we are not running in the main thread.
- On Windows.
"""
size: Size | None = None
interval = self.terminal_size_polling_interval
if interval is None:
return
while True:
await asyncio.sleep(interval)
new_size = self.output.get_size()
if size is not None and new_size != size:
self._on_resize()
size = new_size
def cpr_not_supported_callback(self) -> None:
"""
Called when we don't receive the cursor position response in time.
"""
if not self.output.responds_to_cpr:
return # We know about this already.
def in_terminal() -> None:
self.output.write(
"WARNING: your terminal doesn't support cursor position requests (CPR).\r\n"
)
self.output.flush()
run_in_terminal(in_terminal)
def exit(self) -> None:
"Exit without arguments."
def exit(self, *, result: _AppResult, style: str = "") -> None:
"Exit with `_AppResult`."
def exit(
self, *, exception: BaseException | type[BaseException], style: str = ""
) -> None:
"Exit with exception."
def exit(
self,
result: _AppResult | None = None,
exception: BaseException | type[BaseException] | None = None,
style: str = "",
) -> None:
"""
Exit application.
.. note::
If `Application.exit` is called before `Application.run()` is
called, then the `Application` won't exit (because the
`Application.future` doesn't correspond to the current run). Use a
`pre_run` hook and an event to synchronize the closing if there's a
chance this can happen.
:param result: Set this result for the application.
:param exception: Set this exception as the result for an application. For
a prompt, this is often `EOFError` or `KeyboardInterrupt`.
:param style: Apply this style on the whole content when quitting,
often this is 'class:exiting' for a prompt. (Used when
`erase_when_done` is not set.)
"""
assert result is None or exception is None
if self.future is None:
raise Exception("Application is not running. Application.exit() failed.")
if self.future.done():
raise Exception("Return value already set. Application.exit() failed.")
self.exit_style = style
if exception is not None:
self.future.set_exception(exception)
else:
self.future.set_result(cast(_AppResult, result))
def _request_absolute_cursor_position(self) -> None:
"""
Send CPR request.
"""
# Note: only do this if the input queue is not empty, and a return
# value has not been set. Otherwise, we won't be able to read the
# response anyway.
if not self.key_processor.input_queue and not self.is_done:
self.renderer.request_absolute_cursor_position()
async def run_system_command(
self,
command: str,
wait_for_enter: bool = True,
display_before_text: AnyFormattedText = "",
wait_text: str = "Press ENTER to continue...",
) -> None:
"""
Run system command (While hiding the prompt. When finished, all the
output will scroll above the prompt.)
:param command: Shell command to be executed.
:param wait_for_enter: FWait for the user to press enter, when the
command is finished.
:param display_before_text: If given, text to be displayed before the
command executes.
:return: A `Future` object.
"""
async with in_terminal():
# Try to use the same input/output file descriptors as the one,
# used to run this application.
try:
input_fd = self.input.fileno()
except AttributeError:
input_fd = sys.stdin.fileno()
try:
output_fd = self.output.fileno()
except AttributeError:
output_fd = sys.stdout.fileno()
# Run sub process.
def run_command() -> None:
self.print_text(display_before_text)
p = Popen(command, shell=True, stdin=input_fd, stdout=output_fd)
p.wait()
await run_in_executor_with_context(run_command)
# Wait for the user to press enter.
if wait_for_enter:
await _do_wait_for_enter(wait_text)
def suspend_to_background(self, suspend_group: bool = True) -> None:
"""
(Not thread safe -- to be called from inside the key bindings.)
Suspend process.
:param suspend_group: When true, suspend the whole process group.
(This is the default, and probably what you want.)
"""
# Only suspend when the operating system supports it.
# (Not on Windows.)
if _SIGTSTP is not None:
def run() -> None:
signal = cast(int, _SIGTSTP)
# Send `SIGTSTP` to own process.
# This will cause it to suspend.
# Usually we want the whole process group to be suspended. This
# handles the case when input is piped from another process.
if suspend_group:
os.kill(0, signal)
else:
os.kill(os.getpid(), signal)
run_in_terminal(run)
def print_text(
self, text: AnyFormattedText, style: BaseStyle | None = None
) -> None:
"""
Print a list of (style_str, text) tuples to the output.
(When the UI is running, this method has to be called through
`run_in_terminal`, otherwise it will destroy the UI.)
:param text: List of ``(style_str, text)`` tuples.
:param style: Style class to use. Defaults to the active style in the CLI.
"""
print_formatted_text(
output=self.output,
formatted_text=text,
style=style or self._merged_style,
color_depth=self.color_depth,
style_transformation=self.style_transformation,
)
def is_running(self) -> bool:
"`True` when the application is currently active/running."
return self._is_running
def is_done(self) -> bool:
if self.future:
return self.future.done()
return False
def get_used_style_strings(self) -> list[str]:
"""
Return a list of used style strings. This is helpful for debugging, and
for writing a new `Style`.
"""
attrs_for_style = self.renderer._attrs_for_style
if attrs_for_style:
return sorted(
re.sub(r"\s+", " ", style_str).strip()
for style_str in attrs_for_style.keys()
)
return []
The provided code snippet includes necessary dependencies for implementing the `set_app` function. Write a Python function `def set_app(app: Application[Any]) -> Generator[None, None, None]` to solve the following problem:
Context manager that sets the given :class:`.Application` active in an `AppSession`. This should only be called by the `Application` itself. The application will automatically be active while its running. If you want the application to be active in other threads/coroutines, where that's not the case, use `contextvars.copy_context()`, or use `Application.context` to run it in the appropriate context.
Here is the function:
def set_app(app: Application[Any]) -> Generator[None, None, None]:
"""
Context manager that sets the given :class:`.Application` active in an
`AppSession`.
This should only be called by the `Application` itself.
The application will automatically be active while its running. If you want
the application to be active in other threads/coroutines, where that's not
the case, use `contextvars.copy_context()`, or use `Application.context` to
run it in the appropriate context.
"""
session = _current_app_session.get()
previous_app = session.app
session.app = app
try:
yield
finally:
session.app = previous_app | Context manager that sets the given :class:`.Application` active in an `AppSession`. This should only be called by the `Application` itself. The application will automatically be active while its running. If you want the application to be active in other threads/coroutines, where that's not the case, use `contextvars.copy_context()`, or use `Application.context` to run it in the appropriate context. |
172,118 | from __future__ import annotations
import sys
from contextlib import contextmanager
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Generator, Optional
class AppSession:
"""
An AppSession is an interactive session, usually connected to one terminal.
Within one such session, interaction with many applications can happen, one
after the other.
The input/output device is not supposed to change during one session.
Warning: Always use the `create_app_session` function to create an
instance, so that it gets activated correctly.
:param input: Use this as a default input for all applications
running in this session, unless an input is passed to the `Application`
explicitely.
:param output: Use this as a default output.
"""
def __init__(
self, input: Input | None = None, output: Output | None = None
) -> None:
self._input = input
self._output = output
# The application will be set dynamically by the `set_app` context
# manager. This is called in the application itself.
self.app: Application[Any] | None = None
def __repr__(self) -> str:
return f"AppSession(app={self.app!r})"
def input(self) -> Input:
if self._input is None:
from prompt_toolkit.input.defaults import create_input
self._input = create_input()
return self._input
def output(self) -> Output:
if self._output is None:
from prompt_toolkit.output.defaults import create_output
self._output = create_output()
return self._output
def create_app_session(
input: Input | None = None, output: Output | None = None
) -> Generator[AppSession, None, None]:
"""
Create a separate AppSession.
This is useful if there can be multiple individual `AppSession`s going on.
Like in the case of an Telnet/SSH server. This functionality uses
contextvars and requires at least Python 3.7.
"""
if sys.version_info <= (3, 6):
raise RuntimeError("Application sessions require Python 3.7.")
# If no input/output is specified, fall back to the current input/output,
# whatever that is.
if input is None:
input = get_app_session().input
if output is None:
output = get_app_session().output
# Create new `AppSession` and activate.
session = AppSession(input=input, output=output)
token = _current_app_session.set(session)
try:
yield session
finally:
_current_app_session.reset(token)
class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
def __next__(self) -> _T_co: ...
def send(self, __value: _T_contra) -> _T_co: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> _T_co: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ...
def close(self) -> None: ...
def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ...
def gi_code(self) -> CodeType: ...
def gi_frame(self) -> FrameType: ...
def gi_running(self) -> bool: ...
def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ...
def create_input(stdin: TextIO | None = None, always_prefer_tty: bool = False) -> Input:
"""
Create the appropriate `Input` object for the current os/environment.
:param always_prefer_tty: When set, if `sys.stdin` is connected to a Unix
`pipe`, check whether `sys.stdout` or `sys.stderr` are connected to a
pseudo terminal. If so, open the tty for reading instead of reading for
`sys.stdin`. (We can open `stdout` or `stderr` for reading, this is how
a `$PAGER` works.)
"""
if sys.platform == "win32":
from .win32 import Win32Input
# If `stdin` was assigned `None` (which happens with pythonw.exe), use
# a `DummyInput`. This triggers `EOFError` in the application code.
if stdin is None and sys.stdin is None:
return DummyInput()
return Win32Input(stdin or sys.stdin)
else:
from .vt100 import Vt100Input
# If no input TextIO is given, use stdin/stdout.
if stdin is None:
stdin = sys.stdin
if always_prefer_tty:
for obj in [sys.stdin, sys.stdout, sys.stderr]:
if obj.isatty():
stdin = obj
break
# If we can't access the file descriptor for the selected stdin, return
# a `DummyInput` instead. This can happen for instance in unit tests,
# when `sys.stdin` is patched by something that's not an actual file.
# (Instantiating `Vt100Input` would fail in this case.)
try:
stdin.fileno()
except io.UnsupportedOperation:
return DummyInput()
return Vt100Input(stdin)
def create_output(
stdout: TextIO | None = None, always_prefer_tty: bool = False
) -> Output:
"""
Return an :class:`~prompt_toolkit.output.Output` instance for the command
line.
:param stdout: The stdout object
:param always_prefer_tty: When set, look for `sys.stderr` if `sys.stdout`
is not a TTY. Useful if `sys.stdout` is redirected to a file, but we
still want user input and output on the terminal.
By default, this is `False`. If `sys.stdout` is not a terminal (maybe
it's redirected to a file), then a `PlainTextOutput` will be returned.
That way, tools like `print_formatted_text` will write plain text into
that file.
"""
# Consider TERM, PROMPT_TOOLKIT_BELL, and PROMPT_TOOLKIT_COLOR_DEPTH
# environment variables. Notice that PROMPT_TOOLKIT_COLOR_DEPTH value is
# the default that's used if the Application doesn't override it.
term_from_env = get_term_environment_variable()
bell_from_env = get_bell_environment_variable()
color_depth_from_env = ColorDepth.from_env()
if stdout is None:
# By default, render to stdout. If the output is piped somewhere else,
# render to stderr.
stdout = sys.stdout
if always_prefer_tty:
for io in [sys.stdout, sys.stderr]:
if io is not None and io.isatty():
# (This is `None` when using `pythonw.exe` on Windows.)
stdout = io
break
# If the output is still `None`, use a DummyOutput.
# This happens for instance on Windows, when running the application under
# `pythonw.exe`. In that case, there won't be a terminal Window, and
# stdin/stdout/stderr are `None`.
if stdout is None:
return DummyOutput()
# If the patch_stdout context manager has been used, then sys.stdout is
# replaced by this proxy. For prompt_toolkit applications, we want to use
# the real stdout.
from prompt_toolkit.patch_stdout import StdoutProxy
while isinstance(stdout, StdoutProxy):
stdout = stdout.original_stdout
if sys.platform == "win32":
from .conemu import ConEmuOutput
from .win32 import Win32Output
from .windows10 import Windows10_Output, is_win_vt100_enabled
if is_win_vt100_enabled():
return cast(
Output,
Windows10_Output(stdout, default_color_depth=color_depth_from_env),
)
if is_conemu_ansi():
return cast(
Output, ConEmuOutput(stdout, default_color_depth=color_depth_from_env)
)
else:
return Win32Output(stdout, default_color_depth=color_depth_from_env)
else:
from .vt100 import Vt100_Output
# Stdout is not a TTY? Render as plain text.
# This is mostly useful if stdout is redirected to a file, and
# `print_formatted_text` is used.
if not stdout.isatty():
return PlainTextOutput(stdout)
return Vt100_Output.from_pty(
stdout,
term=term_from_env,
default_color_depth=color_depth_from_env,
enable_bell=bell_from_env,
)
The provided code snippet includes necessary dependencies for implementing the `create_app_session_from_tty` function. Write a Python function `def create_app_session_from_tty() -> Generator[AppSession, None, None]` to solve the following problem:
Create `AppSession` that always prefers the TTY input/output. Even if `sys.stdin` and `sys.stdout` are connected to input/output pipes, this will still use the terminal for interaction (because `sys.stderr` is still connected to the terminal). Usage:: from prompt_toolkit.shortcuts import prompt with create_app_session_from_tty(): prompt('>')
Here is the function:
def create_app_session_from_tty() -> Generator[AppSession, None, None]:
"""
Create `AppSession` that always prefers the TTY input/output.
Even if `sys.stdin` and `sys.stdout` are connected to input/output pipes,
this will still use the terminal for interaction (because `sys.stderr` is
still connected to the terminal).
Usage::
from prompt_toolkit.shortcuts import prompt
with create_app_session_from_tty():
prompt('>')
"""
from prompt_toolkit.input.defaults import create_input
from prompt_toolkit.output.defaults import create_output
input = create_input(always_prefer_tty=True)
output = create_output(always_prefer_tty=True)
with create_app_session(input=input, output=output) as app_session:
yield app_session | Create `AppSession` that always prefers the TTY input/output. Even if `sys.stdin` and `sys.stdout` are connected to input/output pipes, this will still use the terminal for interaction (because `sys.stderr` is still connected to the terminal). Usage:: from prompt_toolkit.shortcuts import prompt with create_app_session_from_tty(): prompt('>') |
172,119 | from __future__ import annotations
import asyncio
import contextvars
import os
import re
import signal
import sys
import threading
import time
from asyncio import (
AbstractEventLoop,
Future,
Task,
ensure_future,
get_running_loop,
sleep,
)
from contextlib import ExitStack, contextmanager
from subprocess import Popen
from traceback import format_tb
from typing import (
Any,
Callable,
Coroutine,
Dict,
FrozenSet,
Generator,
Generic,
Hashable,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.clipboard import Clipboard, InMemoryClipboard
from prompt_toolkit.cursor_shapes import AnyCursorShapeConfig, to_cursor_shape_config
from prompt_toolkit.data_structures import Size
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.eventloop import (
get_traceback_from_context,
run_in_executor_with_context,
)
from prompt_toolkit.eventloop.utils import call_soon_threadsafe
from prompt_toolkit.filters import Condition, Filter, FilterOrBool, to_filter
from prompt_toolkit.formatted_text import AnyFormattedText
from prompt_toolkit.input.base import Input
from prompt_toolkit.input.typeahead import get_typeahead, store_typeahead
from prompt_toolkit.key_binding.bindings.page_navigation import (
load_page_navigation_bindings,
)
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.key_binding.emacs_state import EmacsState
from prompt_toolkit.key_binding.key_bindings import (
Binding,
ConditionalKeyBindings,
GlobalOnlyKeyBindings,
KeyBindings,
KeyBindingsBase,
KeysTuple,
merge_key_bindings,
)
from prompt_toolkit.key_binding.key_processor import KeyPressEvent, KeyProcessor
from prompt_toolkit.key_binding.vi_state import ViState
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import Container, Window
from prompt_toolkit.layout.controls import BufferControl, UIControl
from prompt_toolkit.layout.dummy import create_dummy_layout
from prompt_toolkit.layout.layout import Layout, walk
from prompt_toolkit.output import ColorDepth, Output
from prompt_toolkit.renderer import Renderer, print_formatted_text
from prompt_toolkit.search import SearchState
from prompt_toolkit.styles import (
BaseStyle,
DummyStyle,
DummyStyleTransformation,
DynamicStyle,
StyleTransformation,
default_pygments_style,
default_ui_style,
merge_styles,
)
from prompt_toolkit.utils import Event, in_main_thread
from .current import get_app_session, set_app
from .run_in_terminal import in_terminal, run_in_terminal
E = KeyPressEvent
Any = object()
class KeyBindings(KeyBindingsBase):
"""
A container for a set of key bindings.
Example usage::
kb = KeyBindings()
def _(event):
print('Control-T pressed')
def _(event):
print('Control-A pressed, followed by Control-B')
def _(event):
print('Control-X pressed') # Works only if we are searching.
"""
def __init__(self) -> None:
self._bindings: list[Binding] = []
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)
self.__version = 0 # For cache invalidation.
def _clear_cache(self) -> None:
self.__version += 1
self._get_bindings_for_keys_cache.clear()
self._get_bindings_starting_with_keys_cache.clear()
def bindings(self) -> list[Binding]:
return self._bindings
def _version(self) -> Hashable:
return self.__version
def add(
self,
*keys: Keys | str,
filter: FilterOrBool = True,
eager: FilterOrBool = False,
is_global: FilterOrBool = False,
save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
record_in_macro: FilterOrBool = True,
) -> Callable[[T], T]:
"""
Decorator for adding a key bindings.
:param filter: :class:`~prompt_toolkit.filters.Filter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param is_global: When this key bindings is added to a `Container` or
`Control`, make it a global (always active) binding.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.)
:param record_in_macro: Record these key bindings when a macro is
being recorded. (True by default.)
"""
assert keys
keys = tuple(_parse_key(k) for k in keys)
if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that
# case don't bother putting it in the key bindings. It will slow
# down every key press otherwise.
def decorator(func: T) -> T:
return func
else:
def decorator(func: T) -> T:
if isinstance(func, Binding):
# We're adding an existing Binding object.
self.bindings.append(
Binding(
keys,
func.handler,
filter=func.filter & to_filter(filter),
eager=to_filter(eager) | func.eager,
is_global=to_filter(is_global) | func.is_global,
save_before=func.save_before,
record_in_macro=func.record_in_macro,
)
)
else:
self.bindings.append(
Binding(
keys,
cast(KeyHandlerCallable, func),
filter=filter,
eager=eager,
is_global=is_global,
save_before=save_before,
record_in_macro=record_in_macro,
)
)
self._clear_cache()
return func
return decorator
def remove(self, *args: Keys | str | KeyHandlerCallable) -> None:
"""
Remove a key binding.
This expects either a function that was given to `add` method as
parameter or a sequence of key bindings.
Raises `ValueError` when no bindings was found.
Usage::
remove(handler) # Pass handler.
remove('c-x', 'c-a') # Or pass the key bindings.
"""
found = False
if callable(args[0]):
assert len(args) == 1
function = args[0]
# Remove the given function.
for b in self.bindings:
if b.handler == function:
self.bindings.remove(b)
found = True
else:
assert len(args) > 0
args = cast(Tuple[Union[Keys, str]], args)
# Remove this sequence of key bindings.
keys = tuple(_parse_key(k) for k in args)
for b in self.bindings:
if b.keys == keys:
self.bindings.remove(b)
found = True
if found:
self._clear_cache()
else:
# No key binding found for this function. Raise ValueError.
raise ValueError(f"Binding not found: {function!r}")
# For backwards-compatibility.
add_binding = add
remove_binding = remove
def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that can handle this key.
(This return also inactive bindings, so the `filter` still has to be
called, for checking it.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result: list[tuple[int, Binding]] = []
for b in self.bindings:
if len(keys) == len(b.keys):
match = True
any_count = 0
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if i == Keys.Any:
any_count += 1
if match:
result.append((any_count, b))
# Place bindings that have more 'Any' occurrences in them at the end.
result = sorted(result, key=lambda item: -item[0])
return [item[1] for item in result]
return self._get_bindings_for_keys_cache.get(keys, get)
def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
"""
Return a list of key bindings that handle a key sequence starting with
`keys`. (It does only return bindings for which the sequences are
longer than `keys`. And like `get_bindings_for_keys`, it also includes
inactive bindings.)
:param keys: tuple of keys.
"""
def get() -> list[Binding]:
result = []
for b in self.bindings:
if len(keys) < len(b.keys):
match = True
for i, j in zip(b.keys, keys):
if i != j and i != Keys.Any:
match = False
break
if match:
result.append(b)
return result
return self._get_bindings_starting_with_keys_cache.get(keys, get)
class Keys(str, Enum):
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
value: str
Escape = "escape" # Also Control-[
ShiftEscape = "s-escape"
ControlAt = "c-@" # Also Control-Space.
ControlA = "c-a"
ControlB = "c-b"
ControlC = "c-c"
ControlD = "c-d"
ControlE = "c-e"
ControlF = "c-f"
ControlG = "c-g"
ControlH = "c-h"
ControlI = "c-i" # Tab
ControlJ = "c-j" # Newline
ControlK = "c-k"
ControlL = "c-l"
ControlM = "c-m" # Carriage return
ControlN = "c-n"
ControlO = "c-o"
ControlP = "c-p"
ControlQ = "c-q"
ControlR = "c-r"
ControlS = "c-s"
ControlT = "c-t"
ControlU = "c-u"
ControlV = "c-v"
ControlW = "c-w"
ControlX = "c-x"
ControlY = "c-y"
ControlZ = "c-z"
Control1 = "c-1"
Control2 = "c-2"
Control3 = "c-3"
Control4 = "c-4"
Control5 = "c-5"
Control6 = "c-6"
Control7 = "c-7"
Control8 = "c-8"
Control9 = "c-9"
Control0 = "c-0"
ControlShift1 = "c-s-1"
ControlShift2 = "c-s-2"
ControlShift3 = "c-s-3"
ControlShift4 = "c-s-4"
ControlShift5 = "c-s-5"
ControlShift6 = "c-s-6"
ControlShift7 = "c-s-7"
ControlShift8 = "c-s-8"
ControlShift9 = "c-s-9"
ControlShift0 = "c-s-0"
ControlBackslash = "c-\\"
ControlSquareClose = "c-]"
ControlCircumflex = "c-^"
ControlUnderscore = "c-_"
Left = "left"
Right = "right"
Up = "up"
Down = "down"
Home = "home"
End = "end"
Insert = "insert"
Delete = "delete"
PageUp = "pageup"
PageDown = "pagedown"
ControlLeft = "c-left"
ControlRight = "c-right"
ControlUp = "c-up"
ControlDown = "c-down"
ControlHome = "c-home"
ControlEnd = "c-end"
ControlInsert = "c-insert"
ControlDelete = "c-delete"
ControlPageUp = "c-pageup"
ControlPageDown = "c-pagedown"
ShiftLeft = "s-left"
ShiftRight = "s-right"
ShiftUp = "s-up"
ShiftDown = "s-down"
ShiftHome = "s-home"
ShiftEnd = "s-end"
ShiftInsert = "s-insert"
ShiftDelete = "s-delete"
ShiftPageUp = "s-pageup"
ShiftPageDown = "s-pagedown"
ControlShiftLeft = "c-s-left"
ControlShiftRight = "c-s-right"
ControlShiftUp = "c-s-up"
ControlShiftDown = "c-s-down"
ControlShiftHome = "c-s-home"
ControlShiftEnd = "c-s-end"
ControlShiftInsert = "c-s-insert"
ControlShiftDelete = "c-s-delete"
ControlShiftPageUp = "c-s-pageup"
ControlShiftPageDown = "c-s-pagedown"
BackTab = "s-tab" # shift + tab
F1 = "f1"
F2 = "f2"
F3 = "f3"
F4 = "f4"
F5 = "f5"
F6 = "f6"
F7 = "f7"
F8 = "f8"
F9 = "f9"
F10 = "f10"
F11 = "f11"
F12 = "f12"
F13 = "f13"
F14 = "f14"
F15 = "f15"
F16 = "f16"
F17 = "f17"
F18 = "f18"
F19 = "f19"
F20 = "f20"
F21 = "f21"
F22 = "f22"
F23 = "f23"
F24 = "f24"
ControlF1 = "c-f1"
ControlF2 = "c-f2"
ControlF3 = "c-f3"
ControlF4 = "c-f4"
ControlF5 = "c-f5"
ControlF6 = "c-f6"
ControlF7 = "c-f7"
ControlF8 = "c-f8"
ControlF9 = "c-f9"
ControlF10 = "c-f10"
ControlF11 = "c-f11"
ControlF12 = "c-f12"
ControlF13 = "c-f13"
ControlF14 = "c-f14"
ControlF15 = "c-f15"
ControlF16 = "c-f16"
ControlF17 = "c-f17"
ControlF18 = "c-f18"
ControlF19 = "c-f19"
ControlF20 = "c-f20"
ControlF21 = "c-f21"
ControlF22 = "c-f22"
ControlF23 = "c-f23"
ControlF24 = "c-f24"
# Matches any key.
Any = "<any>"
# Special.
ScrollUp = "<scroll-up>"
ScrollDown = "<scroll-down>"
CPRResponse = "<cursor-position-response>"
Vt100MouseEvent = "<vt100-mouse-event>"
WindowsMouseEvent = "<windows-mouse-event>"
BracketedPaste = "<bracketed-paste>"
SIGINT = "<sigint>"
# For internal use: key which is ignored.
# (The key binding for this key should not do anything.)
Ignore = "<ignore>"
# Some 'Key' aliases (for backwards-compatibility).
ControlSpace = ControlAt
Tab = ControlI
Enter = ControlM
Backspace = ControlH
# ShiftControl was renamed to ControlShift in
# 888fcb6fa4efea0de8333177e1bbc792f3ff3c24 (20 Feb 2020).
ShiftControlLeft = ControlShiftLeft
ShiftControlRight = ControlShiftRight
ShiftControlHome = ControlShiftHome
ShiftControlEnd = ControlShiftEnd
The provided code snippet includes necessary dependencies for implementing the `_do_wait_for_enter` function. Write a Python function `async def _do_wait_for_enter(wait_text: AnyFormattedText) -> None` to solve the following problem:
Create a sub application to wait for the enter key press. This has two advantages over using 'input'/'raw_input': - This will share the same input/output I/O. - This doesn't block the event loop.
Here is the function:
async def _do_wait_for_enter(wait_text: AnyFormattedText) -> None:
"""
Create a sub application to wait for the enter key press.
This has two advantages over using 'input'/'raw_input':
- This will share the same input/output I/O.
- This doesn't block the event loop.
"""
from prompt_toolkit.shortcuts import PromptSession
key_bindings = KeyBindings()
@key_bindings.add("enter")
def _ok(event: E) -> None:
event.app.exit()
@key_bindings.add(Keys.Any)
def _ignore(event: E) -> None:
"Disallow typing."
pass
session: PromptSession[None] = PromptSession(
message=wait_text, key_bindings=key_bindings
)
try:
await session.app.run_async()
except KeyboardInterrupt:
pass # Control-c pressed. Don't propagate this error. | Create a sub application to wait for the enter key press. This has two advantages over using 'input'/'raw_input': - This will share the same input/output I/O. - This doesn't block the event loop. |
172,120 | from __future__ import annotations
import asyncio
import contextvars
import os
import re
import signal
import sys
import threading
import time
from asyncio import (
AbstractEventLoop,
Future,
Task,
ensure_future,
get_running_loop,
sleep,
)
from contextlib import ExitStack, contextmanager
from subprocess import Popen
from traceback import format_tb
from typing import (
Any,
Callable,
Coroutine,
Dict,
FrozenSet,
Generator,
Generic,
Hashable,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.clipboard import Clipboard, InMemoryClipboard
from prompt_toolkit.cursor_shapes import AnyCursorShapeConfig, to_cursor_shape_config
from prompt_toolkit.data_structures import Size
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.eventloop import (
get_traceback_from_context,
run_in_executor_with_context,
)
from prompt_toolkit.eventloop.utils import call_soon_threadsafe
from prompt_toolkit.filters import Condition, Filter, FilterOrBool, to_filter
from prompt_toolkit.formatted_text import AnyFormattedText
from prompt_toolkit.input.base import Input
from prompt_toolkit.input.typeahead import get_typeahead, store_typeahead
from prompt_toolkit.key_binding.bindings.page_navigation import (
load_page_navigation_bindings,
)
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.key_binding.emacs_state import EmacsState
from prompt_toolkit.key_binding.key_bindings import (
Binding,
ConditionalKeyBindings,
GlobalOnlyKeyBindings,
KeyBindings,
KeyBindingsBase,
KeysTuple,
merge_key_bindings,
)
from prompt_toolkit.key_binding.key_processor import KeyPressEvent, KeyProcessor
from prompt_toolkit.key_binding.vi_state import ViState
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import Container, Window
from prompt_toolkit.layout.controls import BufferControl, UIControl
from prompt_toolkit.layout.dummy import create_dummy_layout
from prompt_toolkit.layout.layout import Layout, walk
from prompt_toolkit.output import ColorDepth, Output
from prompt_toolkit.renderer import Renderer, print_formatted_text
from prompt_toolkit.search import SearchState
from prompt_toolkit.styles import (
BaseStyle,
DummyStyle,
DummyStyleTransformation,
DynamicStyle,
StyleTransformation,
default_pygments_style,
default_ui_style,
merge_styles,
)
from prompt_toolkit.utils import Event, in_main_thread
from .current import get_app_session, set_app
from .run_in_terminal import in_terminal, run_in_terminal
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
def __next__(self) -> _T_co: ...
def send(self, __value: _T_contra) -> _T_co: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> _T_co: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ...
def close(self) -> None: ...
def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ...
def gi_code(self) -> CodeType: ...
def gi_frame(self) -> FrameType: ...
def gi_running(self) -> bool: ...
def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ...
def in_main_thread() -> bool:
"""
True when the current thread is the main thread.
"""
return threading.current_thread().__class__.__name__ == "_MainThread"
The provided code snippet includes necessary dependencies for implementing the `attach_winch_signal_handler` function. Write a Python function `def attach_winch_signal_handler( handler: Callable[[], None] ) -> Generator[None, None, None]` to solve the following problem:
Attach the given callback as a WINCH signal handler within the context manager. Restore the original signal handler when done. The `Application.run` method will register SIGWINCH, so that it will properly repaint when the terminal window resizes. However, using `run_in_terminal`, we can temporarily send an application to the background, and run an other app in between, which will then overwrite the SIGWINCH. This is why it's important to restore the handler when the app terminates.
Here is the function:
def attach_winch_signal_handler(
handler: Callable[[], None]
) -> Generator[None, None, None]:
"""
Attach the given callback as a WINCH signal handler within the context
manager. Restore the original signal handler when done.
The `Application.run` method will register SIGWINCH, so that it will
properly repaint when the terminal window resizes. However, using
`run_in_terminal`, we can temporarily send an application to the
background, and run an other app in between, which will then overwrite the
SIGWINCH. This is why it's important to restore the handler when the app
terminates.
"""
# The tricky part here is that signals are registered in the Unix event
# loop with a wakeup fd, but another application could have registered
# signals using signal.signal directly. For now, the implementation is
# hard-coded for the `asyncio.unix_events._UnixSelectorEventLoop`.
# No WINCH? Then don't do anything.
sigwinch = getattr(signal, "SIGWINCH", None)
if sigwinch is None or not in_main_thread():
yield
return
# Keep track of the previous handler.
# (Only UnixSelectorEventloop has `_signal_handlers`.)
loop = get_running_loop()
previous_winch_handler = getattr(loop, "_signal_handlers", {}).get(sigwinch)
try:
loop.add_signal_handler(sigwinch, handler)
yield
finally:
# Restore the previous signal handler.
loop.remove_signal_handler(sigwinch)
if previous_winch_handler is not None:
loop.add_signal_handler(
sigwinch,
previous_winch_handler._callback,
*previous_winch_handler._args,
) | Attach the given callback as a WINCH signal handler within the context manager. Restore the original signal handler when done. The `Application.run` method will register SIGWINCH, so that it will properly repaint when the terminal window resizes. However, using `run_in_terminal`, we can temporarily send an application to the background, and run an other app in between, which will then overwrite the SIGWINCH. This is why it's important to restore the handler when the app terminates. |
172,121 | from __future__ import annotations
from string import Formatter
from typing import Generator, List, Optional
from prompt_toolkit.output.vt100 import BG_ANSI_COLORS, FG_ANSI_COLORS
from prompt_toolkit.output.vt100 import _256_colors as _256_colors_table
from .base import StyleAndTextTuples
The provided code snippet includes necessary dependencies for implementing the `ansi_escape` function. Write a Python function `def ansi_escape(text: object) -> str` to solve the following problem:
Replace characters with a special meaning.
Here is the function:
def ansi_escape(text: object) -> str:
"""
Replace characters with a special meaning.
"""
return str(text).replace("\x1b", "?").replace("\b", "?") | Replace characters with a special meaning. |
172,122 | from __future__ import annotations
import xml.dom.minidom as minidom
from string import Formatter
from typing import Any, List
from .base import FormattedText, StyleAndTextTuples
def html_escape(text: object) -> str:
# The string interpolation functions also take integers and other types.
# Convert to string first.
if not isinstance(text, str):
text = f"{text}"
return (
text.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
) | null |
172,123 | from __future__ import annotations
from typing import Iterable, cast
from prompt_toolkit.utils import get_cwidth
from .base import (
AnyFormattedText,
OneStyleAndTextTuple,
StyleAndTextTuples,
to_formatted_text,
)
def fragment_list_to_text(fragments: StyleAndTextTuples) -> str:
"""
Concatenate all the text parts again.
:param fragments: List of ``(style_str, text)`` or
``(style_str, text, mouse_handler)`` tuples.
"""
ZeroWidthEscape = "[ZeroWidthEscape]"
return "".join(item[1] for item in fragments if ZeroWidthEscape not in item[0])
AnyFormattedText = Union[
str,
"MagicFormattedText",
StyleAndTextTuples,
# Callable[[], 'AnyFormattedText'] # Recursive definition not supported by mypy.
Callable[[], Any],
None,
]
def to_formatted_text(
value: AnyFormattedText, style: str = "", auto_convert: bool = False
) -> FormattedText:
"""
Convert the given value (which can be formatted text) into a list of text
fragments. (Which is the canonical form of formatted text.) The outcome is
always a `FormattedText` instance, which is a list of (style, text) tuples.
It can take a plain text string, an `HTML` or `ANSI` object, anything that
implements `__pt_formatted_text__` or a callable that takes no arguments and
returns one of those.
:param style: An additional style string which is applied to all text
fragments.
:param auto_convert: If `True`, also accept other types, and convert them
to a string first.
"""
result: FormattedText | StyleAndTextTuples
if value is None:
result = []
elif isinstance(value, str):
result = [("", value)]
elif isinstance(value, list):
result = value # StyleAndTextTuples
elif hasattr(value, "__pt_formatted_text__"):
result = cast("MagicFormattedText", value).__pt_formatted_text__()
elif callable(value):
return to_formatted_text(value(), style=style)
elif auto_convert:
result = [("", f"{value}")]
else:
raise ValueError(
"No formatted text. Expecting a unicode object, "
"HTML, ANSI or a FormattedText instance. Got %r" % (value,)
)
# Apply extra style.
if style:
result = cast(
StyleAndTextTuples,
[(style + " " + item_style, *rest) for item_style, *rest in result],
)
# Make sure the result is wrapped in a `FormattedText`. Among other
# reasons, this is important for `print_formatted_text` to work correctly
# and distinguish between lists and formatted text.
if isinstance(result, FormattedText):
return result
else:
return FormattedText(result)
The provided code snippet includes necessary dependencies for implementing the `to_plain_text` function. Write a Python function `def to_plain_text(value: AnyFormattedText) -> str` to solve the following problem:
Turn any kind of formatted text back into plain text.
Here is the function:
def to_plain_text(value: AnyFormattedText) -> str:
"""
Turn any kind of formatted text back into plain text.
"""
return fragment_list_to_text(to_formatted_text(value)) | Turn any kind of formatted text back into plain text. |
172,124 | from __future__ import annotations
from typing import Iterable, cast
from prompt_toolkit.utils import get_cwidth
from .base import (
AnyFormattedText,
OneStyleAndTextTuple,
StyleAndTextTuples,
to_formatted_text,
)
StyleAndTextTuples = List[OneStyleAndTextTuple]
The provided code snippet includes necessary dependencies for implementing the `fragment_list_len` function. Write a Python function `def fragment_list_len(fragments: StyleAndTextTuples) -> int` to solve the following problem:
Return the amount of characters in this text fragment list. :param fragments: List of ``(style_str, text)`` or ``(style_str, text, mouse_handler)`` tuples.
Here is the function:
def fragment_list_len(fragments: StyleAndTextTuples) -> int:
"""
Return the amount of characters in this text fragment list.
:param fragments: List of ``(style_str, text)`` or
``(style_str, text, mouse_handler)`` tuples.
"""
ZeroWidthEscape = "[ZeroWidthEscape]"
return sum(len(item[1]) for item in fragments if ZeroWidthEscape not in item[0]) | Return the amount of characters in this text fragment list. :param fragments: List of ``(style_str, text)`` or ``(style_str, text, mouse_handler)`` tuples. |
172,125 | from __future__ import annotations
from typing import Iterable, cast
from prompt_toolkit.utils import get_cwidth
from .base import (
AnyFormattedText,
OneStyleAndTextTuple,
StyleAndTextTuples,
to_formatted_text,
)
def get_cwidth(string: str) -> int:
"""
Return width of a string. Wrapper around ``wcwidth``.
"""
return _CHAR_SIZES_CACHE[string]
StyleAndTextTuples = List[OneStyleAndTextTuple]
The provided code snippet includes necessary dependencies for implementing the `fragment_list_width` function. Write a Python function `def fragment_list_width(fragments: StyleAndTextTuples) -> int` to solve the following problem:
Return the character width of this text fragment list. (Take double width characters into account.) :param fragments: List of ``(style_str, text)`` or ``(style_str, text, mouse_handler)`` tuples.
Here is the function:
def fragment_list_width(fragments: StyleAndTextTuples) -> int:
"""
Return the character width of this text fragment list.
(Take double width characters into account.)
:param fragments: List of ``(style_str, text)`` or
``(style_str, text, mouse_handler)`` tuples.
"""
ZeroWidthEscape = "[ZeroWidthEscape]"
return sum(
get_cwidth(c)
for item in fragments
for c in item[1]
if ZeroWidthEscape not in item[0]
) | Return the character width of this text fragment list. (Take double width characters into account.) :param fragments: List of ``(style_str, text)`` or ``(style_str, text, mouse_handler)`` tuples. |
172,126 | from __future__ import annotations
from typing import Iterable, cast
from prompt_toolkit.utils import get_cwidth
from .base import (
AnyFormattedText,
OneStyleAndTextTuple,
StyleAndTextTuples,
to_formatted_text,
)
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]: ...
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
OneStyleAndTextTuple = Union[
Tuple[str, str], Tuple[str, str, Callable[[MouseEvent], "NotImplementedOrNone"]]
]
StyleAndTextTuples = List[OneStyleAndTextTuple]
The provided code snippet includes necessary dependencies for implementing the `split_lines` function. Write a Python function `def split_lines(fragments: StyleAndTextTuples) -> Iterable[StyleAndTextTuples]` to solve the following problem:
Take a single list of (style_str, text) tuples and yield one such list for each line. Just like str.split, this will yield at least one item. :param fragments: List of (style_str, text) or (style_str, text, mouse_handler) tuples.
Here is the function:
def split_lines(fragments: StyleAndTextTuples) -> Iterable[StyleAndTextTuples]:
"""
Take a single list of (style_str, text) tuples and yield one such list for each
line. Just like str.split, this will yield at least one item.
:param fragments: List of (style_str, text) or (style_str, text, mouse_handler)
tuples.
"""
line: StyleAndTextTuples = []
for style, string, *mouse_handler in fragments:
parts = string.split("\n")
for part in parts[:-1]:
if part:
line.append(cast(OneStyleAndTextTuple, (style, part, *mouse_handler)))
yield line
line = []
line.append(cast(OneStyleAndTextTuple, (style, parts[-1], *mouse_handler)))
# Always yield the last line, even when this is an empty line. This ensures
# that when `fragments` ends with a newline character, an additional empty
# line is yielded. (Otherwise, there's no way to differentiate between the
# cases where `fragments` does and doesn't end with a newline.)
yield line | Take a single list of (style_str, text) tuples and yield one such list for each line. Just like str.split, this will yield at least one item. :param fragments: List of (style_str, text) or (style_str, text, mouse_handler) tuples. |
172,127 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Tuple, Union, cast
from prompt_toolkit.mouse_events import MouseEvent
AnyFormattedText = Union[
str,
"MagicFormattedText",
StyleAndTextTuples,
# Callable[[], 'AnyFormattedText'] # Recursive definition not supported by mypy.
Callable[[], Any],
None,
]
The provided code snippet includes necessary dependencies for implementing the `is_formatted_text` function. Write a Python function `def is_formatted_text(value: object) -> TypeGuard[AnyFormattedText]` to solve the following problem:
Check whether the input is valid formatted text (for use in assert statements). In case of a callable, it doesn't check the return type.
Here is the function:
def is_formatted_text(value: object) -> TypeGuard[AnyFormattedText]:
"""
Check whether the input is valid formatted text (for use in assert
statements).
In case of a callable, it doesn't check the return type.
"""
if callable(value):
return True
if isinstance(value, (str, list)):
return True
if hasattr(value, "__pt_formatted_text__"):
return True
return False | Check whether the input is valid formatted text (for use in assert statements). In case of a callable, it doesn't check the return type. |
172,128 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Tuple, Union, cast
from prompt_toolkit.mouse_events import MouseEvent
AnyFormattedText = Union[
str,
"MagicFormattedText",
StyleAndTextTuples,
# Callable[[], 'AnyFormattedText'] # Recursive definition not supported by mypy.
Callable[[], Any],
None,
]
def to_formatted_text(
value: AnyFormattedText, style: str = "", auto_convert: bool = False
) -> FormattedText:
"""
Convert the given value (which can be formatted text) into a list of text
fragments. (Which is the canonical form of formatted text.) The outcome is
always a `FormattedText` instance, which is a list of (style, text) tuples.
It can take a plain text string, an `HTML` or `ANSI` object, anything that
implements `__pt_formatted_text__` or a callable that takes no arguments and
returns one of those.
:param style: An additional style string which is applied to all text
fragments.
:param auto_convert: If `True`, also accept other types, and convert them
to a string first.
"""
result: FormattedText | StyleAndTextTuples
if value is None:
result = []
elif isinstance(value, str):
result = [("", value)]
elif isinstance(value, list):
result = value # StyleAndTextTuples
elif hasattr(value, "__pt_formatted_text__"):
result = cast("MagicFormattedText", value).__pt_formatted_text__()
elif callable(value):
return to_formatted_text(value(), style=style)
elif auto_convert:
result = [("", f"{value}")]
else:
raise ValueError(
"No formatted text. Expecting a unicode object, "
"HTML, ANSI or a FormattedText instance. Got %r" % (value,)
)
# Apply extra style.
if style:
result = cast(
StyleAndTextTuples,
[(style + " " + item_style, *rest) for item_style, *rest in result],
)
# Make sure the result is wrapped in a `FormattedText`. Among other
# reasons, this is important for `print_formatted_text` to work correctly
# and distinguish between lists and formatted text.
if isinstance(result, FormattedText):
return result
else:
return FormattedText(result)
class FormattedText(StyleAndTextTuples):
"""
A list of ``(style, text)`` tuples.
(In some situations, this can also be ``(style, text, mouse_handler)``
tuples.)
"""
def __pt_formatted_text__(self) -> StyleAndTextTuples:
return self
def __repr__(self) -> str:
return "FormattedText(%s)" % super().__repr__()
class Iterable(Protocol[_T_co]):
def __iter__(self) -> Iterator[_T_co]: ...
The provided code snippet includes necessary dependencies for implementing the `merge_formatted_text` function. Write a Python function `def merge_formatted_text(items: Iterable[AnyFormattedText]) -> AnyFormattedText` to solve the following problem:
Merge (Concatenate) several pieces of formatted text together.
Here is the function:
def merge_formatted_text(items: Iterable[AnyFormattedText]) -> AnyFormattedText:
"""
Merge (Concatenate) several pieces of formatted text together.
"""
def _merge_formatted_text() -> AnyFormattedText:
result = FormattedText()
for i in items:
result.extend(to_formatted_text(i))
return result
return _merge_formatted_text | Merge (Concatenate) several pieces of formatted text together. |
172,129 | from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum
from typing import TYPE_CHECKING, Any, Callable, Union
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.vi_state import InputMode
class CursorShape(Enum):
# Default value that should tell the output implementation to never send
# cursor shape escape sequences. This is the default right now, because
# before this `CursorShape` functionality was introduced into
# prompt_toolkit itself, people had workarounds to send cursor shapes
# escapes into the terminal, by monkey patching some of prompt_toolkit's
# internals. We don't want the default prompt_toolkit implemetation to
# interfere with that. E.g., IPython patches the `ViState.input_mode`
# property. See: https://github.com/ipython/ipython/pull/13501/files
_NEVER_CHANGE = "_NEVER_CHANGE"
BLOCK = "BLOCK"
BEAM = "BEAM"
UNDERLINE = "UNDERLINE"
BLINKING_BLOCK = "BLINKING_BLOCK"
BLINKING_BEAM = "BLINKING_BEAM"
BLINKING_UNDERLINE = "BLINKING_UNDERLINE"
class CursorShapeConfig(ABC):
def get_cursor_shape(self, application: Application[Any]) -> CursorShape:
"""
Return the cursor shape to be used in the current state.
"""
AnyCursorShapeConfig = Union[CursorShape, CursorShapeConfig, None]
class SimpleCursorShapeConfig(CursorShapeConfig):
"""
Always show the given cursor shape.
"""
def __init__(self, cursor_shape: CursorShape = CursorShape._NEVER_CHANGE) -> None:
self.cursor_shape = cursor_shape
def get_cursor_shape(self, application: Application[Any]) -> CursorShape:
return self.cursor_shape
The provided code snippet includes necessary dependencies for implementing the `to_cursor_shape_config` function. Write a Python function `def to_cursor_shape_config(value: AnyCursorShapeConfig) -> CursorShapeConfig` to solve the following problem:
Take a `CursorShape` instance or `CursorShapeConfig` and turn it into a `CursorShapeConfig`.
Here is the function:
def to_cursor_shape_config(value: AnyCursorShapeConfig) -> CursorShapeConfig:
"""
Take a `CursorShape` instance or `CursorShapeConfig` and turn it into a
`CursorShapeConfig`.
"""
if value is None:
return SimpleCursorShapeConfig()
if isinstance(value, CursorShape):
return SimpleCursorShapeConfig(value)
return value | Take a `CursorShape` instance or `CursorShapeConfig` and turn it into a `CursorShapeConfig`. |
172,130 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from typing import AsyncGenerator, Callable, Iterable, Optional, Sequence
from prompt_toolkit.document import Document
from prompt_toolkit.eventloop import aclosing, generator_to_async_generator
from prompt_toolkit.filters import FilterOrBool, to_filter
from prompt_toolkit.formatted_text import AnyFormattedText, StyleAndTextTuples
class Completer(metaclass=ABCMeta):
"""
Base class for completer implementations.
"""
def get_completions(
self, document: Document, complete_event: CompleteEvent
) -> Iterable[Completion]:
"""
This should be a generator that yields :class:`.Completion` instances.
If the generation of completions is something expensive (that takes a
lot of time), consider wrapping this `Completer` class in a
`ThreadedCompleter`. In that case, the completer algorithm runs in a
background thread and completions will be displayed as soon as they
arrive.
:param document: :class:`~prompt_toolkit.document.Document` instance.
:param complete_event: :class:`.CompleteEvent` instance.
"""
while False:
yield
async def get_completions_async(
self, document: Document, complete_event: CompleteEvent
) -> AsyncGenerator[Completion, None]:
"""
Asynchronous generator for completions. (Probably, you won't have to
override this.)
Asynchronous generator of :class:`.Completion` objects.
"""
for item in self.get_completions(document, complete_event):
yield item
class _MergedCompleter(Completer):
"""
Combine several completers into one.
"""
def __init__(self, completers: Sequence[Completer]) -> None:
self.completers = completers
def get_completions(
self, document: Document, complete_event: CompleteEvent
) -> Iterable[Completion]:
# Get all completions from the other completers in a blocking way.
for completer in self.completers:
yield from completer.get_completions(document, complete_event)
async def get_completions_async(
self, document: Document, complete_event: CompleteEvent
) -> AsyncGenerator[Completion, None]:
# Get all completions from the other completers in a non-blocking way.
for completer in self.completers:
async with aclosing(
completer.get_completions_async(document, complete_event)
) as async_generator:
async for item in async_generator:
yield item
class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]):
def __getitem__(self, i: int) -> _T_co: ...
def __getitem__(self, s: slice) -> Sequence[_T_co]: ...
# Mixin methods
def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ...
def count(self, value: Any) -> int: ...
def __contains__(self, x: object) -> bool: ...
def __iter__(self) -> Iterator[_T_co]: ...
def __reversed__(self) -> Iterator[_T_co]: ...
class DeduplicateCompleter(Completer):
"""
Wrapper around a completer that removes duplicates. Only the first unique
completions are kept.
Completions are considered to be a duplicate if they result in the same
document text when they would be applied.
"""
def __init__(self, completer: Completer) -> None:
self.completer = completer
def get_completions(
self, document: Document, complete_event: CompleteEvent
) -> Iterable[Completion]:
# Keep track of the document strings we'd get after applying any completion.
found_so_far: set[str] = set()
for completion in self.completer.get_completions(document, complete_event):
text_if_applied = (
document.text[: document.cursor_position + completion.start_position]
+ completion.text
+ document.text[document.cursor_position :]
)
if text_if_applied == document.text:
# Don't include completions that don't have any effect at all.
continue
if text_if_applied in found_so_far:
continue
found_so_far.add(text_if_applied)
yield completion
The provided code snippet includes necessary dependencies for implementing the `merge_completers` function. Write a Python function `def merge_completers( completers: Sequence[Completer], deduplicate: bool = False ) -> Completer` to solve the following problem:
Combine several completers into one. :param deduplicate: If `True`, wrap the result in a `DeduplicateCompleter` so that completions that would result in the same text will be deduplicated.
Here is the function:
def merge_completers(
completers: Sequence[Completer], deduplicate: bool = False
) -> Completer:
"""
Combine several completers into one.
:param deduplicate: If `True`, wrap the result in a `DeduplicateCompleter`
so that completions that would result in the same text will be
deduplicated.
"""
if deduplicate:
from .deduplicate import DeduplicateCompleter
return DeduplicateCompleter(_MergedCompleter(completers))
return _MergedCompleter(completers) | Combine several completers into one. :param deduplicate: If `True`, wrap the result in a `DeduplicateCompleter` so that completions that would result in the same text will be deduplicated. |
172,131 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from typing import AsyncGenerator, Callable, Iterable, Optional, Sequence
from prompt_toolkit.document import Document
from prompt_toolkit.eventloop import aclosing, generator_to_async_generator
from prompt_toolkit.filters import FilterOrBool, to_filter
from prompt_toolkit.formatted_text import AnyFormattedText, StyleAndTextTuples
class Completion:
"""
:param text: The new string that will be inserted into the document.
:param start_position: Position relative to the cursor_position where the
new text will start. The text will be inserted between the
start_position and the original cursor position.
:param display: (optional string or formatted text) If the completion has
to be displayed differently in the completion menu.
:param display_meta: (Optional string or formatted text) Meta information
about the completion, e.g. the path or source where it's coming from.
This can also be a callable that returns a string.
:param style: Style string.
:param selected_style: Style string, used for a selected completion.
This can override the `style` parameter.
"""
def __init__(
self,
text: str,
start_position: int = 0,
display: AnyFormattedText | None = None,
display_meta: AnyFormattedText | None = None,
style: str = "",
selected_style: str = "",
) -> None:
from prompt_toolkit.formatted_text import to_formatted_text
self.text = text
self.start_position = start_position
self._display_meta = display_meta
if display is None:
display = text
self.display = to_formatted_text(display)
self.style = style
self.selected_style = selected_style
assert self.start_position <= 0
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,
)
else:
return "{}(text={!r}, start_position={!r}, display={!r})".format(
self.__class__.__name__,
self.text,
self.start_position,
self.display,
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Completion):
return False
return (
self.text == other.text
and self.start_position == other.start_position
and self.display == other.display
and self._display_meta == other._display_meta
)
def __hash__(self) -> int:
return hash((self.text, self.start_position, self.display, self._display_meta))
def display_text(self) -> str:
"The 'display' field as plain text."
from prompt_toolkit.formatted_text import fragment_list_to_text
return fragment_list_to_text(self.display)
def display_meta(self) -> StyleAndTextTuples:
"Return meta-text. (This is lazy when using a callable)."
from prompt_toolkit.formatted_text import to_formatted_text
return to_formatted_text(self._display_meta or "")
def display_meta_text(self) -> str:
"The 'meta' field as plain text."
from prompt_toolkit.formatted_text import fragment_list_to_text
return fragment_list_to_text(self.display_meta)
def new_completion_from_position(self, position: int) -> Completion:
"""
(Only for internal use!)
Get a new completion by splitting this one. Used by `Application` when
it needs to have a list of new completions after inserting the common
prefix.
"""
assert position - self.start_position >= 0
return Completion(
text=self.text[position - self.start_position :],
display=self.display,
display_meta=self._display_meta,
)
def _commonprefix(strings: Iterable[str]) -> str:
# Similar to os.path.commonprefix
if not strings:
return ""
else:
s1 = min(strings)
s2 = max(strings)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]):
def __getitem__(self, i: int) -> _T_co: ...
def __getitem__(self, s: slice) -> Sequence[_T_co]: ...
# Mixin methods
def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ...
def count(self, value: Any) -> int: ...
def __contains__(self, x: object) -> bool: ...
def __iter__(self) -> Iterator[_T_co]: ...
def __reversed__(self) -> Iterator[_T_co]: ...
class Document:
"""
This is a immutable class around the text and cursor position, and contains
methods for querying this data, e.g. to give the text before the cursor.
This class is usually instantiated by a :class:`~prompt_toolkit.buffer.Buffer`
object, and accessed as the `document` property of that class.
:param text: string
:param cursor_position: int
:param selection: :class:`.SelectionState`
"""
__slots__ = ("_text", "_cursor_position", "_selection", "_cache")
def __init__(
self,
text: str = "",
cursor_position: int | None = None,
selection: SelectionState | None = None,
) -> None:
# Check cursor position. It can also be right after the end. (Where we
# insert text.)
assert cursor_position is None or cursor_position <= len(text), AssertionError(
f"cursor_position={cursor_position!r}, len_text={len(text)!r}"
)
# By default, if no cursor position was given, make sure to put the
# cursor position is at the end of the document. This is what makes
# sense in most places.
if cursor_position is None:
cursor_position = len(text)
# Keep these attributes private. A `Document` really has to be
# considered to be immutable, because otherwise the caching will break
# things. Because of that, we wrap these into read-only properties.
self._text = text
self._cursor_position = cursor_position
self._selection = selection
# Cache for lines/indexes. (Shared with other Document instances that
# contain the same text.
try:
self._cache = _text_to_document_cache[self.text]
except KeyError:
self._cache = _DocumentCache()
_text_to_document_cache[self.text] = self._cache
# XX: For some reason, above, we can't use 'WeakValueDictionary.setdefault'.
# This fails in Pypy3. `self._cache` becomes None, because that's what
# 'setdefault' returns.
# self._cache = _text_to_document_cache.setdefault(self.text, _DocumentCache())
# assert self._cache
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.text!r}, {self.cursor_position!r})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Document):
return False
return (
self.text == other.text
and self.cursor_position == other.cursor_position
and self.selection == other.selection
)
def text(self) -> str:
"The document text."
return self._text
def cursor_position(self) -> int:
"The document cursor position."
return self._cursor_position
def selection(self) -> SelectionState | None:
":class:`.SelectionState` object."
return self._selection
def current_char(self) -> str:
"""Return character under cursor or an empty string."""
return self._get_char_relative_to_cursor(0) or ""
def char_before_cursor(self) -> str:
"""Return character before the cursor or an empty string."""
return self._get_char_relative_to_cursor(-1) or ""
def text_before_cursor(self) -> str:
return self.text[: self.cursor_position :]
def text_after_cursor(self) -> str:
return self.text[self.cursor_position :]
def current_line_before_cursor(self) -> str:
"""Text from the start of the line until the cursor."""
_, _, text = self.text_before_cursor.rpartition("\n")
return text
def current_line_after_cursor(self) -> str:
"""Text from the cursor until the end of the line."""
text, _, _ = self.text_after_cursor.partition("\n")
return text
def lines(self) -> list[str]:
"""
Array of all the lines.
"""
# Cache, because this one is reused very often.
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split("\n"))
return self._cache.lines
def _line_start_indexes(self) -> list[int]:
"""
Array pointing to the start indexes of all the lines.
"""
# Cache, because this is often reused. (If it is used, it's often used
# many times. And this has to be fast for editing big documents!)
if self._cache.line_indexes is None:
# Create list of line lengths.
line_lengths = map(len, self.lines)
# Calculate cumulative sums.
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
# Remove the last item. (This is not a new line.)
if len(indexes) > 1:
indexes.pop()
self._cache.line_indexes = indexes
return self._cache.line_indexes
def lines_from_current(self) -> list[str]:
"""
Array of the lines starting from the current line, until the last line.
"""
return self.lines[self.cursor_position_row :]
def line_count(self) -> int:
r"""Return the number of lines in this document. If the document ends
with a trailing \n, that counts as the beginning of a new line."""
return len(self.lines)
def current_line(self) -> str:
"""Return the text on the line where the cursor is. (when the input
consists of just one line, it equals `text`."""
return self.current_line_before_cursor + self.current_line_after_cursor
def leading_whitespace_in_current_line(self) -> str:
"""The leading whitespace in the left margin of the current line."""
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length]
def _get_char_relative_to_cursor(self, offset: int = 0) -> str:
"""
Return character relative to cursor position, or empty string
"""
try:
return self.text[self.cursor_position + offset]
except IndexError:
return ""
def on_first_line(self) -> bool:
"""
True when we are at the first line.
"""
return self.cursor_position_row == 0
def on_last_line(self) -> bool:
"""
True when we are at the last line.
"""
return self.cursor_position_row == self.line_count - 1
def cursor_position_row(self) -> int:
"""
Current row. (0-based.)
"""
row, _ = self._find_line_start_index(self.cursor_position)
return row
def cursor_position_col(self) -> int:
"""
Current column. (0-based.)
"""
# (Don't use self.text_before_cursor to calculate this. Creating
# substrings and doing rsplit is too expensive for getting the cursor
# position.)
_, line_start_index = self._find_line_start_index(self.cursor_position)
return self.cursor_position - line_start_index
def _find_line_start_index(self, index: int) -> tuple[int, int]:
"""
For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple.
"""
indexes = self._line_start_indexes
pos = bisect.bisect_right(indexes, index) - 1
return pos, indexes[pos]
def translate_index_to_position(self, index: int) -> tuple[int, int]:
"""
Given an index for the text, return the corresponding (row, col) tuple.
(0-based. Returns (0, 0) for index=0.)
"""
# Find start of this line.
row, row_index = self._find_line_start_index(index)
col = index - row_index
return row, col
def translate_row_col_to_index(self, row: int, col: int) -> int:
"""
Given a (row, col) tuple, return the corresponding index.
(Row and col params are 0-based.)
Negative row/col values are turned into zero.
"""
try:
result = self._line_start_indexes[row]
line = self.lines[row]
except IndexError:
if row < 0:
result = self._line_start_indexes[0]
line = self.lines[0]
else:
result = self._line_start_indexes[-1]
line = self.lines[-1]
result += max(0, min(col, len(line)))
# Keep in range. (len(self.text) is included, because the cursor can be
# right after the end of the text as well.)
result = max(0, min(result, len(self.text)))
return result
def is_cursor_at_the_end(self) -> bool:
"""True when the cursor is at the end of the text."""
return self.cursor_position == len(self.text)
def is_cursor_at_the_end_of_line(self) -> bool:
"""True when the cursor is at the end of this line."""
return self.current_char in ("\n", "")
def has_match_at_current_position(self, sub: str) -> bool:
"""
`True` when this substring is found at the cursor position.
"""
return self.text.find(sub, self.cursor_position) == self.cursor_position
def find(
self,
sub: str,
in_current_line: bool = False,
include_current_position: bool = False,
ignore_case: bool = False,
count: int = 1,
) -> int | None:
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurrence.
"""
assert isinstance(ignore_case, bool)
if in_current_line:
text = self.current_line_after_cursor
else:
text = self.text_after_cursor
if not include_current_position:
if len(text) == 0:
return None # (Otherwise, we always get a match for the empty string.)
else:
text = text[1:]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub), text, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
if include_current_position:
return match.start(0)
else:
return match.start(0) + 1
except StopIteration:
pass
return None
def find_all(self, sub: str, ignore_case: bool = False) -> list[int]:
"""
Find all occurrences of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)]
def find_backwards(
self,
sub: str,
in_current_line: bool = False,
ignore_case: bool = False,
count: int = 1,
) -> int | None:
"""
Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurrence.
"""
if in_current_line:
before_cursor = self.current_line_before_cursor[::-1]
else:
before_cursor = self.text_before_cursor[::-1]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.start(0) - len(sub)
except StopIteration:
pass
return None
def get_word_before_cursor(
self, WORD: bool = False, pattern: Pattern[str] | None = None
) -> str:
"""
Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string.
:param pattern: (None or compiled regex). When given, use this regex
pattern.
"""
if self._is_word_before_cursor_complete(WORD=WORD, pattern=pattern):
# Space before the cursor or no text before cursor.
return ""
text_before_cursor = self.text_before_cursor
start = self.find_start_of_previous_word(WORD=WORD, pattern=pattern) or 0
return text_before_cursor[len(text_before_cursor) + start :]
def _is_word_before_cursor_complete(
self, WORD: bool = False, pattern: Pattern[str] | None = None
) -> bool:
if pattern:
return self.find_start_of_previous_word(WORD=WORD, pattern=pattern) is None
else:
return (
self.text_before_cursor == "" or self.text_before_cursor[-1:].isspace()
)
def find_start_of_previous_word(
self, count: int = 1, WORD: bool = False, pattern: Pattern[str] | None = None
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found.
:param pattern: (None or compiled regex). When given, use this regex
pattern.
"""
assert not (WORD and pattern)
# Reverse the text before the cursor, in order to do an efficient
# backwards search.
text_before_cursor = self.text_before_cursor[::-1]
if pattern:
regex = pattern
elif WORD:
regex = _FIND_BIG_WORD_RE
else:
regex = _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.end(0)
except StopIteration:
pass
return None
def find_boundaries_of_current_word(
self,
WORD: bool = False,
include_leading_whitespace: bool = False,
include_trailing_whitespace: bool = False,
) -> tuple[int, int]:
"""
Return the relative boundaries (startpos, endpos) of the current word under the
cursor. (This is at the current line, because line boundaries obviously
don't belong to any word.)
If not on a word, this returns (0,0)
"""
text_before_cursor = self.current_line_before_cursor[::-1]
text_after_cursor = self.current_line_after_cursor
def get_regex(include_whitespace: bool) -> Pattern[str]:
return {
(False, False): _FIND_CURRENT_WORD_RE,
(False, True): _FIND_CURRENT_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
(True, False): _FIND_CURRENT_BIG_WORD_RE,
(True, True): _FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
}[(WORD, include_whitespace)]
match_before = get_regex(include_leading_whitespace).search(text_before_cursor)
match_after = get_regex(include_trailing_whitespace).search(text_after_cursor)
# When there is a match before and after, and we're not looking for
# WORDs, make sure that both the part before and after the cursor are
# either in the [a-zA-Z_] alphabet or not. Otherwise, drop the part
# before the cursor.
if not WORD and match_before and match_after:
c1 = self.text[self.cursor_position - 1]
c2 = self.text[self.cursor_position]
alphabet = string.ascii_letters + "0123456789_"
if (c1 in alphabet) != (c2 in alphabet):
match_before = None
return (
-match_before.end(1) if match_before else 0,
match_after.end(1) if match_after else 0,
)
def get_word_under_cursor(self, WORD: bool = False) -> str:
"""
Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region.
"""
start, end = self.find_boundaries_of_current_word(WORD=WORD)
return self.text[self.cursor_position + start : self.cursor_position + end]
def find_next_word_beginning(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_after_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return match.start(1)
except StopIteration:
pass
return None
def find_next_word_ending(
self, include_current_position: bool = False, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_ending(count=-count, WORD=WORD)
if include_current_position:
text = self.text_after_cursor
else:
text = self.text_after_cursor[1:]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterable = regex.finditer(text)
try:
for i, match in enumerate(iterable):
if i + 1 == count:
value = match.end(1)
if include_current_position:
return value
else:
return value + 1
except StopIteration:
pass
return None
def find_previous_word_beginning(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_before_cursor[::-1])
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return -match.end(1)
except StopIteration:
pass
return None
def find_previous_word_ending(
self, count: int = 1, WORD: bool = False
) -> int | None:
"""
Return an index relative to the cursor position pointing to the end
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_ending(count=-count, WORD=WORD)
text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return -match.start(1) + 1
except StopIteration:
pass
return None
def find_next_matching_line(
self, match_func: Callable[[str], bool], count: int = 1
) -> int | None:
"""
Look downwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[self.cursor_position_row + 1 :]):
if match_func(line):
result = 1 + index
count -= 1
if count == 0:
break
return result
def find_previous_matching_line(
self, match_func: Callable[[str], bool], count: int = 1
) -> int | None:
"""
Look upwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[: self.cursor_position_row][::-1]):
if match_func(line):
result = -1 - index
count -= 1
if count == 0:
break
return result
def get_cursor_left_position(self, count: int = 1) -> int:
"""
Relative position for cursor left.
"""
if count < 0:
return self.get_cursor_right_position(-count)
return -min(self.cursor_position_col, count)
def get_cursor_right_position(self, count: int = 1) -> int:
"""
Relative position for cursor_right.
"""
if count < 0:
return self.get_cursor_left_position(-count)
return min(count, len(self.current_line_after_cursor))
def get_cursor_up_position(
self, count: int = 1, preferred_column: int | None = None
) -> int:
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-up button.
:param preferred_column: When given, go to this column instead of
staying at the current column.
"""
assert count >= 1
column = (
self.cursor_position_col if preferred_column is None else preferred_column
)
return (
self.translate_row_col_to_index(
max(0, self.cursor_position_row - count), column
)
- self.cursor_position
)
def get_cursor_down_position(
self, count: int = 1, preferred_column: int | None = None
) -> int:
"""
Return the relative cursor position (character index) where we would be if the
user pressed the arrow-down button.
:param preferred_column: When given, go to this column instead of
staying at the current column.
"""
assert count >= 1
column = (
self.cursor_position_col if preferred_column is None else preferred_column
)
return (
self.translate_row_col_to_index(self.cursor_position_row + count, column)
- self.cursor_position
)
def find_enclosing_bracket_right(
self, left_ch: str, right_ch: str, end_pos: int | None = None
) -> int | None:
"""
Find the right bracket enclosing current position. Return the relative
position to the cursor position.
When `end_pos` is given, don't look past the position.
"""
if self.current_char == right_ch:
return 0
if end_pos is None:
end_pos = len(self.text)
else:
end_pos = min(len(self.text), end_pos)
stack = 1
# Look forward.
for i in range(self.cursor_position + 1, end_pos):
c = self.text[i]
if c == left_ch:
stack += 1
elif c == right_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position
return None
def find_enclosing_bracket_left(
self, left_ch: str, right_ch: str, start_pos: int | None = None
) -> int | None:
"""
Find the left bracket enclosing current position. Return the relative
position to the cursor position.
When `start_pos` is given, don't look past the position.
"""
if self.current_char == left_ch:
return 0
if start_pos is None:
start_pos = 0
else:
start_pos = max(0, start_pos)
stack = 1
# Look backward.
for i in range(self.cursor_position - 1, start_pos - 1, -1):
c = self.text[i]
if c == right_ch:
stack += 1
elif c == left_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position
return None
def find_matching_bracket_position(
self, start_pos: int | None = None, end_pos: int | None = None
) -> int:
"""
Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
# Look for a match.
for pair in "()", "[]", "{}", "<>":
A = pair[0]
B = pair[1]
if self.current_char == A:
return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
elif self.current_char == B:
return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
return 0
def get_start_of_document_position(self) -> int:
"""Relative position for the start of the document."""
return -self.cursor_position
def get_end_of_document_position(self) -> int:
"""Relative position for the end of the document."""
return len(self.text) - self.cursor_position
def get_start_of_line_position(self, after_whitespace: bool = False) -> int:
"""Relative position for the start of this line."""
if after_whitespace:
current_line = self.current_line
return (
len(current_line)
- len(current_line.lstrip())
- self.cursor_position_col
)
else:
return -len(self.current_line_before_cursor)
def get_end_of_line_position(self) -> int:
"""Relative position for the end of this line."""
return len(self.current_line_after_cursor)
def last_non_blank_of_current_line_position(self) -> int:
"""
Relative position for the last non blank character of this line.
"""
return len(self.current_line.rstrip()) - self.cursor_position_col - 1
def get_column_cursor_position(self, column: int) -> int:
"""
Return the relative cursor position for this column at the current
line. (It will stay between the boundaries of the line in case of a
larger number.)
"""
line_length = len(self.current_line)
current_column = self.cursor_position_col
column = max(0, min(line_length, column))
return column - current_column
def selection_range(
self,
) -> tuple[
int, int
]: # XXX: shouldn't this return `None` if there is no selection???
"""
Return (from, to) tuple of the selection.
start and end position are included.
This doesn't take the selection type into account. Use
`selection_ranges` instead.
"""
if self.selection:
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
else:
from_, to = self.cursor_position, self.cursor_position
return from_, to
def selection_ranges(self) -> Iterable[tuple[int, int]]:
"""
Return a list of `(from, to)` tuples for the selection or none if
nothing was selected. The upper boundary is not included.
This will yield several (from, to) tuples in case of a BLOCK selection.
This will return zero ranges, like (8,8) for empty lines in a block
selection.
"""
if self.selection:
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
if self.selection.type == SelectionType.BLOCK:
from_line, from_column = self.translate_index_to_position(from_)
to_line, to_column = self.translate_index_to_position(to)
from_column, to_column = sorted([from_column, to_column])
lines = self.lines
if vi_mode():
to_column += 1
for l in range(from_line, to_line + 1):
line_length = len(lines[l])
if from_column <= line_length:
yield (
self.translate_row_col_to_index(l, from_column),
self.translate_row_col_to_index(
l, min(line_length, to_column)
),
)
else:
# In case of a LINES selection, go to the start/end of the lines.
if self.selection.type == SelectionType.LINES:
from_ = max(0, self.text.rfind("\n", 0, from_) + 1)
if self.text.find("\n", to) >= 0:
to = self.text.find("\n", to)
else:
to = len(self.text) - 1
# In Vi mode, the upper boundary is always included. For Emacs,
# that's not the case.
if vi_mode():
to += 1
yield from_, to
def selection_range_at_line(self, row: int) -> tuple[int, int] | None:
"""
If the selection spans a portion of the given line, return a (from, to) tuple.
The returned upper boundary is not included in the selection, so
`(0, 0)` is an empty selection. `(0, 1)`, is a one character selection.
Returns None if the selection doesn't cover this line at all.
"""
if self.selection:
line = self.lines[row]
row_start = self.translate_row_col_to_index(row, 0)
row_end = self.translate_row_col_to_index(row, len(line))
from_, to = sorted(
[self.cursor_position, self.selection.original_cursor_position]
)
# Take the intersection of the current line and the selection.
intersection_start = max(row_start, from_)
intersection_end = min(row_end, to)
if intersection_start <= intersection_end:
if self.selection.type == SelectionType.LINES:
intersection_start = row_start
intersection_end = row_end
elif self.selection.type == SelectionType.BLOCK:
_, col1 = self.translate_index_to_position(from_)
_, col2 = self.translate_index_to_position(to)
col1, col2 = sorted([col1, col2])
if col1 > len(line):
return None # Block selection doesn't cross this line.
intersection_start = self.translate_row_col_to_index(row, col1)
intersection_end = self.translate_row_col_to_index(row, col2)
_, from_column = self.translate_index_to_position(intersection_start)
_, to_column = self.translate_index_to_position(intersection_end)
# In Vi mode, the upper boundary is always included. For Emacs
# mode, that's not the case.
if vi_mode():
to_column += 1
return from_column, to_column
return None
def cut_selection(self) -> tuple[Document, ClipboardData]:
"""
Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the
document represents the new document when the selection is cut, and the
clipboard data, represents whatever has to be put on the clipboard.
"""
if self.selection:
cut_parts = []
remaining_parts = []
new_cursor_position = self.cursor_position
last_to = 0
for from_, to in self.selection_ranges():
if last_to == 0:
new_cursor_position = from_
remaining_parts.append(self.text[last_to:from_])
cut_parts.append(self.text[from_:to])
last_to = to
remaining_parts.append(self.text[last_to:])
cut_text = "\n".join(cut_parts)
remaining_text = "".join(remaining_parts)
# In case of a LINES selection, don't include the trailing newline.
if self.selection.type == SelectionType.LINES and cut_text.endswith("\n"):
cut_text = cut_text[:-1]
return (
Document(text=remaining_text, cursor_position=new_cursor_position),
ClipboardData(cut_text, self.selection.type),
)
else:
return self, ClipboardData("")
def paste_clipboard_data(
self,
data: ClipboardData,
paste_mode: PasteMode = PasteMode.EMACS,
count: int = 1,
) -> Document:
"""
Return a new :class:`.Document` instance which contains the result if
we would paste this data at the current cursor position.
:param paste_mode: Where to paste. (Before/after/emacs.)
:param count: When >1, Paste multiple times.
"""
before = paste_mode == PasteMode.VI_BEFORE
after = paste_mode == PasteMode.VI_AFTER
if data.type == SelectionType.CHARACTERS:
if after:
new_text = (
self.text[: self.cursor_position + 1]
+ data.text * count
+ self.text[self.cursor_position + 1 :]
)
else:
new_text = (
self.text_before_cursor + data.text * count + self.text_after_cursor
)
new_cursor_position = self.cursor_position + len(data.text) * count
if before:
new_cursor_position -= 1
elif data.type == SelectionType.LINES:
l = self.cursor_position_row
if before:
lines = self.lines[:l] + [data.text] * count + self.lines[l:]
new_text = "\n".join(lines)
new_cursor_position = len("".join(self.lines[:l])) + l
else:
lines = self.lines[: l + 1] + [data.text] * count + self.lines[l + 1 :]
new_cursor_position = len("".join(self.lines[: l + 1])) + l + 1
new_text = "\n".join(lines)
elif data.type == SelectionType.BLOCK:
lines = self.lines[:]
start_line = self.cursor_position_row
start_column = self.cursor_position_col + (0 if before else 1)
for i, line in enumerate(data.text.split("\n")):
index = i + start_line
if index >= len(lines):
lines.append("")
lines[index] = lines[index].ljust(start_column)
lines[index] = (
lines[index][:start_column]
+ line * count
+ lines[index][start_column:]
)
new_text = "\n".join(lines)
new_cursor_position = self.cursor_position + (0 if before else 1)
return Document(text=new_text, cursor_position=new_cursor_position)
def empty_line_count_at_the_end(self) -> int:
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count
def start_of_paragraph(self, count: int = 1, before: bool = False) -> int:
"""
Return the start of the current paragraph. (Relative cursor position.)
"""
def match_func(text: str) -> bool:
return not text or text.isspace()
line_index = self.find_previous_matching_line(
match_func=match_func, count=count
)
if line_index:
add = 0 if before else 1
return min(0, self.get_cursor_up_position(count=-line_index) + add)
else:
return -self.cursor_position
def end_of_paragraph(self, count: int = 1, after: bool = False) -> int:
"""
Return the end of the current paragraph. (Relative cursor position.)
"""
def match_func(text: str) -> bool:
return not text or text.isspace()
line_index = self.find_next_matching_line(match_func=match_func, count=count)
if line_index:
add = 0 if after else 1
return max(0, self.get_cursor_down_position(count=line_index) - add)
else:
return len(self.text_after_cursor)
# Modifiers.
def insert_after(self, text: str) -> Document:
"""
Create a new document, with this text inserted after the buffer.
It keeps selection ranges and cursor position in sync.
"""
return Document(
text=self.text + text,
cursor_position=self.cursor_position,
selection=self.selection,
)
def insert_before(self, text: str) -> Document:
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
original_cursor_position=selection_state.original_cursor_position
+ len(text),
type=selection_state.type,
)
return Document(
text=text + self.text,
cursor_position=self.cursor_position + len(text),
selection=selection_state,
)
The provided code snippet includes necessary dependencies for implementing the `get_common_complete_suffix` function. Write a Python function `def get_common_complete_suffix( document: Document, completions: Sequence[Completion] ) -> str` to solve the following problem:
Return the common prefix for all completions.
Here is the function:
def get_common_complete_suffix(
document: Document, completions: Sequence[Completion]
) -> str:
"""
Return the common prefix for all completions.
"""
# Take only completions that don't change the text before the cursor.
def doesnt_change_before_cursor(completion: Completion) -> bool:
end = completion.text[: -completion.start_position]
return document.text_before_cursor.endswith(end)
completions2 = [c for c in completions if doesnt_change_before_cursor(c)]
# When there is at least one completion that changes the text before the
# cursor, don't return any common part.
if len(completions2) != len(completions):
return ""
# Return the common prefix.
def get_suffix(completion: Completion) -> str:
return completion.text[-completion.start_position :]
return _commonprefix([get_suffix(c) for c in completions2]) | Return the common prefix for all completions. |
172,132 | from __future__ import annotations
import os
import sys
from abc import abstractmethod
from asyncio import get_running_loop
from contextlib import contextmanager
from ..utils import SPHINX_AUTODOC_RUNNING
from ctypes import Array, pointer
from ctypes.wintypes import DWORD, HANDLE
from typing import (
Callable,
ContextManager,
Dict,
Iterable,
Iterator,
List,
Optional,
TextIO,
)
from prompt_toolkit.eventloop import run_in_executor_with_context
from prompt_toolkit.eventloop.win32 import create_win32_event, wait_for_handles
from prompt_toolkit.key_binding.key_processor import KeyPress
from prompt_toolkit.keys import Keys
from prompt_toolkit.mouse_events import MouseButton, MouseEventType
from prompt_toolkit.win32_types import (
INPUT_RECORD,
KEY_EVENT_RECORD,
MOUSE_EVENT_RECORD,
STD_INPUT_HANDLE,
EventTypes,
)
from .ansi_escape_sequences import REVERSE_ANSI_SEQUENCES
from .base import Input
class _Win32InputBase(Input):
"""
Base class for `Win32Input` and `Win32PipeInput`.
"""
def __init__(self) -> None:
self.win32_handles = _Win32Handles()
def handle(self) -> HANDLE:
pass
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
class Iterator(Iterable[_T_co], Protocol[_T_co]):
def __next__(self) -> _T_co: ...
def __iter__(self) -> Iterator[_T_co]: ...
The provided code snippet includes necessary dependencies for implementing the `attach_win32_input` function. Write a Python function `def attach_win32_input( input: _Win32InputBase, callback: Callable[[], None] ) -> Iterator[None]` to solve the following problem:
Context manager that makes this input active in the current event loop. :param input: :class:`~prompt_toolkit.input.Input` object. :param input_ready_callback: Called when the input is ready to read.
Here is the function:
def attach_win32_input(
input: _Win32InputBase, callback: Callable[[], None]
) -> Iterator[None]:
"""
Context manager that makes this input active in the current event loop.
:param input: :class:`~prompt_toolkit.input.Input` object.
:param input_ready_callback: Called when the input is ready to read.
"""
win32_handles = input.win32_handles
handle = input.handle
if handle.value is None:
raise ValueError("Invalid handle.")
# Add reader.
previous_callback = win32_handles.remove_win32_handle(handle)
win32_handles.add_win32_handle(handle, callback)
try:
yield
finally:
win32_handles.remove_win32_handle(handle)
if previous_callback:
win32_handles.add_win32_handle(handle, previous_callback) | Context manager that makes this input active in the current event loop. :param input: :class:`~prompt_toolkit.input.Input` object. :param input_ready_callback: Called when the input is ready to read. |
172,133 | from __future__ import annotations
import os
import sys
from abc import abstractmethod
from asyncio import get_running_loop
from contextlib import contextmanager
from ..utils import SPHINX_AUTODOC_RUNNING
from ctypes import Array, pointer
from ctypes.wintypes import DWORD, HANDLE
from typing import (
Callable,
ContextManager,
Dict,
Iterable,
Iterator,
List,
Optional,
TextIO,
)
from prompt_toolkit.eventloop import run_in_executor_with_context
from prompt_toolkit.eventloop.win32 import create_win32_event, wait_for_handles
from prompt_toolkit.key_binding.key_processor import KeyPress
from prompt_toolkit.keys import Keys
from prompt_toolkit.mouse_events import MouseButton, MouseEventType
from prompt_toolkit.win32_types import (
INPUT_RECORD,
KEY_EVENT_RECORD,
MOUSE_EVENT_RECORD,
STD_INPUT_HANDLE,
EventTypes,
)
from .ansi_escape_sequences import REVERSE_ANSI_SEQUENCES
from .base import Input
class _Win32InputBase(Input):
"""
Base class for `Win32Input` and `Win32PipeInput`.
"""
def __init__(self) -> None:
self.win32_handles = _Win32Handles()
def handle(self) -> HANDLE:
pass
class Iterator(Iterable[_T_co], Protocol[_T_co]):
def __next__(self) -> _T_co: ...
def __iter__(self) -> Iterator[_T_co]: ...
def detach_win32_input(input: _Win32InputBase) -> Iterator[None]:
win32_handles = input.win32_handles
handle = input.handle
if handle.value is None:
raise ValueError("Invalid handle.")
previous_callback = win32_handles.remove_win32_handle(handle)
try:
yield
finally:
if previous_callback:
win32_handles.add_win32_handle(handle, previous_callback) | null |
172,134 | from __future__ import annotations
from typing import Dict, Tuple, Union
from ..keys import Keys
ANSI_SEQUENCES: dict[str, Keys | tuple[Keys, ...]] = {
# Control keys.
"\x00": Keys.ControlAt, # Control-At (Also for Ctrl-Space)
"\x01": Keys.ControlA, # Control-A (home)
"\x02": Keys.ControlB, # Control-B (emacs cursor left)
"\x03": Keys.ControlC, # Control-C (interrupt)
"\x04": Keys.ControlD, # Control-D (exit)
"\x05": Keys.ControlE, # Control-E (end)
"\x06": Keys.ControlF, # Control-F (cursor forward)
"\x07": Keys.ControlG, # Control-G
"\x08": Keys.ControlH, # Control-H (8) (Identical to '\b')
"\x09": Keys.ControlI, # Control-I (9) (Identical to '\t')
"\x0a": Keys.ControlJ, # Control-J (10) (Identical to '\n')
"\x0b": Keys.ControlK, # Control-K (delete until end of line; vertical tab)
"\x0c": Keys.ControlL, # Control-L (clear; form feed)
"\x0d": Keys.ControlM, # Control-M (13) (Identical to '\r')
"\x0e": Keys.ControlN, # Control-N (14) (history forward)
"\x0f": Keys.ControlO, # Control-O (15)
"\x10": Keys.ControlP, # Control-P (16) (history back)
"\x11": Keys.ControlQ, # Control-Q
"\x12": Keys.ControlR, # Control-R (18) (reverse search)
"\x13": Keys.ControlS, # Control-S (19) (forward search)
"\x14": Keys.ControlT, # Control-T
"\x15": Keys.ControlU, # Control-U
"\x16": Keys.ControlV, # Control-V
"\x17": Keys.ControlW, # Control-W
"\x18": Keys.ControlX, # Control-X
"\x19": Keys.ControlY, # Control-Y (25)
"\x1a": Keys.ControlZ, # Control-Z
"\x1b": Keys.Escape, # Also Control-[
"\x9b": Keys.ShiftEscape,
"\x1c": Keys.ControlBackslash, # Both Control-\ (also Ctrl-| )
"\x1d": Keys.ControlSquareClose, # Control-]
"\x1e": Keys.ControlCircumflex, # Control-^
"\x1f": Keys.ControlUnderscore, # Control-underscore (Also for Ctrl-hyphen.)
# ASCII Delete (0x7f)
# Vt220 (and Linux terminal) send this when pressing backspace. We map this
# to ControlH, because that will make it easier to create key bindings that
# work everywhere, with the trade-off that it's no longer possible to
# handle backspace and control-h individually for the few terminals that
# support it. (Most terminals send ControlH when backspace is pressed.)
# See: http://www.ibb.net/~anne/keyboard.html
"\x7f": Keys.ControlH,
# --
# Various
"\x1b[1~": Keys.Home, # tmux
"\x1b[2~": Keys.Insert,
"\x1b[3~": Keys.Delete,
"\x1b[4~": Keys.End, # tmux
"\x1b[5~": Keys.PageUp,
"\x1b[6~": Keys.PageDown,
"\x1b[7~": Keys.Home, # xrvt
"\x1b[8~": Keys.End, # xrvt
"\x1b[Z": Keys.BackTab, # shift + tab
"\x1b\x09": Keys.BackTab, # Linux console
"\x1b[~": Keys.BackTab, # Windows console
# --
# Function keys.
"\x1bOP": Keys.F1,
"\x1bOQ": Keys.F2,
"\x1bOR": Keys.F3,
"\x1bOS": Keys.F4,
"\x1b[[A": Keys.F1, # Linux console.
"\x1b[[B": Keys.F2, # Linux console.
"\x1b[[C": Keys.F3, # Linux console.
"\x1b[[D": Keys.F4, # Linux console.
"\x1b[[E": Keys.F5, # Linux console.
"\x1b[11~": Keys.F1, # rxvt-unicode
"\x1b[12~": Keys.F2, # rxvt-unicode
"\x1b[13~": Keys.F3, # rxvt-unicode
"\x1b[14~": Keys.F4, # rxvt-unicode
"\x1b[15~": Keys.F5,
"\x1b[17~": Keys.F6,
"\x1b[18~": Keys.F7,
"\x1b[19~": Keys.F8,
"\x1b[20~": Keys.F9,
"\x1b[21~": Keys.F10,
"\x1b[23~": Keys.F11,
"\x1b[24~": Keys.F12,
"\x1b[25~": Keys.F13,
"\x1b[26~": Keys.F14,
"\x1b[28~": Keys.F15,
"\x1b[29~": Keys.F16,
"\x1b[31~": Keys.F17,
"\x1b[32~": Keys.F18,
"\x1b[33~": Keys.F19,
"\x1b[34~": Keys.F20,
# Xterm
"\x1b[1;2P": Keys.F13,
"\x1b[1;2Q": Keys.F14,
# '\x1b[1;2R': Keys.F15, # Conflicts with CPR response.
"\x1b[1;2S": Keys.F16,
"\x1b[15;2~": Keys.F17,
"\x1b[17;2~": Keys.F18,
"\x1b[18;2~": Keys.F19,
"\x1b[19;2~": Keys.F20,
"\x1b[20;2~": Keys.F21,
"\x1b[21;2~": Keys.F22,
"\x1b[23;2~": Keys.F23,
"\x1b[24;2~": Keys.F24,
# --
# CSI 27 disambiguated modified "other" keys (xterm)
# Ref: https://invisible-island.net/xterm/modified-keys.html
# These are currently unsupported, so just re-map some common ones to the
# unmodified versions
"\x1b[27;2;13~": Keys.ControlM, # Shift + Enter
"\x1b[27;5;13~": Keys.ControlM, # Ctrl + Enter
"\x1b[27;6;13~": Keys.ControlM, # Ctrl + Shift + Enter
# --
# Control + function keys.
"\x1b[1;5P": Keys.ControlF1,
"\x1b[1;5Q": Keys.ControlF2,
# "\x1b[1;5R": Keys.ControlF3, # Conflicts with CPR response.
"\x1b[1;5S": Keys.ControlF4,
"\x1b[15;5~": Keys.ControlF5,
"\x1b[17;5~": Keys.ControlF6,
"\x1b[18;5~": Keys.ControlF7,
"\x1b[19;5~": Keys.ControlF8,
"\x1b[20;5~": Keys.ControlF9,
"\x1b[21;5~": Keys.ControlF10,
"\x1b[23;5~": Keys.ControlF11,
"\x1b[24;5~": Keys.ControlF12,
"\x1b[1;6P": Keys.ControlF13,
"\x1b[1;6Q": Keys.ControlF14,
# "\x1b[1;6R": Keys.ControlF15, # Conflicts with CPR response.
"\x1b[1;6S": Keys.ControlF16,
"\x1b[15;6~": Keys.ControlF17,
"\x1b[17;6~": Keys.ControlF18,
"\x1b[18;6~": Keys.ControlF19,
"\x1b[19;6~": Keys.ControlF20,
"\x1b[20;6~": Keys.ControlF21,
"\x1b[21;6~": Keys.ControlF22,
"\x1b[23;6~": Keys.ControlF23,
"\x1b[24;6~": Keys.ControlF24,
# --
# Tmux (Win32 subsystem) sends the following scroll events.
"\x1b[62~": Keys.ScrollUp,
"\x1b[63~": Keys.ScrollDown,
"\x1b[200~": Keys.BracketedPaste, # Start of bracketed paste.
# --
# Sequences generated by numpad 5. Not sure what it means. (It doesn't
# appear in 'infocmp'. Just ignore.
"\x1b[E": Keys.Ignore, # Xterm.
"\x1b[G": Keys.Ignore, # Linux console.
# --
# Meta/control/escape + pageup/pagedown/insert/delete.
"\x1b[3;2~": Keys.ShiftDelete, # xterm, gnome-terminal.
"\x1b[5;2~": Keys.ShiftPageUp,
"\x1b[6;2~": Keys.ShiftPageDown,
"\x1b[2;3~": (Keys.Escape, Keys.Insert),
"\x1b[3;3~": (Keys.Escape, Keys.Delete),
"\x1b[5;3~": (Keys.Escape, Keys.PageUp),
"\x1b[6;3~": (Keys.Escape, Keys.PageDown),
"\x1b[2;4~": (Keys.Escape, Keys.ShiftInsert),
"\x1b[3;4~": (Keys.Escape, Keys.ShiftDelete),
"\x1b[5;4~": (Keys.Escape, Keys.ShiftPageUp),
"\x1b[6;4~": (Keys.Escape, Keys.ShiftPageDown),
"\x1b[3;5~": Keys.ControlDelete, # xterm, gnome-terminal.
"\x1b[5;5~": Keys.ControlPageUp,
"\x1b[6;5~": Keys.ControlPageDown,
"\x1b[3;6~": Keys.ControlShiftDelete,
"\x1b[5;6~": Keys.ControlShiftPageUp,
"\x1b[6;6~": Keys.ControlShiftPageDown,
"\x1b[2;7~": (Keys.Escape, Keys.ControlInsert),
"\x1b[5;7~": (Keys.Escape, Keys.ControlPageDown),
"\x1b[6;7~": (Keys.Escape, Keys.ControlPageDown),
"\x1b[2;8~": (Keys.Escape, Keys.ControlShiftInsert),
"\x1b[5;8~": (Keys.Escape, Keys.ControlShiftPageDown),
"\x1b[6;8~": (Keys.Escape, Keys.ControlShiftPageDown),
# --
# Arrows.
# (Normal cursor mode).
"\x1b[A": Keys.Up,
"\x1b[B": Keys.Down,
"\x1b[C": Keys.Right,
"\x1b[D": Keys.Left,
"\x1b[H": Keys.Home,
"\x1b[F": Keys.End,
# Tmux sends following keystrokes when control+arrow is pressed, but for
# Emacs ansi-term sends the same sequences for normal arrow keys. Consider
# it a normal arrow press, because that's more important.
# (Application cursor mode).
"\x1bOA": Keys.Up,
"\x1bOB": Keys.Down,
"\x1bOC": Keys.Right,
"\x1bOD": Keys.Left,
"\x1bOF": Keys.End,
"\x1bOH": Keys.Home,
# Shift + arrows.
"\x1b[1;2A": Keys.ShiftUp,
"\x1b[1;2B": Keys.ShiftDown,
"\x1b[1;2C": Keys.ShiftRight,
"\x1b[1;2D": Keys.ShiftLeft,
"\x1b[1;2F": Keys.ShiftEnd,
"\x1b[1;2H": Keys.ShiftHome,
# Meta + arrow keys. Several terminals handle this differently.
# The following sequences are for xterm and gnome-terminal.
# (Iterm sends ESC followed by the normal arrow_up/down/left/right
# sequences, and the OSX Terminal sends ESCb and ESCf for "alt
# arrow_left" and "alt arrow_right." We don't handle these
# explicitly, in here, because would could not distinguish between
# pressing ESC (to go to Vi navigation mode), followed by just the
# 'b' or 'f' key. These combinations are handled in
# the input processor.)
"\x1b[1;3A": (Keys.Escape, Keys.Up),
"\x1b[1;3B": (Keys.Escape, Keys.Down),
"\x1b[1;3C": (Keys.Escape, Keys.Right),
"\x1b[1;3D": (Keys.Escape, Keys.Left),
"\x1b[1;3F": (Keys.Escape, Keys.End),
"\x1b[1;3H": (Keys.Escape, Keys.Home),
# Alt+shift+number.
"\x1b[1;4A": (Keys.Escape, Keys.ShiftDown),
"\x1b[1;4B": (Keys.Escape, Keys.ShiftUp),
"\x1b[1;4C": (Keys.Escape, Keys.ShiftRight),
"\x1b[1;4D": (Keys.Escape, Keys.ShiftLeft),
"\x1b[1;4F": (Keys.Escape, Keys.ShiftEnd),
"\x1b[1;4H": (Keys.Escape, Keys.ShiftHome),
# Control + arrows.
"\x1b[1;5A": Keys.ControlUp, # Cursor Mode
"\x1b[1;5B": Keys.ControlDown, # Cursor Mode
"\x1b[1;5C": Keys.ControlRight, # Cursor Mode
"\x1b[1;5D": Keys.ControlLeft, # Cursor Mode
"\x1b[1;5F": Keys.ControlEnd,
"\x1b[1;5H": Keys.ControlHome,
# Tmux sends following keystrokes when control+arrow is pressed, but for
# Emacs ansi-term sends the same sequences for normal arrow keys. Consider
# it a normal arrow press, because that's more important.
"\x1b[5A": Keys.ControlUp,
"\x1b[5B": Keys.ControlDown,
"\x1b[5C": Keys.ControlRight,
"\x1b[5D": Keys.ControlLeft,
"\x1bOc": Keys.ControlRight, # rxvt
"\x1bOd": Keys.ControlLeft, # rxvt
# Control + shift + arrows.
"\x1b[1;6A": Keys.ControlShiftDown,
"\x1b[1;6B": Keys.ControlShiftUp,
"\x1b[1;6C": Keys.ControlShiftRight,
"\x1b[1;6D": Keys.ControlShiftLeft,
"\x1b[1;6F": Keys.ControlShiftEnd,
"\x1b[1;6H": Keys.ControlShiftHome,
# Control + Meta + arrows.
"\x1b[1;7A": (Keys.Escape, Keys.ControlDown),
"\x1b[1;7B": (Keys.Escape, Keys.ControlUp),
"\x1b[1;7C": (Keys.Escape, Keys.ControlRight),
"\x1b[1;7D": (Keys.Escape, Keys.ControlLeft),
"\x1b[1;7F": (Keys.Escape, Keys.ControlEnd),
"\x1b[1;7H": (Keys.Escape, Keys.ControlHome),
# Meta + Shift + arrows.
"\x1b[1;8A": (Keys.Escape, Keys.ControlShiftDown),
"\x1b[1;8B": (Keys.Escape, Keys.ControlShiftUp),
"\x1b[1;8C": (Keys.Escape, Keys.ControlShiftRight),
"\x1b[1;8D": (Keys.Escape, Keys.ControlShiftLeft),
"\x1b[1;8F": (Keys.Escape, Keys.ControlShiftEnd),
"\x1b[1;8H": (Keys.Escape, Keys.ControlShiftHome),
# Meta + arrow on (some?) Macs when using iTerm defaults (see issue #483).
"\x1b[1;9A": (Keys.Escape, Keys.Up),
"\x1b[1;9B": (Keys.Escape, Keys.Down),
"\x1b[1;9C": (Keys.Escape, Keys.Right),
"\x1b[1;9D": (Keys.Escape, Keys.Left),
# --
# Control/shift/meta + number in mintty.
# (c-2 will actually send c-@ and c-6 will send c-^.)
"\x1b[1;5p": Keys.Control0,
"\x1b[1;5q": Keys.Control1,
"\x1b[1;5r": Keys.Control2,
"\x1b[1;5s": Keys.Control3,
"\x1b[1;5t": Keys.Control4,
"\x1b[1;5u": Keys.Control5,
"\x1b[1;5v": Keys.Control6,
"\x1b[1;5w": Keys.Control7,
"\x1b[1;5x": Keys.Control8,
"\x1b[1;5y": Keys.Control9,
"\x1b[1;6p": Keys.ControlShift0,
"\x1b[1;6q": Keys.ControlShift1,
"\x1b[1;6r": Keys.ControlShift2,
"\x1b[1;6s": Keys.ControlShift3,
"\x1b[1;6t": Keys.ControlShift4,
"\x1b[1;6u": Keys.ControlShift5,
"\x1b[1;6v": Keys.ControlShift6,
"\x1b[1;6w": Keys.ControlShift7,
"\x1b[1;6x": Keys.ControlShift8,
"\x1b[1;6y": Keys.ControlShift9,
"\x1b[1;7p": (Keys.Escape, Keys.Control0),
"\x1b[1;7q": (Keys.Escape, Keys.Control1),
"\x1b[1;7r": (Keys.Escape, Keys.Control2),
"\x1b[1;7s": (Keys.Escape, Keys.Control3),
"\x1b[1;7t": (Keys.Escape, Keys.Control4),
"\x1b[1;7u": (Keys.Escape, Keys.Control5),
"\x1b[1;7v": (Keys.Escape, Keys.Control6),
"\x1b[1;7w": (Keys.Escape, Keys.Control7),
"\x1b[1;7x": (Keys.Escape, Keys.Control8),
"\x1b[1;7y": (Keys.Escape, Keys.Control9),
"\x1b[1;8p": (Keys.Escape, Keys.ControlShift0),
"\x1b[1;8q": (Keys.Escape, Keys.ControlShift1),
"\x1b[1;8r": (Keys.Escape, Keys.ControlShift2),
"\x1b[1;8s": (Keys.Escape, Keys.ControlShift3),
"\x1b[1;8t": (Keys.Escape, Keys.ControlShift4),
"\x1b[1;8u": (Keys.Escape, Keys.ControlShift5),
"\x1b[1;8v": (Keys.Escape, Keys.ControlShift6),
"\x1b[1;8w": (Keys.Escape, Keys.ControlShift7),
"\x1b[1;8x": (Keys.Escape, Keys.ControlShift8),
"\x1b[1;8y": (Keys.Escape, Keys.ControlShift9),
}
class Keys(str, Enum):
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
value: str
Escape = "escape" # Also Control-[
ShiftEscape = "s-escape"
ControlAt = "c-@" # Also Control-Space.
ControlA = "c-a"
ControlB = "c-b"
ControlC = "c-c"
ControlD = "c-d"
ControlE = "c-e"
ControlF = "c-f"
ControlG = "c-g"
ControlH = "c-h"
ControlI = "c-i" # Tab
ControlJ = "c-j" # Newline
ControlK = "c-k"
ControlL = "c-l"
ControlM = "c-m" # Carriage return
ControlN = "c-n"
ControlO = "c-o"
ControlP = "c-p"
ControlQ = "c-q"
ControlR = "c-r"
ControlS = "c-s"
ControlT = "c-t"
ControlU = "c-u"
ControlV = "c-v"
ControlW = "c-w"
ControlX = "c-x"
ControlY = "c-y"
ControlZ = "c-z"
Control1 = "c-1"
Control2 = "c-2"
Control3 = "c-3"
Control4 = "c-4"
Control5 = "c-5"
Control6 = "c-6"
Control7 = "c-7"
Control8 = "c-8"
Control9 = "c-9"
Control0 = "c-0"
ControlShift1 = "c-s-1"
ControlShift2 = "c-s-2"
ControlShift3 = "c-s-3"
ControlShift4 = "c-s-4"
ControlShift5 = "c-s-5"
ControlShift6 = "c-s-6"
ControlShift7 = "c-s-7"
ControlShift8 = "c-s-8"
ControlShift9 = "c-s-9"
ControlShift0 = "c-s-0"
ControlBackslash = "c-\\"
ControlSquareClose = "c-]"
ControlCircumflex = "c-^"
ControlUnderscore = "c-_"
Left = "left"
Right = "right"
Up = "up"
Down = "down"
Home = "home"
End = "end"
Insert = "insert"
Delete = "delete"
PageUp = "pageup"
PageDown = "pagedown"
ControlLeft = "c-left"
ControlRight = "c-right"
ControlUp = "c-up"
ControlDown = "c-down"
ControlHome = "c-home"
ControlEnd = "c-end"
ControlInsert = "c-insert"
ControlDelete = "c-delete"
ControlPageUp = "c-pageup"
ControlPageDown = "c-pagedown"
ShiftLeft = "s-left"
ShiftRight = "s-right"
ShiftUp = "s-up"
ShiftDown = "s-down"
ShiftHome = "s-home"
ShiftEnd = "s-end"
ShiftInsert = "s-insert"
ShiftDelete = "s-delete"
ShiftPageUp = "s-pageup"
ShiftPageDown = "s-pagedown"
ControlShiftLeft = "c-s-left"
ControlShiftRight = "c-s-right"
ControlShiftUp = "c-s-up"
ControlShiftDown = "c-s-down"
ControlShiftHome = "c-s-home"
ControlShiftEnd = "c-s-end"
ControlShiftInsert = "c-s-insert"
ControlShiftDelete = "c-s-delete"
ControlShiftPageUp = "c-s-pageup"
ControlShiftPageDown = "c-s-pagedown"
BackTab = "s-tab" # shift + tab
F1 = "f1"
F2 = "f2"
F3 = "f3"
F4 = "f4"
F5 = "f5"
F6 = "f6"
F7 = "f7"
F8 = "f8"
F9 = "f9"
F10 = "f10"
F11 = "f11"
F12 = "f12"
F13 = "f13"
F14 = "f14"
F15 = "f15"
F16 = "f16"
F17 = "f17"
F18 = "f18"
F19 = "f19"
F20 = "f20"
F21 = "f21"
F22 = "f22"
F23 = "f23"
F24 = "f24"
ControlF1 = "c-f1"
ControlF2 = "c-f2"
ControlF3 = "c-f3"
ControlF4 = "c-f4"
ControlF5 = "c-f5"
ControlF6 = "c-f6"
ControlF7 = "c-f7"
ControlF8 = "c-f8"
ControlF9 = "c-f9"
ControlF10 = "c-f10"
ControlF11 = "c-f11"
ControlF12 = "c-f12"
ControlF13 = "c-f13"
ControlF14 = "c-f14"
ControlF15 = "c-f15"
ControlF16 = "c-f16"
ControlF17 = "c-f17"
ControlF18 = "c-f18"
ControlF19 = "c-f19"
ControlF20 = "c-f20"
ControlF21 = "c-f21"
ControlF22 = "c-f22"
ControlF23 = "c-f23"
ControlF24 = "c-f24"
# Matches any key.
Any = "<any>"
# Special.
ScrollUp = "<scroll-up>"
ScrollDown = "<scroll-down>"
CPRResponse = "<cursor-position-response>"
Vt100MouseEvent = "<vt100-mouse-event>"
WindowsMouseEvent = "<windows-mouse-event>"
BracketedPaste = "<bracketed-paste>"
SIGINT = "<sigint>"
# For internal use: key which is ignored.
# (The key binding for this key should not do anything.)
Ignore = "<ignore>"
# Some 'Key' aliases (for backwards-compatibility).
ControlSpace = ControlAt
Tab = ControlI
Enter = ControlM
Backspace = ControlH
# ShiftControl was renamed to ControlShift in
# 888fcb6fa4efea0de8333177e1bbc792f3ff3c24 (20 Feb 2020).
ShiftControlLeft = ControlShiftLeft
ShiftControlRight = ControlShiftRight
ShiftControlHome = ControlShiftHome
ShiftControlEnd = ControlShiftEnd
The provided code snippet includes necessary dependencies for implementing the `_get_reverse_ansi_sequences` function. Write a Python function `def _get_reverse_ansi_sequences() -> dict[Keys, str]` to solve the following problem:
Create a dictionary that maps prompt_toolkit keys back to the VT100 escape sequences.
Here is the function:
def _get_reverse_ansi_sequences() -> dict[Keys, str]:
"""
Create a dictionary that maps prompt_toolkit keys back to the VT100 escape
sequences.
"""
result: dict[Keys, str] = {}
for sequence, key in ANSI_SEQUENCES.items():
if not isinstance(key, tuple):
if key not in result:
result[key] = sequence
return result | Create a dictionary that maps prompt_toolkit keys back to the VT100 escape sequences. |
172,135 | from __future__ import annotations
import sys
import contextlib
import io
import termios
import tty
from asyncio import AbstractEventLoop, get_running_loop
from typing import (
Callable,
ContextManager,
Dict,
Generator,
List,
Optional,
Set,
TextIO,
Tuple,
Union,
)
from ..key_binding import KeyPress
from .base import Input
from .posix_utils import PosixStdinReader
from .vt100_parser import Vt100Parser
class Vt100Input(Input):
"""
Vt100 input for Posix systems.
(This uses a posix file descriptor that can be registered in the event loop.)
"""
# For the error messages. Only display "Input is not a terminal" once per
# file descriptor.
_fds_not_a_terminal: set[int] = set()
def __init__(self, stdin: TextIO) -> None:
# Test whether the given input object has a file descriptor.
# (Idle reports stdin to be a TTY, but fileno() is not implemented.)
try:
# This should not raise, but can return 0.
stdin.fileno()
except io.UnsupportedOperation as e:
if "idlelib.run" in sys.modules:
raise io.UnsupportedOperation(
"Stdin is not a terminal. Running from Idle is not supported."
) from e
else:
raise io.UnsupportedOperation("Stdin is not a terminal.") from e
# Even when we have a file descriptor, it doesn't mean it's a TTY.
# Normally, this requires a real TTY device, but people instantiate
# this class often during unit tests as well. They use for instance
# pexpect to pipe data into an application. For convenience, we print
# an error message and go on.
isatty = stdin.isatty()
fd = stdin.fileno()
if not isatty and fd not in Vt100Input._fds_not_a_terminal:
msg = "Warning: Input is not a terminal (fd=%r).\n"
sys.stderr.write(msg % fd)
sys.stderr.flush()
Vt100Input._fds_not_a_terminal.add(fd)
#
self.stdin = stdin
# Create a backup of the fileno(). We want this to work even if the
# underlying file is closed, so that `typeahead_hash()` keeps working.
self._fileno = stdin.fileno()
self._buffer: list[KeyPress] = [] # Buffer to collect the Key objects.
self.stdin_reader = PosixStdinReader(self._fileno, encoding=stdin.encoding)
self.vt100_parser = Vt100Parser(
lambda key_press: self._buffer.append(key_press)
)
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
return _attached_input(self, input_ready_callback)
def detach(self) -> ContextManager[None]:
"""
Return a context manager that makes sure that this input is not active
in the current event loop.
"""
return _detached_input(self)
def read_keys(self) -> list[KeyPress]:
"Read list of KeyPress."
# Read text from stdin.
data = self.stdin_reader.read()
# Pass it through our vt100 parser.
self.vt100_parser.feed(data)
# Return result.
result = self._buffer
self._buffer = []
return result
def flush_keys(self) -> list[KeyPress]:
"""
Flush pending keys and return them.
(Used for flushing the 'escape' key.)
"""
# Flush all pending keys. (This is most important to flush the vt100
# 'Escape' key early when nothing else follows.)
self.vt100_parser.flush()
# Return result.
result = self._buffer
self._buffer = []
return result
def closed(self) -> bool:
return self.stdin_reader.closed
def raw_mode(self) -> ContextManager[None]:
return raw_mode(self.stdin.fileno())
def cooked_mode(self) -> ContextManager[None]:
return cooked_mode(self.stdin.fileno())
def fileno(self) -> int:
return self.stdin.fileno()
def typeahead_hash(self) -> str:
return f"fd-{self._fileno}"
_current_callbacks: dict[
tuple[AbstractEventLoop, int], Callable[[], None] | None
] = {}
class Callable(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
except IndexError:
debug.warning('Callable[...] defined without two arguments')
return NO_VALUES
else:
from jedi.inference.gradual.annotation import infer_return_for_callable
return infer_return_for_callable(arguments, param_values, result_values)
def py__get__(self, instance, class_value):
return ValueSet([self])
class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
def __next__(self) -> _T_co: ...
def send(self, __value: _T_contra) -> _T_co: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> _T_co: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ...
def close(self) -> None: ...
def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ...
def gi_code(self) -> CodeType: ...
def gi_frame(self) -> FrameType: ...
def gi_running(self) -> bool: ...
def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ...
The provided code snippet includes necessary dependencies for implementing the `_attached_input` function. Write a Python function `def _attached_input( input: Vt100Input, callback: Callable[[], None] ) -> Generator[None, None, None]` to solve the following problem:
Context manager that makes this input active in the current event loop. :param input: :class:`~prompt_toolkit.input.Input` object. :param callback: Called when the input is ready to read.
Here is the function:
def _attached_input(
input: Vt100Input, callback: Callable[[], None]
) -> Generator[None, None, None]:
"""
Context manager that makes this input active in the current event loop.
:param input: :class:`~prompt_toolkit.input.Input` object.
:param callback: Called when the input is ready to read.
"""
loop = get_running_loop()
fd = input.fileno()
previous = _current_callbacks.get((loop, fd))
def callback_wrapper() -> None:
"""Wrapper around the callback that already removes the reader when
the input is closed. Otherwise, we keep continuously calling this
callback, until we leave the context manager (which can happen a bit
later). This fixes issues when piping /dev/null into a prompt_toolkit
application."""
if input.closed:
loop.remove_reader(fd)
callback()
try:
loop.add_reader(fd, callback_wrapper)
except PermissionError:
# For `EPollSelector`, adding /dev/null to the event loop will raise
# `PermisisonError` (that doesn't happen for `SelectSelector`
# apparently). Whenever we get a `PermissionError`, we can raise
# `EOFError`, because there's not more to be read anyway. `EOFError` is
# an exception that people expect in
# `prompt_toolkit.application.Application.run()`.
# To reproduce, do: `ptpython 0< /dev/null 1< /dev/null`
raise EOFError
_current_callbacks[loop, fd] = callback
try:
yield
finally:
loop.remove_reader(fd)
if previous:
loop.add_reader(fd, previous)
_current_callbacks[loop, fd] = previous
else:
del _current_callbacks[loop, fd] | Context manager that makes this input active in the current event loop. :param input: :class:`~prompt_toolkit.input.Input` object. :param callback: Called when the input is ready to read. |
172,136 | from __future__ import annotations
import sys
import contextlib
import io
import termios
import tty
from asyncio import AbstractEventLoop, get_running_loop
from typing import (
Callable,
ContextManager,
Dict,
Generator,
List,
Optional,
Set,
TextIO,
Tuple,
Union,
)
from ..key_binding import KeyPress
from .base import Input
from .posix_utils import PosixStdinReader
from .vt100_parser import Vt100Parser
class Vt100Input(Input):
"""
Vt100 input for Posix systems.
(This uses a posix file descriptor that can be registered in the event loop.)
"""
# For the error messages. Only display "Input is not a terminal" once per
# file descriptor.
_fds_not_a_terminal: set[int] = set()
def __init__(self, stdin: TextIO) -> None:
# Test whether the given input object has a file descriptor.
# (Idle reports stdin to be a TTY, but fileno() is not implemented.)
try:
# This should not raise, but can return 0.
stdin.fileno()
except io.UnsupportedOperation as e:
if "idlelib.run" in sys.modules:
raise io.UnsupportedOperation(
"Stdin is not a terminal. Running from Idle is not supported."
) from e
else:
raise io.UnsupportedOperation("Stdin is not a terminal.") from e
# Even when we have a file descriptor, it doesn't mean it's a TTY.
# Normally, this requires a real TTY device, but people instantiate
# this class often during unit tests as well. They use for instance
# pexpect to pipe data into an application. For convenience, we print
# an error message and go on.
isatty = stdin.isatty()
fd = stdin.fileno()
if not isatty and fd not in Vt100Input._fds_not_a_terminal:
msg = "Warning: Input is not a terminal (fd=%r).\n"
sys.stderr.write(msg % fd)
sys.stderr.flush()
Vt100Input._fds_not_a_terminal.add(fd)
#
self.stdin = stdin
# Create a backup of the fileno(). We want this to work even if the
# underlying file is closed, so that `typeahead_hash()` keeps working.
self._fileno = stdin.fileno()
self._buffer: list[KeyPress] = [] # Buffer to collect the Key objects.
self.stdin_reader = PosixStdinReader(self._fileno, encoding=stdin.encoding)
self.vt100_parser = Vt100Parser(
lambda key_press: self._buffer.append(key_press)
)
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
return _attached_input(self, input_ready_callback)
def detach(self) -> ContextManager[None]:
"""
Return a context manager that makes sure that this input is not active
in the current event loop.
"""
return _detached_input(self)
def read_keys(self) -> list[KeyPress]:
"Read list of KeyPress."
# Read text from stdin.
data = self.stdin_reader.read()
# Pass it through our vt100 parser.
self.vt100_parser.feed(data)
# Return result.
result = self._buffer
self._buffer = []
return result
def flush_keys(self) -> list[KeyPress]:
"""
Flush pending keys and return them.
(Used for flushing the 'escape' key.)
"""
# Flush all pending keys. (This is most important to flush the vt100
# 'Escape' key early when nothing else follows.)
self.vt100_parser.flush()
# Return result.
result = self._buffer
self._buffer = []
return result
def closed(self) -> bool:
return self.stdin_reader.closed
def raw_mode(self) -> ContextManager[None]:
return raw_mode(self.stdin.fileno())
def cooked_mode(self) -> ContextManager[None]:
return cooked_mode(self.stdin.fileno())
def fileno(self) -> int:
return self.stdin.fileno()
def typeahead_hash(self) -> str:
return f"fd-{self._fileno}"
_current_callbacks: dict[
tuple[AbstractEventLoop, int], Callable[[], None] | None
] = {}
class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
def __next__(self) -> _T_co: ...
def send(self, __value: _T_contra) -> _T_co: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> _T_co: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ...
def close(self) -> None: ...
def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ...
def gi_code(self) -> CodeType: ...
def gi_frame(self) -> FrameType: ...
def gi_running(self) -> bool: ...
def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ...
def _detached_input(input: Vt100Input) -> Generator[None, None, None]:
loop = get_running_loop()
fd = input.fileno()
previous = _current_callbacks.get((loop, fd))
if previous:
loop.remove_reader(fd)
_current_callbacks[loop, fd] = None
try:
yield
finally:
if previous:
loop.add_reader(fd, previous)
_current_callbacks[loop, fd] = previous | null |
172,137 | from __future__ import annotations
import io
import sys
from typing import ContextManager, Optional, TextIO
from .base import DummyInput, Input, PipeInput
class ContextManager(Protocol[_T_co]):
def __enter__(self) -> _T_co: ...
def __exit__(
self,
__exc_type: Optional[Type[BaseException]],
__exc_value: Optional[BaseException],
__traceback: Optional[TracebackType],
) -> Optional[bool]: ...
class PipeInput(Input):
"""
Abstraction for pipe input.
"""
def send_bytes(self, data: bytes) -> None:
"""Feed byte string into the pipe"""
def send_text(self, data: str) -> None:
"""Feed a text string into the pipe"""
class Win32PipeInput(_Win32InputBase, PipeInput):
"""
This is an input pipe that works on Windows.
Text or bytes can be feed into the pipe, and key strokes can be read from
the pipe. This is useful if we want to send the input programmatically into
the application. Mostly useful for unit testing.
Notice that even though it's Windows, we use vt100 escape sequences over
the pipe.
Usage::
input = Win32PipeInput()
input.send_text('inputdata')
"""
_id = 0
def __init__(self, _event: HANDLE) -> None:
super().__init__()
# Event (handle) for registering this input in the event loop.
# This event is set when there is data available to read from the pipe.
# Note: We use this approach instead of using a regular pipe, like
# returned from `os.pipe()`, because making such a regular pipe
# non-blocking is tricky and this works really well.
self._event = create_win32_event()
self._closed = False
# Parser for incoming keys.
self._buffer: list[KeyPress] = [] # Buffer to collect the Key objects.
self.vt100_parser = Vt100Parser(lambda key: self._buffer.append(key))
# Identifier for every PipeInput for the hash.
self.__class__._id += 1
self._id = self.__class__._id
def create(cls) -> Iterator[Win32PipeInput]:
event = create_win32_event()
try:
yield Win32PipeInput(_event=event)
finally:
windll.kernel32.CloseHandle(event)
def closed(self) -> bool:
return self._closed
def fileno(self) -> int:
"""
The windows pipe doesn't depend on the file handle.
"""
raise NotImplementedError
def handle(self) -> HANDLE:
"The handle used for registering this pipe in the event loop."
return self._event
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
return attach_win32_input(self, input_ready_callback)
def detach(self) -> ContextManager[None]:
"""
Return a context manager that makes sure that this input is not active
in the current event loop.
"""
return detach_win32_input(self)
def read_keys(self) -> list[KeyPress]:
"Read list of KeyPress."
# Return result.
result = self._buffer
self._buffer = []
# Reset event.
if not self._closed:
# (If closed, the event should not reset.)
windll.kernel32.ResetEvent(self._event)
return result
def flush_keys(self) -> list[KeyPress]:
"""
Flush pending keys and return them.
(Used for flushing the 'escape' key.)
"""
# Flush all pending keys. (This is most important to flush the vt100
# 'Escape' key early when nothing else follows.)
self.vt100_parser.flush()
# Return result.
result = self._buffer
self._buffer = []
return result
def send_bytes(self, data: bytes) -> None:
"Send bytes to the input."
self.send_text(data.decode("utf-8", "ignore"))
def send_text(self, text: str) -> None:
"Send text to the input."
if self._closed:
raise ValueError("Attempt to write into a closed pipe.")
# Pass it through our vt100 parser.
self.vt100_parser.feed(text)
# Set event.
windll.kernel32.SetEvent(self._event)
def raw_mode(self) -> ContextManager[None]:
return DummyContext()
def cooked_mode(self) -> ContextManager[None]:
return DummyContext()
def close(self) -> None:
"Close write-end of the pipe."
self._closed = True
windll.kernel32.SetEvent(self._event)
def typeahead_hash(self) -> str:
"""
This needs to be unique for every `PipeInput`.
"""
return f"pipe-input-{self._id}"
class PosixPipeInput(Vt100Input, PipeInput):
"""
Input that is send through a pipe.
This is useful if we want to send the input programmatically into the
application. Mostly useful for unit testing.
Usage::
with PosixPipeInput.create() as input:
input.send_text('inputdata')
"""
_id = 0
def __init__(self, _pipe: _Pipe, _text: str = "") -> None:
# Private constructor. Users should use the public `.create()` method.
self.pipe = _pipe
class Stdin:
encoding = "utf-8"
def isatty(stdin) -> bool:
return True
def fileno(stdin) -> int:
return self.pipe.read_fd
super().__init__(cast(TextIO, Stdin()))
self.send_text(_text)
# Identifier for every PipeInput for the hash.
self.__class__._id += 1
self._id = self.__class__._id
def create(cls, text: str = "") -> Iterator[PosixPipeInput]:
pipe = _Pipe()
try:
yield PosixPipeInput(_pipe=pipe, _text=text)
finally:
pipe.close()
def send_bytes(self, data: bytes) -> None:
os.write(self.pipe.write_fd, data)
def send_text(self, data: str) -> None:
"Send text to the input."
os.write(self.pipe.write_fd, data.encode("utf-8"))
def raw_mode(self) -> ContextManager[None]:
return DummyContext()
def cooked_mode(self) -> ContextManager[None]:
return DummyContext()
def close(self) -> None:
"Close pipe fds."
# Only close the write-end of the pipe. This will unblock the reader
# callback (in vt100.py > _attached_input), which eventually will raise
# `EOFError`. If we'd also close the read-end, then the event loop
# won't wake up the corresponding callback because of this.
self.pipe.close_write()
def typeahead_hash(self) -> str:
"""
This needs to be unique for every `PipeInput`.
"""
return f"pipe-input-{self._id}"
The provided code snippet includes necessary dependencies for implementing the `create_pipe_input` function. Write a Python function `def create_pipe_input() -> ContextManager[PipeInput]` to solve the following problem:
Create an input pipe. This is mostly useful for unit testing. Usage:: with create_pipe_input() as input: input.send_text('inputdata') Breaking change: In prompt_toolkit 3.0.28 and earlier, this was returning the `PipeInput` directly, rather than through a context manager.
Here is the function:
def create_pipe_input() -> ContextManager[PipeInput]:
"""
Create an input pipe.
This is mostly useful for unit testing.
Usage::
with create_pipe_input() as input:
input.send_text('inputdata')
Breaking change: In prompt_toolkit 3.0.28 and earlier, this was returning
the `PipeInput` directly, rather than through a context manager.
"""
if sys.platform == "win32":
from .win32_pipe import Win32PipeInput
return Win32PipeInput.create()
else:
from .posix_pipe import PosixPipeInput
return PosixPipeInput.create() | Create an input pipe. This is mostly useful for unit testing. Usage:: with create_pipe_input() as input: input.send_text('inputdata') Breaking change: In prompt_toolkit 3.0.28 and earlier, this was returning the `PipeInput` directly, rather than through a context manager. |
172,138 | from __future__ import annotations
from abc import ABCMeta, abstractmethod, abstractproperty
from contextlib import contextmanager
from typing import Callable, ContextManager, Generator, List
from prompt_toolkit.key_binding import KeyPress
class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
def __next__(self) -> _T_co: ...
def send(self, __value: _T_contra) -> _T_co: ...
def throw(
self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ...
) -> _T_co: ...
def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> _T_co: ...
def close(self) -> None: ...
def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ...
def gi_code(self) -> CodeType: ...
def gi_frame(self) -> FrameType: ...
def gi_running(self) -> bool: ...
def gi_yieldfrom(self) -> Optional[Generator[Any, Any, Any]]: ...
def _dummy_context_manager() -> Generator[None, None, None]:
yield | null |
172,139 | from __future__ import annotations
from collections import defaultdict
from typing import Dict, List
from ..key_binding import KeyPress
from .base import Input
_buffer: dict[str, list[KeyPress]] = defaultdict(list)
class Input(metaclass=ABCMeta):
"""
Abstraction for any input.
An instance of this class can be given to the constructor of a
:class:`~prompt_toolkit.application.Application` and will also be
passed to the :class:`~prompt_toolkit.eventloop.base.EventLoop`.
"""
def fileno(self) -> int:
"""
Fileno for putting this in an event loop.
"""
def typeahead_hash(self) -> str:
"""
Identifier for storing type ahead key presses.
"""
def read_keys(self) -> list[KeyPress]:
"""
Return a list of Key objects which are read/parsed from the input.
"""
def flush_keys(self) -> list[KeyPress]:
"""
Flush the underlying parser. and return the pending keys.
(Used for vt100 input.)
"""
return []
def flush(self) -> None:
"The event loop can call this when the input has to be flushed."
pass
def closed(self) -> bool:
"Should be true when the input stream is closed."
return False
def raw_mode(self) -> ContextManager[None]:
"""
Context manager that turns the input into raw mode.
"""
def cooked_mode(self) -> ContextManager[None]:
"""
Context manager that turns the input into cooked mode.
"""
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
def detach(self) -> ContextManager[None]:
"""
Return a context manager that makes sure that this input is not active
in the current event loop.
"""
def close(self) -> None:
"Close input."
pass
The provided code snippet includes necessary dependencies for implementing the `store_typeahead` function. Write a Python function `def store_typeahead(input_obj: Input, key_presses: list[KeyPress]) -> None` to solve the following problem:
Insert typeahead key presses for the given input.
Here is the function:
def store_typeahead(input_obj: Input, key_presses: list[KeyPress]) -> None:
"""
Insert typeahead key presses for the given input.
"""
global _buffer
key = input_obj.typeahead_hash()
_buffer[key].extend(key_presses) | Insert typeahead key presses for the given input. |
172,140 | from __future__ import annotations
from collections import defaultdict
from typing import Dict, List
from ..key_binding import KeyPress
from .base import Input
_buffer: dict[str, list[KeyPress]] = defaultdict(list)
class Input(metaclass=ABCMeta):
"""
Abstraction for any input.
An instance of this class can be given to the constructor of a
:class:`~prompt_toolkit.application.Application` and will also be
passed to the :class:`~prompt_toolkit.eventloop.base.EventLoop`.
"""
def fileno(self) -> int:
"""
Fileno for putting this in an event loop.
"""
def typeahead_hash(self) -> str:
"""
Identifier for storing type ahead key presses.
"""
def read_keys(self) -> list[KeyPress]:
"""
Return a list of Key objects which are read/parsed from the input.
"""
def flush_keys(self) -> list[KeyPress]:
"""
Flush the underlying parser. and return the pending keys.
(Used for vt100 input.)
"""
return []
def flush(self) -> None:
"The event loop can call this when the input has to be flushed."
pass
def closed(self) -> bool:
"Should be true when the input stream is closed."
return False
def raw_mode(self) -> ContextManager[None]:
"""
Context manager that turns the input into raw mode.
"""
def cooked_mode(self) -> ContextManager[None]:
"""
Context manager that turns the input into cooked mode.
"""
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
def detach(self) -> ContextManager[None]:
"""
Return a context manager that makes sure that this input is not active
in the current event loop.
"""
def close(self) -> None:
"Close input."
pass
The provided code snippet includes necessary dependencies for implementing the `get_typeahead` function. Write a Python function `def get_typeahead(input_obj: Input) -> list[KeyPress]` to solve the following problem:
Retrieve typeahead and reset the buffer for this input.
Here is the function:
def get_typeahead(input_obj: Input) -> list[KeyPress]:
"""
Retrieve typeahead and reset the buffer for this input.
"""
global _buffer
key = input_obj.typeahead_hash()
result = _buffer[key]
_buffer[key] = []
return result | Retrieve typeahead and reset the buffer for this input. |
172,141 | from __future__ import annotations
from collections import defaultdict
from typing import Dict, List
from ..key_binding import KeyPress
from .base import Input
_buffer: dict[str, list[KeyPress]] = defaultdict(list)
class Input(metaclass=ABCMeta):
"""
Abstraction for any input.
An instance of this class can be given to the constructor of a
:class:`~prompt_toolkit.application.Application` and will also be
passed to the :class:`~prompt_toolkit.eventloop.base.EventLoop`.
"""
def fileno(self) -> int:
"""
Fileno for putting this in an event loop.
"""
def typeahead_hash(self) -> str:
"""
Identifier for storing type ahead key presses.
"""
def read_keys(self) -> list[KeyPress]:
"""
Return a list of Key objects which are read/parsed from the input.
"""
def flush_keys(self) -> list[KeyPress]:
"""
Flush the underlying parser. and return the pending keys.
(Used for vt100 input.)
"""
return []
def flush(self) -> None:
"The event loop can call this when the input has to be flushed."
pass
def closed(self) -> bool:
"Should be true when the input stream is closed."
return False
def raw_mode(self) -> ContextManager[None]:
"""
Context manager that turns the input into raw mode.
"""
def cooked_mode(self) -> ContextManager[None]:
"""
Context manager that turns the input into cooked mode.
"""
def attach(self, input_ready_callback: Callable[[], None]) -> ContextManager[None]:
"""
Return a context manager that makes this input active in the current
event loop.
"""
def detach(self) -> ContextManager[None]:
"""
Return a context manager that makes sure that this input is not active
in the current event loop.
"""
def close(self) -> None:
"Close input."
pass
The provided code snippet includes necessary dependencies for implementing the `clear_typeahead` function. Write a Python function `def clear_typeahead(input_obj: Input) -> None` to solve the following problem:
Clear typeahead buffer.
Here is the function:
def clear_typeahead(input_obj: Input) -> None:
"""
Clear typeahead buffer.
"""
global _buffer
key = input_obj.typeahead_hash()
_buffer[key] = [] | Clear typeahead buffer. |
172,142 | from __future__ import annotations
from typing import Dict
from .base import Always, Filter, FilterOrBool, Never
def to_filter(bool_or_filter: FilterOrBool) -> Filter:
"""
Accept both booleans and Filters as input and
turn it into a Filter.
"""
if isinstance(bool_or_filter, bool):
return _bool_to_filter[bool_or_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)
FilterOrBool = Union[Filter, bool]
The provided code snippet includes necessary dependencies for implementing the `is_true` function. Write a Python function `def is_true(value: FilterOrBool) -> bool` to solve the following problem:
Test whether `value` is True. In case of a Filter, call it. :param value: Boolean or `Filter` instance.
Here is the function:
def is_true(value: FilterOrBool) -> bool:
"""
Test whether `value` is True. In case of a Filter, call it.
:param value: Boolean or `Filter` instance.
"""
return to_filter(value)() | Test whether `value` is True. In case of a Filter, call it. :param value: Boolean or `Filter` instance. |
172,143 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class Condition(Filter):
"""
Turn any callable into a Filter. The callable is supposed to not take any
arguments.
This can be used as a decorator::
def feature_is_active(): # `feature_is_active` becomes a Filter.
return True
:param func: Callable which takes no inputs and returns a boolean.
"""
def __init__(self, func: Callable[[], bool]) -> None:
super().__init__()
self.func = func
def __call__(self) -> bool:
return self.func()
def __repr__(self) -> str:
return "Condition(%r)" % self.func
FocusableElement = Union[str, Buffer, UIControl, AnyContainer]
class Buffer:
"""
The core data structure that holds the text and cursor position of the
current input line and implements all text manipulations on top of it. It
also implements the history, undo stack and the completion state.
:param completer: :class:`~prompt_toolkit.completion.Completer` instance.
:param history: :class:`~prompt_toolkit.history.History` instance.
:param tempfile_suffix: The tempfile suffix (extension) to be used for the
"open in editor" function. For a Python REPL, this would be ".py", so
that the editor knows the syntax highlighting to use. This can also be
a callable that returns a string.
:param tempfile: For more advanced tempfile situations where you need
control over the subdirectories and filename. For a Git Commit Message,
this would be ".git/COMMIT_EDITMSG", so that the editor knows the syntax
highlighting to use. This can also be a callable that returns a string.
:param name: Name for this buffer. E.g. DEFAULT_BUFFER. This is mostly
useful for key bindings where we sometimes prefer to refer to a buffer
by their name instead of by reference.
:param accept_handler: Called when the buffer input is accepted. (Usually
when the user presses `enter`.) The accept handler receives this
`Buffer` as input and should return True when the buffer text should be
kept instead of calling reset.
In case of a `PromptSession` for instance, we want to keep the text,
because we will exit the application, and only reset it during the next
run.
Events:
:param on_text_changed: When the buffer text changes. (Callable or None.)
:param on_text_insert: When new text is inserted. (Callable or None.)
:param on_cursor_position_changed: When the cursor moves. (Callable or None.)
:param on_completions_changed: When the completions were changed. (Callable or None.)
:param on_suggestion_set: When an auto-suggestion text has been set. (Callable or None.)
Filters:
:param complete_while_typing: :class:`~prompt_toolkit.filters.Filter`
or `bool`. Decide whether or not to do asynchronous autocompleting while
typing.
:param validate_while_typing: :class:`~prompt_toolkit.filters.Filter`
or `bool`. Decide whether or not to do asynchronous validation while
typing.
:param enable_history_search: :class:`~prompt_toolkit.filters.Filter` or
`bool` to indicate when up-arrow partial string matching is enabled. It
is advised to not enable this at the same time as
`complete_while_typing`, because when there is an autocompletion found,
the up arrows usually browse through the completions, rather than
through the history.
:param read_only: :class:`~prompt_toolkit.filters.Filter`. When True,
changes will not be allowed.
:param multiline: :class:`~prompt_toolkit.filters.Filter` or `bool`. When
not set, pressing `Enter` will call the `accept_handler`. Otherwise,
pressing `Esc-Enter` is required.
"""
def __init__(
self,
completer: Completer | None = None,
auto_suggest: AutoSuggest | None = None,
history: History | None = None,
validator: Validator | None = None,
tempfile_suffix: str | Callable[[], str] = "",
tempfile: str | Callable[[], str] = "",
name: str = "",
complete_while_typing: FilterOrBool = False,
validate_while_typing: FilterOrBool = False,
enable_history_search: FilterOrBool = False,
document: Document | None = None,
accept_handler: BufferAcceptHandler | None = None,
read_only: FilterOrBool = False,
multiline: FilterOrBool = True,
on_text_changed: BufferEventHandler | None = None,
on_text_insert: BufferEventHandler | None = None,
on_cursor_position_changed: BufferEventHandler | None = None,
on_completions_changed: BufferEventHandler | None = None,
on_suggestion_set: BufferEventHandler | None = None,
):
# Accept both filters and booleans as input.
enable_history_search = to_filter(enable_history_search)
complete_while_typing = to_filter(complete_while_typing)
validate_while_typing = to_filter(validate_while_typing)
read_only = to_filter(read_only)
multiline = to_filter(multiline)
self.completer = completer or DummyCompleter()
self.auto_suggest = auto_suggest
self.validator = validator
self.tempfile_suffix = tempfile_suffix
self.tempfile = tempfile
self.name = name
self.accept_handler = accept_handler
# Filters. (Usually, used by the key bindings to drive the buffer.)
self.complete_while_typing = complete_while_typing
self.validate_while_typing = validate_while_typing
self.enable_history_search = enable_history_search
self.read_only = read_only
self.multiline = multiline
# Text width. (For wrapping, used by the Vi 'gq' operator.)
self.text_width = 0
#: The command buffer history.
# Note that we shouldn't use a lazy 'or' here. bool(history) could be
# False when empty.
self.history = InMemoryHistory() if history is None else history
self.__cursor_position = 0
# Events
self.on_text_changed: Event[Buffer] = Event(self, on_text_changed)
self.on_text_insert: Event[Buffer] = Event(self, on_text_insert)
self.on_cursor_position_changed: Event[Buffer] = Event(
self, on_cursor_position_changed
)
self.on_completions_changed: Event[Buffer] = Event(self, on_completions_changed)
self.on_suggestion_set: Event[Buffer] = Event(self, on_suggestion_set)
# Document cache. (Avoid creating new Document instances.)
self._document_cache: FastDictCache[
tuple[str, int, SelectionState | None], Document
] = FastDictCache(Document, size=10)
# Create completer / auto suggestion / validation coroutines.
self._async_suggester = self._create_auto_suggest_coroutine()
self._async_completer = self._create_completer_coroutine()
self._async_validator = self._create_auto_validate_coroutine()
# Asyncio task for populating the history.
self._load_history_task: asyncio.Future[None] | None = None
# Reset other attributes.
self.reset(document=document)
def __repr__(self) -> str:
if len(self.text) < 15:
text = self.text
else:
text = self.text[:12] + "..."
return f"<Buffer(name={self.name!r}, text={text!r}) at {id(self)!r}>"
def reset(
self, document: Document | None = None, append_to_history: bool = False
) -> None:
"""
:param append_to_history: Append current input to history first.
"""
if append_to_history:
self.append_to_history()
document = document or Document()
self.__cursor_position = document.cursor_position
# `ValidationError` instance. (Will be set when the input is wrong.)
self.validation_error: ValidationError | None = None
self.validation_state: ValidationState | None = ValidationState.UNKNOWN
# State of the selection.
self.selection_state: SelectionState | None = None
# Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode,
# we can insert text on multiple lines at once. This is implemented by
# using multiple cursors.)
self.multiple_cursor_positions: list[int] = []
# When doing consecutive up/down movements, prefer to stay at this column.
self.preferred_column: int | None = None
# State of complete browser
# For interactive completion through Ctrl-N/Ctrl-P.
self.complete_state: CompletionState | None = None
# State of Emacs yank-nth-arg completion.
self.yank_nth_arg_state: YankNthArgState | None = None # for yank-nth-arg.
# Remember the document that we had *right before* the last paste
# operation. This is used for rotating through the kill ring.
self.document_before_paste: Document | None = None
# Current suggestion.
self.suggestion: Suggestion | None = None
# The history search text. (Used for filtering the history when we
# browse through it.)
self.history_search_text: str | None = None
# Undo/redo stacks (stack of `(text, cursor_position)`).
self._undo_stack: list[tuple[str, int]] = []
self._redo_stack: list[tuple[str, int]] = []
# Cancel history loader. If history loading was still ongoing.
# Cancel the `_load_history_task`, so that next repaint of the
# `BufferControl` we will repopulate it.
if self._load_history_task is not None:
self._load_history_task.cancel()
self._load_history_task = None
#: The working lines. Similar to history, except that this can be
#: modified. The user can press arrow_up and edit previous entries.
#: Ctrl-C should reset this, and copy the whole history back in here.
#: Enter should process the current command and append to the real
#: history.
self._working_lines: Deque[str] = deque([document.text])
self.__working_index = 0
def load_history_if_not_yet_loaded(self) -> None:
"""
Create task for populating the buffer history (if not yet done).
Note::
This needs to be called from within the event loop of the
application, because history loading is async, and we need to be
sure the right event loop is active. Therefor, we call this method
in the `BufferControl.create_content`.
There are situations where prompt_toolkit applications are created
in one thread, but will later run in a different thread (Ptpython
is one example. The REPL runs in a separate thread, in order to
prevent interfering with a potential different event loop in the
main thread. The REPL UI however is still created in the main
thread.) We could decide to not support creating prompt_toolkit
objects in one thread and running the application in a different
thread, but history loading is the only place where it matters, and
this solves it.
"""
if self._load_history_task is None:
async def load_history() -> None:
async for item in self.history.load():
self._working_lines.appendleft(item)
self.__working_index += 1
self._load_history_task = get_app().create_background_task(load_history())
def load_history_done(f: asyncio.Future[None]) -> None:
"""
Handle `load_history` result when either done, cancelled, or
when an exception was raised.
"""
try:
f.result()
except asyncio.CancelledError:
# Ignore cancellation. But handle it, so that we don't get
# this traceback.
pass
except GeneratorExit:
# Probably not needed, but we had situations where
# `GeneratorExit` was raised in `load_history` during
# cancellation.
pass
except BaseException:
# Log error if something goes wrong. (We don't have a
# caller to which we can propagate this exception.)
logger.exception("Loading history failed")
self._load_history_task.add_done_callback(load_history_done)
# <getters/setters>
def _set_text(self, value: str) -> bool:
"""set text at current working_index. Return whether it changed."""
working_index = self.working_index
working_lines = self._working_lines
original_value = working_lines[working_index]
working_lines[working_index] = value
# Return True when this text has been changed.
if len(value) != len(original_value):
# For Python 2, it seems that when two strings have a different
# length and one is a prefix of the other, Python still scans
# character by character to see whether the strings are different.
# (Some benchmarking showed significant differences for big
# documents. >100,000 of lines.)
return True
elif value != original_value:
return True
return False
def _set_cursor_position(self, value: int) -> bool:
"""Set cursor position. Return whether it changed."""
original_position = self.__cursor_position
self.__cursor_position = max(0, value)
return self.__cursor_position != original_position
def text(self) -> str:
return self._working_lines[self.working_index]
def text(self, value: str) -> None:
"""
Setting text. (When doing this, make sure that the cursor_position is
valid for this text. text/cursor_position should be consistent at any time,
otherwise set a Document instead.)
"""
# Ensure cursor position remains within the size of the text.
if self.cursor_position > len(value):
self.cursor_position = len(value)
# Don't allow editing of read-only buffers.
if self.read_only():
raise EditReadOnlyBuffer()
changed = self._set_text(value)
if changed:
self._text_changed()
# Reset history search text.
# (Note that this doesn't need to happen when working_index
# changes, which is when we traverse the history. That's why we
# don't do this in `self._text_changed`.)
self.history_search_text = None
def cursor_position(self) -> int:
return self.__cursor_position
def cursor_position(self, value: int) -> None:
"""
Setting cursor position.
"""
assert isinstance(value, int)
# Ensure cursor position is within the size of the text.
if value > len(self.text):
value = len(self.text)
if value < 0:
value = 0
changed = self._set_cursor_position(value)
if changed:
self._cursor_position_changed()
def working_index(self) -> int:
return self.__working_index
def working_index(self, value: int) -> None:
if self.__working_index != value:
self.__working_index = value
# Make sure to reset the cursor position, otherwise we end up in
# situations where the cursor position is out of the bounds of the
# text.
self.cursor_position = 0
self._text_changed()
def _text_changed(self) -> None:
# Remove any validation errors and complete state.
self.validation_error = None
self.validation_state = ValidationState.UNKNOWN
self.complete_state = None
self.yank_nth_arg_state = None
self.document_before_paste = None
self.selection_state = None
self.suggestion = None
self.preferred_column = None
# fire 'on_text_changed' event.
self.on_text_changed.fire()
# Input validation.
# (This happens on all change events, unlike auto completion, also when
# deleting text.)
if self.validator and self.validate_while_typing():
get_app().create_background_task(self._async_validator())
def _cursor_position_changed(self) -> None:
# Remove any complete state.
# (Input validation should only be undone when the cursor position
# changes.)
self.complete_state = None
self.yank_nth_arg_state = None
self.document_before_paste = None
# Unset preferred_column. (Will be set after the cursor movement, if
# required.)
self.preferred_column = None
# Note that the cursor position can change if we have a selection the
# new position of the cursor determines the end of the selection.
# fire 'on_cursor_position_changed' event.
self.on_cursor_position_changed.fire()
def document(self) -> Document:
"""
Return :class:`~prompt_toolkit.document.Document` instance from the
current text, cursor position and selection state.
"""
return self._document_cache[
self.text, self.cursor_position, self.selection_state
]
def document(self, value: Document) -> None:
"""
Set :class:`~prompt_toolkit.document.Document` instance.
This will set both the text and cursor position at the same time, but
atomically. (Change events will be triggered only after both have been set.)
"""
self.set_document(value)
def set_document(self, value: Document, bypass_readonly: bool = False) -> None:
"""
Set :class:`~prompt_toolkit.document.Document` instance. Like the
``document`` property, but accept an ``bypass_readonly`` argument.
:param bypass_readonly: When True, don't raise an
:class:`.EditReadOnlyBuffer` exception, even
when the buffer is read-only.
.. warning::
When this buffer is read-only and `bypass_readonly` was not passed,
the `EditReadOnlyBuffer` exception will be caught by the
`KeyProcessor` and is silently suppressed. This is important to
keep in mind when writing key bindings, because it won't do what
you expect, and there won't be a stack trace. Use try/finally
around this function if you need some cleanup code.
"""
# Don't allow editing of read-only buffers.
if not bypass_readonly and self.read_only():
raise EditReadOnlyBuffer()
# Set text and cursor position first.
text_changed = self._set_text(value.text)
cursor_position_changed = self._set_cursor_position(value.cursor_position)
# Now handle change events. (We do this when text/cursor position is
# both set and consistent.)
if text_changed:
self._text_changed()
self.history_search_text = None
if cursor_position_changed:
self._cursor_position_changed()
def is_returnable(self) -> bool:
"""
True when there is something handling accept.
"""
return bool(self.accept_handler)
# End of <getters/setters>
def save_to_undo_stack(self, clear_redo_stack: bool = True) -> None:
"""
Safe current state (input text and cursor position), so that we can
restore it by calling undo.
"""
# Safe if the text is different from the text at the top of the stack
# is different. If the text is the same, just update the cursor position.
if self._undo_stack and self._undo_stack[-1][0] == self.text:
self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position)
else:
self._undo_stack.append((self.text, self.cursor_position))
# Saving anything to the undo stack, clears the redo stack.
if clear_redo_stack:
self._redo_stack = []
def transform_lines(
self,
line_index_iterator: Iterable[int],
transform_callback: Callable[[str], str],
) -> str:
"""
Transforms the text on a range of lines.
When the iterator yield an index not in the range of lines that the
document contains, it skips them silently.
To uppercase some lines::
new_text = transform_lines(range(5,10), lambda text: text.upper())
:param line_index_iterator: Iterator of line numbers (int)
:param transform_callback: callable that takes the original text of a
line, and return the new text for this line.
:returns: The new text.
"""
# Split lines
lines = self.text.split("\n")
# Apply transformation
for index in line_index_iterator:
try:
lines[index] = transform_callback(lines[index])
except IndexError:
pass
return "\n".join(lines)
def transform_current_line(self, transform_callback: Callable[[str], str]) -> None:
"""
Apply the given transformation function to the current line.
:param transform_callback: callable that takes a string and return a new string.
"""
document = self.document
a = document.cursor_position + document.get_start_of_line_position()
b = document.cursor_position + document.get_end_of_line_position()
self.text = (
document.text[:a]
+ transform_callback(document.text[a:b])
+ document.text[b:]
)
def transform_region(
self, from_: int, to: int, transform_callback: Callable[[str], str]
) -> None:
"""
Transform a part of the input string.
:param from_: (int) start position.
:param to: (int) end position.
:param transform_callback: Callable which accepts a string and returns
the transformed string.
"""
assert from_ < to
self.text = "".join(
[
self.text[:from_]
+ transform_callback(self.text[from_:to])
+ self.text[to:]
]
)
def cursor_left(self, count: int = 1) -> None:
self.cursor_position += self.document.get_cursor_left_position(count=count)
def cursor_right(self, count: int = 1) -> None:
self.cursor_position += self.document.get_cursor_right_position(count=count)
def cursor_up(self, count: int = 1) -> None:
"""(for multiline edit). Move cursor to the previous line."""
original_column = self.preferred_column or self.document.cursor_position_col
self.cursor_position += self.document.get_cursor_up_position(
count=count, preferred_column=original_column
)
# Remember the original column for the next up/down movement.
self.preferred_column = original_column
def cursor_down(self, count: int = 1) -> None:
"""(for multiline edit). Move cursor to the next line."""
original_column = self.preferred_column or self.document.cursor_position_col
self.cursor_position += self.document.get_cursor_down_position(
count=count, preferred_column=original_column
)
# Remember the original column for the next up/down movement.
self.preferred_column = original_column
def auto_up(
self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False
) -> None:
"""
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
"""
if self.complete_state:
self.complete_previous(count=count)
elif self.document.cursor_position_row > 0:
self.cursor_up(count=count)
elif not self.selection_state:
self.history_backward(count=count)
# Go to the start of the line?
if go_to_start_of_line_if_history_changes:
self.cursor_position += self.document.get_start_of_line_position()
def auto_down(
self, count: int = 1, go_to_start_of_line_if_history_changes: bool = False
) -> None:
"""
If we're not on the last line (of a multiline input) go a line down,
otherwise go forward in history. (If nothing is selected.)
"""
if self.complete_state:
self.complete_next(count=count)
elif self.document.cursor_position_row < self.document.line_count - 1:
self.cursor_down(count=count)
elif not self.selection_state:
self.history_forward(count=count)
# Go to the start of the line?
if go_to_start_of_line_if_history_changes:
self.cursor_position += self.document.get_start_of_line_position()
def delete_before_cursor(self, count: int = 1) -> str:
"""
Delete specified number of characters before cursor and return the
deleted text.
"""
assert count >= 0
deleted = ""
if self.cursor_position > 0:
deleted = self.text[self.cursor_position - count : self.cursor_position]
new_text = (
self.text[: self.cursor_position - count]
+ self.text[self.cursor_position :]
)
new_cursor_position = self.cursor_position - len(deleted)
# Set new Document atomically.
self.document = Document(new_text, new_cursor_position)
return deleted
def delete(self, count: int = 1) -> str:
"""
Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = (
self.text[: self.cursor_position]
+ self.text[self.cursor_position + len(deleted) :]
)
return deleted
else:
return ""
def join_next_line(self, separator: str = " ") -> None:
"""
Join the next line to the current one by deleting the line ending after
the current line.
"""
if not self.document.on_last_line:
self.cursor_position += self.document.get_end_of_line_position()
self.delete()
# Remove spaces.
self.text = (
self.document.text_before_cursor
+ separator
+ self.document.text_after_cursor.lstrip(" ")
)
def join_selected_lines(self, separator: str = " ") -> None:
"""
Join the selected lines.
"""
assert self.selection_state
# Get lines.
from_, to = sorted(
[self.cursor_position, self.selection_state.original_cursor_position]
)
before = self.text[:from_]
lines = self.text[from_:to].splitlines()
after = self.text[to:]
# Replace leading spaces with just one space.
lines = [l.lstrip(" ") + separator for l in lines]
# Set new document.
self.document = Document(
text=before + "".join(lines) + after,
cursor_position=len(before + "".join(lines[:-1])) - 1,
)
def swap_characters_before_cursor(self) -> None:
"""
Swap the last two characters before the cursor.
"""
pos = self.cursor_position
if pos >= 2:
a = self.text[pos - 2]
b = self.text[pos - 1]
self.text = self.text[: pos - 2] + b + a + self.text[pos:]
def go_to_history(self, index: int) -> None:
"""
Go to this item in the history.
"""
if index < len(self._working_lines):
self.working_index = index
self.cursor_position = len(self.text)
def complete_next(self, count: int = 1, disable_wrap_around: bool = False) -> None:
"""
Browse to the next completions.
(Does nothing if there are no completion.)
"""
index: int | None
if self.complete_state:
completions_count = len(self.complete_state.completions)
if self.complete_state.complete_index is None:
index = 0
elif self.complete_state.complete_index == completions_count - 1:
index = None
if disable_wrap_around:
return
else:
index = min(
completions_count - 1, self.complete_state.complete_index + count
)
self.go_to_completion(index)
def complete_previous(
self, count: int = 1, disable_wrap_around: bool = False
) -> None:
"""
Browse to the previous completions.
(Does nothing if there are no completion.)
"""
index: int | None
if self.complete_state:
if self.complete_state.complete_index == 0:
index = None
if disable_wrap_around:
return
elif self.complete_state.complete_index is None:
index = len(self.complete_state.completions) - 1
else:
index = max(0, self.complete_state.complete_index - count)
self.go_to_completion(index)
def cancel_completion(self) -> None:
"""
Cancel completion, go back to the original text.
"""
if self.complete_state:
self.go_to_completion(None)
self.complete_state = None
def _set_completions(self, completions: list[Completion]) -> CompletionState:
"""
Start completions. (Generate list of completions and initialize.)
By default, no completion will be selected.
"""
self.complete_state = CompletionState(
original_document=self.document, completions=completions
)
# Trigger event. This should eventually invalidate the layout.
self.on_completions_changed.fire()
return self.complete_state
def start_history_lines_completion(self) -> None:
"""
Start a completion based on all the other lines in the document and the
history.
"""
found_completions: set[str] = set()
completions = []
# For every line of the whole history, find matches with the current line.
current_line = self.document.current_line_before_cursor.lstrip()
for i, string in enumerate(self._working_lines):
for j, l in enumerate(string.split("\n")):
l = l.strip()
if l and l.startswith(current_line):
# When a new line has been found.
if l not in found_completions:
found_completions.add(l)
# Create completion.
if i == self.working_index:
display_meta = "Current, line %s" % (j + 1)
else:
display_meta = f"History {i + 1}, line {j + 1}"
completions.append(
Completion(
text=l,
start_position=-len(current_line),
display_meta=display_meta,
)
)
self._set_completions(completions=completions[::-1])
self.go_to_completion(0)
def go_to_completion(self, index: int | None) -> None:
"""
Select a completion from the list of current completions.
"""
assert self.complete_state
# Set new completion
state = self.complete_state
state.go_to_index(index)
# Set text/cursor position
new_text, new_cursor_position = state.new_text_and_position()
self.document = Document(new_text, new_cursor_position)
# (changing text/cursor position will unset complete_state.)
self.complete_state = state
def apply_completion(self, completion: Completion) -> None:
"""
Insert a given completion.
"""
# If there was already a completion active, cancel that one.
if self.complete_state:
self.go_to_completion(None)
self.complete_state = None
# Insert text from the given completion.
self.delete_before_cursor(-completion.start_position)
self.insert_text(completion.text)
def _set_history_search(self) -> None:
"""
Set `history_search_text`.
(The text before the cursor will be used for filtering the history.)
"""
if self.enable_history_search():
if self.history_search_text is None:
self.history_search_text = self.document.text_before_cursor
else:
self.history_search_text = None
def _history_matches(self, i: int) -> bool:
"""
True when the current entry matches the history search.
(when we don't have history search, it's also True.)
"""
return self.history_search_text is None or self._working_lines[i].startswith(
self.history_search_text
)
def history_forward(self, count: int = 1) -> None:
"""
Move forwards through the history.
:param count: Amount of items to move forward.
"""
self._set_history_search()
# Go forward in history.
found_something = False
for i in range(self.working_index + 1, len(self._working_lines)):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we found an entry, move cursor to the end of the first line.
if found_something:
self.cursor_position = 0
self.cursor_position += self.document.get_end_of_line_position()
def history_backward(self, count: int = 1) -> None:
"""
Move backwards through history.
"""
self._set_history_search()
# Go back in history.
found_something = False
for i in range(self.working_index - 1, -1, -1):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we move to another entry, move cursor to the end of the line.
if found_something:
self.cursor_position = len(self.text)
def yank_nth_arg(self, n: int | None = None, _yank_last_arg: bool = False) -> None:
"""
Pick nth word from previous history entry (depending on current
`yank_nth_arg_state`) and insert it at current position. Rotate through
history if called repeatedly. If no `n` has been given, take the first
argument. (The second word.)
:param n: (None or int), The index of the word from the previous line
to take.
"""
assert n is None or isinstance(n, int)
history_strings = self.history.get_strings()
if not len(history_strings):
return
# Make sure we have a `YankNthArgState`.
if self.yank_nth_arg_state is None:
state = YankNthArgState(n=-1 if _yank_last_arg else 1)
else:
state = self.yank_nth_arg_state
if n is not None:
state.n = n
# Get new history position.
new_pos = state.history_position - 1
if -new_pos > len(history_strings):
new_pos = -1
# Take argument from line.
line = history_strings[new_pos]
words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)]
words = [w for w in words if w]
try:
word = words[state.n]
except IndexError:
word = ""
# Insert new argument.
if state.previous_inserted_word:
self.delete_before_cursor(len(state.previous_inserted_word))
self.insert_text(word)
# Save state again for next completion. (Note that the 'insert'
# operation from above clears `self.yank_nth_arg_state`.)
state.previous_inserted_word = word
state.history_position = new_pos
self.yank_nth_arg_state = state
def yank_last_arg(self, n: int | None = None) -> None:
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last
word by default.
"""
self.yank_nth_arg(n=n, _yank_last_arg=True)
def start_selection(
self, selection_type: SelectionType = SelectionType.CHARACTERS
) -> None:
"""
Take the current cursor position as the start of this selection.
"""
self.selection_state = SelectionState(self.cursor_position, selection_type)
def copy_selection(self, _cut: bool = False) -> ClipboardData:
"""
Copy selected text and return :class:`.ClipboardData` instance.
Notice that this doesn't store the copied data on the clipboard yet.
You can store it like this:
.. code:: python
data = buffer.copy_selection()
get_app().clipboard.set_data(data)
"""
new_document, clipboard_data = self.document.cut_selection()
if _cut:
self.document = new_document
self.selection_state = None
return clipboard_data
def cut_selection(self) -> ClipboardData:
"""
Delete selected text and return :class:`.ClipboardData` instance.
"""
return self.copy_selection(_cut=True)
def paste_clipboard_data(
self,
data: ClipboardData,
paste_mode: PasteMode = PasteMode.EMACS,
count: int = 1,
) -> None:
"""
Insert the data from the clipboard.
"""
assert isinstance(data, ClipboardData)
assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
original_document = self.document
self.document = self.document.paste_clipboard_data(
data, paste_mode=paste_mode, count=count
)
# Remember original document. This assignment should come at the end,
# because assigning to 'document' will erase it.
self.document_before_paste = original_document
def newline(self, copy_margin: bool = True) -> None:
"""
Insert a line ending at the current position.
"""
if copy_margin:
self.insert_text("\n" + self.document.leading_whitespace_in_current_line)
else:
self.insert_text("\n")
def insert_line_above(self, copy_margin: bool = True) -> None:
"""
Insert a new line above the current one.
"""
if copy_margin:
insert = self.document.leading_whitespace_in_current_line + "\n"
else:
insert = "\n"
self.cursor_position += self.document.get_start_of_line_position()
self.insert_text(insert)
self.cursor_position -= 1
def insert_line_below(self, copy_margin: bool = True) -> None:
"""
Insert a new line below the current one.
"""
if copy_margin:
insert = "\n" + self.document.leading_whitespace_in_current_line
else:
insert = "\n"
self.cursor_position += self.document.get_end_of_line_position()
self.insert_text(insert)
def insert_text(
self,
data: str,
overwrite: bool = False,
move_cursor: bool = True,
fire_event: bool = True,
) -> None:
"""
Insert characters at cursor position.
:param fire_event: Fire `on_text_insert` event. This is mainly used to
trigger autocompletion while typing.
"""
# Original text & cursor position.
otext = self.text
ocpos = self.cursor_position
# In insert/text mode.
if overwrite:
# Don't overwrite the newline itself. Just before the line ending,
# it should act like insert mode.
overwritten_text = otext[ocpos : ocpos + len(data)]
if "\n" in overwritten_text:
overwritten_text = overwritten_text[: overwritten_text.find("\n")]
text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text) :]
else:
text = otext[:ocpos] + data + otext[ocpos:]
if move_cursor:
cpos = self.cursor_position + len(data)
else:
cpos = self.cursor_position
# Set new document.
# (Set text and cursor position at the same time. Otherwise, setting
# the text will fire a change event before the cursor position has been
# set. It works better to have this atomic.)
self.document = Document(text, cpos)
# Fire 'on_text_insert' event.
if fire_event: # XXX: rename to `start_complete`.
self.on_text_insert.fire()
# Only complete when "complete_while_typing" is enabled.
if self.completer and self.complete_while_typing():
get_app().create_background_task(self._async_completer())
# Call auto_suggest.
if self.auto_suggest:
get_app().create_background_task(self._async_suggester())
def undo(self) -> None:
# Pop from the undo-stack until we find a text that if different from
# the current text. (The current logic of `save_to_undo_stack` will
# cause that the top of the undo stack is usually the same as the
# current text, so in that case we have to pop twice.)
while self._undo_stack:
text, pos = self._undo_stack.pop()
if text != self.text:
# Push current text to redo stack.
self._redo_stack.append((self.text, self.cursor_position))
# Set new text/cursor_position.
self.document = Document(text, cursor_position=pos)
break
def redo(self) -> None:
if self._redo_stack:
# Copy current state on undo stack.
self.save_to_undo_stack(clear_redo_stack=False)
# Pop state from redo stack.
text, pos = self._redo_stack.pop()
self.document = Document(text, cursor_position=pos)
def validate(self, set_cursor: bool = False) -> bool:
"""
Returns `True` if valid.
:param set_cursor: Set the cursor position, if an error was found.
"""
# Don't call the validator again, if it was already called for the
# current input.
if self.validation_state != ValidationState.UNKNOWN:
return self.validation_state == ValidationState.VALID
# Call validator.
if self.validator:
try:
self.validator.validate(self.document)
except ValidationError as e:
# Set cursor position (don't allow invalid values.)
if set_cursor:
self.cursor_position = min(
max(0, e.cursor_position), len(self.text)
)
self.validation_state = ValidationState.INVALID
self.validation_error = e
return False
# Handle validation result.
self.validation_state = ValidationState.VALID
self.validation_error = None
return True
async def _validate_async(self) -> None:
"""
Asynchronous version of `validate()`.
This one doesn't set the cursor position.
We have both variants, because a synchronous version is required.
Handling the ENTER key needs to be completely synchronous, otherwise
stuff like type-ahead is going to give very weird results. (People
could type input while the ENTER key is still processed.)
An asynchronous version is required if we have `validate_while_typing`
enabled.
"""
while True:
# Don't call the validator again, if it was already called for the
# current input.
if self.validation_state != ValidationState.UNKNOWN:
return
# Call validator.
error = None
document = self.document
if self.validator:
try:
await self.validator.validate_async(self.document)
except ValidationError as e:
error = e
# If the document changed during the validation, try again.
if self.document != document:
continue
# Handle validation result.
if error:
self.validation_state = ValidationState.INVALID
else:
self.validation_state = ValidationState.VALID
self.validation_error = error
get_app().invalidate() # Trigger redraw (display error).
def append_to_history(self) -> None:
"""
Append the current input to the history.
"""
# Save at the tail of the history. (But don't if the last entry the
# history is already the same.)
if self.text:
history_strings = self.history.get_strings()
if not len(history_strings) or history_strings[-1] != self.text:
self.history.append_string(self.text)
def _search(
self,
search_state: SearchState,
include_current_position: bool = False,
count: int = 1,
) -> tuple[int, int] | None:
"""
Execute search. Return (working_index, cursor_position) tuple when this
search is applied. Returns `None` when this text cannot be found.
"""
assert count > 0
text = search_state.text
direction = search_state.direction
ignore_case = search_state.ignore_case()
def search_once(
working_index: int, document: Document
) -> tuple[int, Document] | None:
"""
Do search one time.
Return (working_index, document) or `None`
"""
if direction == SearchDirection.FORWARD:
# Try find at the current input.
new_index = document.find(
text,
include_current_position=include_current_position,
ignore_case=ignore_case,
)
if new_index is not None:
return (
working_index,
Document(document.text, document.cursor_position + new_index),
)
else:
# No match, go forward in the history. (Include len+1 to wrap around.)
# (Here we should always include all cursor positions, because
# it's a different line.)
for i in range(working_index + 1, len(self._working_lines) + 1):
i %= len(self._working_lines)
document = Document(self._working_lines[i], 0)
new_index = document.find(
text, include_current_position=True, ignore_case=ignore_case
)
if new_index is not None:
return (i, Document(document.text, new_index))
else:
# Try find at the current input.
new_index = document.find_backwards(text, ignore_case=ignore_case)
if new_index is not None:
return (
working_index,
Document(document.text, document.cursor_position + new_index),
)
else:
# No match, go back in the history. (Include -1 to wrap around.)
for i in range(working_index - 1, -2, -1):
i %= len(self._working_lines)
document = Document(
self._working_lines[i], len(self._working_lines[i])
)
new_index = document.find_backwards(
text, ignore_case=ignore_case
)
if new_index is not None:
return (
i,
Document(document.text, len(document.text) + new_index),
)
return None
# Do 'count' search iterations.
working_index = self.working_index
document = self.document
for _ in range(count):
result = search_once(working_index, document)
if result is None:
return None # Nothing found.
else:
working_index, document = result
return (working_index, document.cursor_position)
def document_for_search(self, search_state: SearchState) -> Document:
"""
Return a :class:`~prompt_toolkit.document.Document` instance that has
the text/cursor position for this search, if we would apply it. This
will be used in the
:class:`~prompt_toolkit.layout.BufferControl` to display feedback while
searching.
"""
search_result = self._search(search_state, include_current_position=True)
if search_result is None:
return self.document
else:
working_index, cursor_position = search_result
# Keep selection, when `working_index` was not changed.
if working_index == self.working_index:
selection = self.selection_state
else:
selection = None
return Document(
self._working_lines[working_index], cursor_position, selection=selection
)
def get_search_position(
self,
search_state: SearchState,
include_current_position: bool = True,
count: int = 1,
) -> int:
"""
Get the cursor position for this search.
(This operation won't change the `working_index`. It's won't go through
the history. Vi text objects can't span multiple items.)
"""
search_result = self._search(
search_state, include_current_position=include_current_position, count=count
)
if search_result is None:
return self.cursor_position
else:
working_index, cursor_position = search_result
return cursor_position
def apply_search(
self,
search_state: SearchState,
include_current_position: bool = True,
count: int = 1,
) -> None:
"""
Apply search. If something is found, set `working_index` and
`cursor_position`.
"""
search_result = self._search(
search_state, include_current_position=include_current_position, count=count
)
if search_result is not None:
working_index, cursor_position = search_result
self.working_index = working_index
self.cursor_position = cursor_position
def exit_selection(self) -> None:
self.selection_state = None
def _editor_simple_tempfile(self) -> tuple[str, Callable[[], None]]:
"""
Simple (file) tempfile implementation.
Return (tempfile, cleanup_func).
"""
suffix = to_str(self.tempfile_suffix)
descriptor, filename = tempfile.mkstemp(suffix)
os.write(descriptor, self.text.encode("utf-8"))
os.close(descriptor)
def cleanup() -> None:
os.unlink(filename)
return filename, cleanup
def _editor_complex_tempfile(self) -> tuple[str, Callable[[], None]]:
# Complex (directory) tempfile implementation.
headtail = to_str(self.tempfile)
if not headtail:
# Revert to simple case.
return self._editor_simple_tempfile()
headtail = str(headtail)
# Try to make according to tempfile logic.
head, tail = os.path.split(headtail)
if os.path.isabs(head):
head = head[1:]
dirpath = tempfile.mkdtemp()
if head:
dirpath = os.path.join(dirpath, head)
# Assume there is no issue creating dirs in this temp dir.
os.makedirs(dirpath)
# Open the filename and write current text.
filename = os.path.join(dirpath, tail)
with open(filename, "w", encoding="utf-8") as fh:
fh.write(self.text)
def cleanup() -> None:
shutil.rmtree(dirpath)
return filename, cleanup
def open_in_editor(self, validate_and_handle: bool = False) -> asyncio.Task[None]:
"""
Open code in editor.
This returns a future, and runs in a thread executor.
"""
if self.read_only():
raise EditReadOnlyBuffer()
# Write current text to temporary file
if self.tempfile:
filename, cleanup_func = self._editor_complex_tempfile()
else:
filename, cleanup_func = self._editor_simple_tempfile()
async def run() -> None:
try:
# Open in editor
# (We need to use `run_in_terminal`, because not all editors go to
# the alternate screen buffer, and some could influence the cursor
# position.)
succes = await run_in_terminal(
lambda: self._open_file_in_editor(filename), in_executor=True
)
# Read content again.
if succes:
with open(filename, "rb") as f:
text = f.read().decode("utf-8")
# Drop trailing newline. (Editors are supposed to add it at the
# end, but we don't need it.)
if text.endswith("\n"):
text = text[:-1]
self.document = Document(text=text, cursor_position=len(text))
# Accept the input.
if validate_and_handle:
self.validate_and_handle()
finally:
# Clean up temp dir/file.
cleanup_func()
return get_app().create_background_task(run())
def _open_file_in_editor(self, filename: str) -> bool:
"""
Call editor executable.
Return True when we received a zero return code.
"""
# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
# Otherwise, fall back to the first available editor that we can find.
visual = os.environ.get("VISUAL")
editor = os.environ.get("EDITOR")
editors = [
visual,
editor,
# Order of preference.
"/usr/bin/editor",
"/usr/bin/nano",
"/usr/bin/pico",
"/usr/bin/vi",
"/usr/bin/emacs",
]
for e in editors:
if e:
try:
# Use 'shlex.split()', because $VISUAL can contain spaces
# and quotes.
returncode = subprocess.call(shlex.split(e) + [filename])
return returncode == 0
except OSError:
# Executable does not exist, try the next one.
pass
return False
def start_completion(
self,
select_first: bool = False,
select_last: bool = False,
insert_common_part: bool = False,
complete_event: CompleteEvent | None = None,
) -> None:
"""
Start asynchronous autocompletion of this buffer.
(This will do nothing if a previous completion was still in progress.)
"""
# Only one of these options can be selected.
assert select_first + select_last + insert_common_part <= 1
get_app().create_background_task(
self._async_completer(
select_first=select_first,
select_last=select_last,
insert_common_part=insert_common_part,
complete_event=complete_event
or CompleteEvent(completion_requested=True),
)
)
def _create_completer_coroutine(self) -> Callable[..., Coroutine[Any, Any, None]]:
"""
Create function for asynchronous autocompletion.
(This consumes the asynchronous completer generator, which possibly
runs the completion algorithm in another thread.)
"""
def completion_does_nothing(document: Document, completion: Completion) -> bool:
"""
Return `True` if applying this completion doesn't have any effect.
(When it doesn't insert any new text.
"""
text_before_cursor = document.text_before_cursor
replaced_text = text_before_cursor[
len(text_before_cursor) + completion.start_position :
]
return replaced_text == completion.text
async def async_completer(
select_first: bool = False,
select_last: bool = False,
insert_common_part: bool = False,
complete_event: CompleteEvent | None = None,
) -> None:
document = self.document
complete_event = complete_event or CompleteEvent(text_inserted=True)
# Don't complete when we already have completions.
if self.complete_state or not self.completer:
return
# Create an empty CompletionState.
complete_state = CompletionState(original_document=self.document)
self.complete_state = complete_state
def proceed() -> bool:
"""Keep retrieving completions. Input text has not yet changed
while generating completions."""
return self.complete_state == complete_state
refresh_needed = asyncio.Event()
async def refresh_while_loading() -> None:
"""Background loop to refresh the UI at most 3 times a second
while the completion are loading. Calling
`on_completions_changed.fire()` for every completion that we
receive is too expensive when there are many completions. (We
could tune `Application.max_render_postpone_time` and
`Application.min_redraw_interval`, but having this here is a
better approach.)
"""
while True:
self.on_completions_changed.fire()
refresh_needed.clear()
await asyncio.sleep(0.3)
await refresh_needed.wait()
refresh_task = asyncio.ensure_future(refresh_while_loading())
try:
# Load.
async with aclosing(
self.completer.get_completions_async(document, complete_event)
) as async_generator:
async for completion in async_generator:
complete_state.completions.append(completion)
refresh_needed.set()
# If the input text changes, abort.
if not proceed():
break
finally:
refresh_task.cancel()
# Refresh one final time after we got everything.
self.on_completions_changed.fire()
completions = complete_state.completions
# When there is only one completion, which has nothing to add, ignore it.
if len(completions) == 1 and completion_does_nothing(
document, completions[0]
):
del completions[:]
# Set completions if the text was not yet changed.
if proceed():
# When no completions were found, or when the user selected
# already a completion by using the arrow keys, don't do anything.
if (
not self.complete_state
or self.complete_state.complete_index is not None
):
return
# When there are no completions, reset completion state anyway.
if not completions:
self.complete_state = None
# Render the ui if the completion menu was shown
# it is needed especially if there is one completion and it was deleted.
self.on_completions_changed.fire()
return
# Select first/last or insert common part, depending on the key
# binding. (For this we have to wait until all completions are
# loaded.)
if select_first:
self.go_to_completion(0)
elif select_last:
self.go_to_completion(len(completions) - 1)
elif insert_common_part:
common_part = get_common_complete_suffix(document, completions)
if common_part:
# Insert the common part, update completions.
self.insert_text(common_part)
if len(completions) > 1:
# (Don't call `async_completer` again, but
# recalculate completions. See:
# https://github.com/ipython/ipython/issues/9658)
completions[:] = [
c.new_completion_from_position(len(common_part))
for c in completions
]
self._set_completions(completions=completions)
else:
self.complete_state = None
else:
# When we were asked to insert the "common"
# prefix, but there was no common suffix but
# still exactly one match, then select the
# first. (It could be that we have a completion
# which does * expansion, like '*.py', with
# exactly one match.)
if len(completions) == 1:
self.go_to_completion(0)
else:
# If the last operation was an insert, (not a delete), restart
# the completion coroutine.
if self.document.text_before_cursor == document.text_before_cursor:
return # Nothing changed.
if self.document.text_before_cursor.startswith(
document.text_before_cursor
):
raise _Retry
return async_completer
def _create_auto_suggest_coroutine(self) -> Callable[[], Coroutine[Any, Any, None]]:
"""
Create function for asynchronous auto suggestion.
(This can be in another thread.)
"""
async def async_suggestor() -> None:
document = self.document
# Don't suggest when we already have a suggestion.
if self.suggestion or not self.auto_suggest:
return
suggestion = await self.auto_suggest.get_suggestion_async(self, document)
# Set suggestion only if the text was not yet changed.
if self.document == document:
# Set suggestion and redraw interface.
self.suggestion = suggestion
self.on_suggestion_set.fire()
else:
# Otherwise, restart thread.
raise _Retry
return async_suggestor
def _create_auto_validate_coroutine(
self,
) -> Callable[[], Coroutine[Any, Any, None]]:
"""
Create a function for asynchronous validation while typing.
(This can be in another thread.)
"""
async def async_validator() -> None:
await self._validate_async()
return async_validator
def validate_and_handle(self) -> None:
"""
Validate buffer and handle the accept action.
"""
valid = self.validate(set_cursor=True)
# When the validation succeeded, accept the input.
if valid:
if self.accept_handler:
keep_text = self.accept_handler(self)
else:
keep_text = False
self.append_to_history()
if not keep_text:
self.reset()
class Container(metaclass=ABCMeta):
"""
Base class for user interface layout.
"""
def reset(self) -> None:
"""
Reset the state of this container and all the children.
(E.g. reset scroll offsets, etc...)
"""
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
desired width for this container.
"""
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
desired height for this container.
"""
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: int | None,
) -> None:
"""
Write the actual content to the screen.
:param screen: :class:`~prompt_toolkit.layout.screen.Screen`
:param mouse_handlers: :class:`~prompt_toolkit.layout.mouse_handlers.MouseHandlers`.
:param parent_style: Style string to pass to the :class:`.Window`
object. This will be applied to all content of the windows.
:class:`.VSplit` and :class:`.HSplit` can use it to pass their
style down to the windows that they contain.
:param z_index: Used for propagating z_index from parent to child.
"""
def is_modal(self) -> bool:
"""
When this container is modal, key bindings from parent containers are
not taken into account if a user control in this container is focused.
"""
return False
def get_key_bindings(self) -> KeyBindingsBase | None:
"""
Returns a :class:`.KeyBindings` object. These bindings become active when any
user control in this container has the focus, except if any containers
between this container and the focused user control is modal.
"""
return None
def get_children(self) -> list[Container]:
"""
Return the list of child :class:`.Container` objects.
"""
return []
class Window(Container):
"""
Container that holds a control.
:param content: :class:`.UIControl` instance.
:param width: :class:`.Dimension` instance or callable.
:param height: :class:`.Dimension` instance or callable.
:param z_index: When specified, this can be used to bring element in front
of floating elements.
:param dont_extend_width: When `True`, don't take up more width then the
preferred width reported by the control.
:param dont_extend_height: When `True`, don't take up more width then the
preferred height reported by the control.
:param ignore_content_width: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` width when calculating the dimensions.
:param ignore_content_height: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` height when calculating the dimensions.
:param left_margins: A list of :class:`.Margin` instance to be displayed on
the left. For instance: :class:`~prompt_toolkit.layout.NumberedMargin`
can be one of them in order to show line numbers.
:param right_margins: Like `left_margins`, but on the other side.
:param scroll_offsets: :class:`.ScrollOffsets` instance, representing the
preferred amount of lines/columns to be always visible before/after the
cursor. When both top and bottom are a very high number, the cursor
will be centered vertically most of the time.
:param allow_scroll_beyond_bottom: A `bool` or
:class:`.Filter` instance. When True, allow scrolling so far, that the
top part of the content is not visible anymore, while there is still
empty space available at the bottom of the window. In the Vi editor for
instance, this is possible. You will see tildes while the top part of
the body is hidden.
:param wrap_lines: A `bool` or :class:`.Filter` instance. When True, don't
scroll horizontally, but wrap lines instead.
:param get_vertical_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
(When this is `None`, the scroll is only determined by the last and
current cursor position.)
:param get_horizontal_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
:param always_hide_cursor: A `bool` or
:class:`.Filter` instance. When True, never display the cursor, even
when the user control specifies a cursor position.
:param cursorline: A `bool` or :class:`.Filter` instance. When True,
display a cursorline.
:param cursorcolumn: A `bool` or :class:`.Filter` instance. When True,
display a cursorcolumn.
:param colorcolumns: A list of :class:`.ColorColumn` instances that
describe the columns to be highlighted, or a callable that returns such
a list.
:param align: :class:`.WindowAlign` value or callable that returns an
:class:`.WindowAlign` value. alignment of content.
:param style: A style string. Style to be applied to all the cells in this
window. (This can be a callable that returns a string.)
:param char: (string) Character to be used for filling the background. This
can also be a callable that returns a character.
:param get_line_prefix: None or a callable that returns formatted text to
be inserted before a line. It takes a line number (int) and a
wrap_count and returns formatted text. This can be used for
implementation of line continuations, things like Vim "breakindent" and
so on.
"""
def __init__(
self,
content: UIControl | None = None,
width: AnyDimension = None,
height: AnyDimension = None,
z_index: int | None = None,
dont_extend_width: FilterOrBool = False,
dont_extend_height: FilterOrBool = False,
ignore_content_width: FilterOrBool = False,
ignore_content_height: FilterOrBool = False,
left_margins: Sequence[Margin] | None = None,
right_margins: Sequence[Margin] | None = None,
scroll_offsets: ScrollOffsets | None = None,
allow_scroll_beyond_bottom: FilterOrBool = False,
wrap_lines: FilterOrBool = False,
get_vertical_scroll: Callable[[Window], int] | None = None,
get_horizontal_scroll: Callable[[Window], int] | None = None,
always_hide_cursor: FilterOrBool = False,
cursorline: FilterOrBool = False,
cursorcolumn: FilterOrBool = False,
colorcolumns: (
None | list[ColorColumn] | Callable[[], list[ColorColumn]]
) = None,
align: WindowAlign | Callable[[], WindowAlign] = WindowAlign.LEFT,
style: str | Callable[[], str] = "",
char: None | str | Callable[[], str] = None,
get_line_prefix: GetLinePrefixCallable | None = None,
) -> None:
self.allow_scroll_beyond_bottom = to_filter(allow_scroll_beyond_bottom)
self.always_hide_cursor = to_filter(always_hide_cursor)
self.wrap_lines = to_filter(wrap_lines)
self.cursorline = to_filter(cursorline)
self.cursorcolumn = to_filter(cursorcolumn)
self.content = content or DummyControl()
self.dont_extend_width = to_filter(dont_extend_width)
self.dont_extend_height = to_filter(dont_extend_height)
self.ignore_content_width = to_filter(ignore_content_width)
self.ignore_content_height = to_filter(ignore_content_height)
self.left_margins = left_margins or []
self.right_margins = right_margins or []
self.scroll_offsets = scroll_offsets or ScrollOffsets()
self.get_vertical_scroll = get_vertical_scroll
self.get_horizontal_scroll = get_horizontal_scroll
self.colorcolumns = colorcolumns or []
self.align = align
self.style = style
self.char = char
self.get_line_prefix = get_line_prefix
self.width = width
self.height = height
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._margin_width_cache: SimpleCache[tuple[Margin, int], int] = SimpleCache(
maxsize=1
)
self.reset()
def __repr__(self) -> str:
return "Window(content=%r)" % self.content
def reset(self) -> None:
self.content.reset()
#: Scrolling position of the main content.
self.vertical_scroll = 0
self.horizontal_scroll = 0
# Vertical scroll 2: this is the vertical offset that a line is
# scrolled if a single line (the one that contains the cursor) consumes
# all of the vertical space.
self.vertical_scroll_2 = 0
#: Keep render information (mappings between buffer input and render
#: output.)
self.render_info: WindowRenderInfo | None = None
def _get_margin_width(self, margin: Margin) -> int:
"""
Return the width for this margin.
(Calculate only once per render time.)
"""
# Margin.get_width, needs to have a UIContent instance.
def get_ui_content() -> UIContent:
return self._get_ui_content(width=0, height=0)
def get_width() -> int:
return margin.get_width(get_ui_content)
key = (margin, get_app().render_counter)
return self._margin_width_cache.get(key, get_width)
def _get_total_margin_width(self) -> int:
"""
Calculate and return the width of the margin (left + right).
"""
return sum(self._get_margin_width(m) for m in self.left_margins) + sum(
self._get_margin_width(m) for m in self.right_margins
)
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Calculate the preferred width for this window.
"""
def preferred_content_width() -> int | None:
"""Content width: is only calculated if no exact width for the
window was given."""
if self.ignore_content_width():
return None
# Calculate the width of the margin.
total_margin_width = self._get_total_margin_width()
# Window of the content. (Can be `None`.)
preferred_width = self.content.preferred_width(
max_available_width - total_margin_width
)
if preferred_width is not None:
# Include width of the margins.
preferred_width += total_margin_width
return preferred_width
# Merge.
return self._merge_dimensions(
dimension=to_dimension(self.width),
get_preferred=preferred_content_width,
dont_extend=self.dont_extend_width(),
)
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Calculate the preferred height for this window.
"""
def preferred_content_height() -> int | None:
"""Content height: is only calculated if no exact height for the
window was given."""
if self.ignore_content_height():
return None
total_margin_width = self._get_total_margin_width()
wrap_lines = self.wrap_lines()
return self.content.preferred_height(
width - total_margin_width,
max_available_height,
wrap_lines,
self.get_line_prefix,
)
return self._merge_dimensions(
dimension=to_dimension(self.height),
get_preferred=preferred_content_height,
dont_extend=self.dont_extend_height(),
)
def _merge_dimensions(
dimension: Dimension | None,
get_preferred: Callable[[], int | None],
dont_extend: bool = False,
) -> Dimension:
"""
Take the Dimension from this `Window` class and the received preferred
size from the `UIControl` and return a `Dimension` to report to the
parent container.
"""
dimension = dimension or Dimension()
# When a preferred dimension was explicitly given to the Window,
# ignore the UIControl.
preferred: int | None
if dimension.preferred_specified:
preferred = dimension.preferred
else:
# Otherwise, calculate the preferred dimension from the UI control
# content.
preferred = get_preferred()
# When a 'preferred' dimension is given by the UIControl, make sure
# that it stays within the bounds of the Window.
if preferred is not None:
if dimension.max_specified:
preferred = min(preferred, dimension.max)
if dimension.min_specified:
preferred = max(preferred, dimension.min)
# When a `dont_extend` flag has been given, use the preferred dimension
# also as the max dimension.
max_: int | None
min_: int | None
if dont_extend and preferred is not None:
max_ = min(dimension.max, preferred)
else:
max_ = dimension.max if dimension.max_specified else None
min_ = dimension.min if dimension.min_specified else None
return Dimension(
min=min_, max=max_, preferred=preferred, weight=dimension.weight
)
def _get_ui_content(self, width: int, height: int) -> UIContent:
"""
Create a `UIContent` instance.
"""
def get_content() -> UIContent:
return self.content.create_content(width=width, height=height)
key = (get_app().render_counter, width, height)
return self._ui_content_cache.get(key, get_content)
def _get_digraph_char(self) -> str | None:
"Return `False`, or the Digraph symbol to be used."
app = get_app()
if app.quoted_insert:
return "^"
if app.vi_state.waiting_for_digraph:
if app.vi_state.digraph_symbol1:
return app.vi_state.digraph_symbol1
return "?"
return None
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: int | None,
) -> None:
"""
Write window to screen. This renders the user control, the margins and
copies everything over to the absolute position at the given screen.
"""
# If dont_extend_width/height was given. Then reduce width/height in
# WritePosition if the parent wanted us to paint in a bigger area.
# (This happens if this window is bundled with another window in a
# HSplit/VSplit, but with different size requirements.)
write_position = WritePosition(
xpos=write_position.xpos,
ypos=write_position.ypos,
width=write_position.width,
height=write_position.height,
)
if self.dont_extend_width():
write_position.width = min(
write_position.width,
self.preferred_width(write_position.width).preferred,
)
if self.dont_extend_height():
write_position.height = min(
write_position.height,
self.preferred_height(
write_position.width, write_position.height
).preferred,
)
# Draw
z_index = z_index if self.z_index is None else self.z_index
draw_func = partial(
self._write_to_screen_at_index,
screen,
mouse_handlers,
write_position,
parent_style,
erase_bg,
)
if z_index is None or z_index <= 0:
# When no z_index is given, draw right away.
draw_func()
else:
# Otherwise, postpone.
screen.draw_with_z_index(z_index=z_index, draw_func=draw_func)
def _write_to_screen_at_index(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
) -> None:
# Don't bother writing invisible windows.
# (We save some time, but also avoid applying last-line styling.)
if write_position.height <= 0 or write_position.width <= 0:
return
# Calculate margin sizes.
left_margin_widths = [self._get_margin_width(m) for m in self.left_margins]
right_margin_widths = [self._get_margin_width(m) for m in self.right_margins]
total_margin_width = sum(left_margin_widths + right_margin_widths)
# Render UserControl.
ui_content = self.content.create_content(
write_position.width - total_margin_width, write_position.height
)
assert isinstance(ui_content, UIContent)
# Scroll content.
wrap_lines = self.wrap_lines()
self._scroll(
ui_content, write_position.width - total_margin_width, write_position.height
)
# Erase background and fill with `char`.
self._fill_bg(screen, write_position, erase_bg)
# Resolve `align` attribute.
align = self.align() if callable(self.align) else self.align
# Write body
visible_line_to_row_col, rowcol_to_yx = self._copy_body(
ui_content,
screen,
write_position,
sum(left_margin_widths),
write_position.width - total_margin_width,
self.vertical_scroll,
self.horizontal_scroll,
wrap_lines=wrap_lines,
highlight_lines=True,
vertical_scroll_2=self.vertical_scroll_2,
always_hide_cursor=self.always_hide_cursor(),
has_focus=get_app().layout.current_control == self.content,
align=align,
get_line_prefix=self.get_line_prefix,
)
# Remember render info. (Set before generating the margins. They need this.)
x_offset = write_position.xpos + sum(left_margin_widths)
y_offset = write_position.ypos
render_info = WindowRenderInfo(
window=self,
ui_content=ui_content,
horizontal_scroll=self.horizontal_scroll,
vertical_scroll=self.vertical_scroll,
window_width=write_position.width - total_margin_width,
window_height=write_position.height,
configured_scroll_offsets=self.scroll_offsets,
visible_line_to_row_col=visible_line_to_row_col,
rowcol_to_yx=rowcol_to_yx,
x_offset=x_offset,
y_offset=y_offset,
wrap_lines=wrap_lines,
)
self.render_info = render_info
# Set mouse handlers.
def mouse_handler(mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Wrapper around the mouse_handler of the `UIControl` that turns
screen coordinates into line coordinates.
Returns `NotImplemented` if no UI invalidation should be done.
"""
# Don't handle mouse events outside of the current modal part of
# the UI.
if self not in get_app().layout.walk_through_modal_area():
return NotImplemented
# Find row/col position first.
yx_to_rowcol = {v: k for k, v in rowcol_to_yx.items()}
y = mouse_event.position.y
x = mouse_event.position.x
# If clicked below the content area, look for a position in the
# last line instead.
max_y = write_position.ypos + len(visible_line_to_row_col) - 1
y = min(max_y, y)
result: NotImplementedOrNone
while x >= 0:
try:
row, col = yx_to_rowcol[y, x]
except KeyError:
# Try again. (When clicking on the right side of double
# width characters, or on the right side of the input.)
x -= 1
else:
# Found position, call handler of UIControl.
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=col, y=row),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
break
else:
# nobreak.
# (No x/y coordinate found for the content. This happens in
# case of a DummyControl, that does not have any content.
# Report (0,0) instead.)
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=0, y=0),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
# If it returns NotImplemented, handle it here.
if result == NotImplemented:
result = self._mouse_handler(mouse_event)
return result
mouse_handlers.set_mouse_handler_for_range(
x_min=write_position.xpos + sum(left_margin_widths),
x_max=write_position.xpos + write_position.width - total_margin_width,
y_min=write_position.ypos,
y_max=write_position.ypos + write_position.height,
handler=mouse_handler,
)
# Render and copy margins.
move_x = 0
def render_margin(m: Margin, width: int) -> UIContent:
"Render margin. Return `Screen`."
# Retrieve margin fragments.
fragments = m.create_margin(render_info, width, write_position.height)
# Turn it into a UIContent object.
# already rendered those fragments using this size.)
return FormattedTextControl(fragments).create_content(
width + 1, write_position.height
)
for m, width in zip(self.left_margins, left_margin_widths):
if width > 0: # (ConditionalMargin returns a zero width. -- Don't render.)
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
move_x = write_position.width - sum(right_margin_widths)
for m, width in zip(self.right_margins, right_margin_widths):
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
# Apply 'self.style'
self._apply_style(screen, write_position, parent_style)
# Tell the screen that this user control has been painted at this
# position.
screen.visible_windows_to_write_positions[self] = write_position
def _copy_body(
self,
ui_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
vertical_scroll: int = 0,
horizontal_scroll: int = 0,
wrap_lines: bool = False,
highlight_lines: bool = False,
vertical_scroll_2: int = 0,
always_hide_cursor: bool = False,
has_focus: bool = False,
align: WindowAlign = WindowAlign.LEFT,
get_line_prefix: Callable[[int, int], AnyFormattedText] | None = None,
) -> tuple[dict[int, tuple[int, int]], dict[tuple[int, int], tuple[int, int]]]:
"""
Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple.
:param get_line_prefix: None or a callable that takes a line number
(int) and a wrap_count (int) and returns formatted text.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
line_count = ui_content.line_count
new_buffer = new_screen.data_buffer
empty_char = _CHAR_CACHE["", ""]
# Map visible line number to (row, col) of input.
# 'col' will always be zero if line wrapping is off.
visible_line_to_row_col: dict[int, tuple[int, int]] = {}
# Maps (row, col) from the input to (y, x) screen coordinates.
rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
def copy_line(
line: StyleAndTextTuples,
lineno: int,
x: int,
y: int,
is_input: bool = False,
) -> tuple[int, int]:
"""
Copy over a single line to the output screen. This can wrap over
multiple lines in the output. It will call the prefix (prompt)
function before every line.
"""
if is_input:
current_rowcol_to_yx = rowcol_to_yx
else:
current_rowcol_to_yx = {} # Throwaway dictionary.
# Draw line prefix.
if is_input and get_line_prefix:
prompt = to_formatted_text(get_line_prefix(lineno, 0))
x, y = copy_line(prompt, lineno, x, y, is_input=False)
# Scroll horizontally.
skipped = 0 # Characters skipped because of horizontal scrolling.
if horizontal_scroll and is_input:
h_scroll = horizontal_scroll
line = explode_text_fragments(line)
while h_scroll > 0 and line:
h_scroll -= get_cwidth(line[0][1])
skipped += 1
del line[:1] # Remove first character.
x -= h_scroll # When scrolling over double width character,
# this can end up being negative.
# Align this line. (Note that this doesn't work well when we use
# get_line_prefix and that function returns variable width prefixes.)
if align == WindowAlign.CENTER:
line_width = fragment_list_width(line)
if line_width < width:
x += (width - line_width) // 2
elif align == WindowAlign.RIGHT:
line_width = fragment_list_width(line)
if line_width < width:
x += width - line_width
col = 0
wrap_count = 0
for style, text, *_ in line:
new_buffer_row = new_buffer[y + ypos]
# Remember raw VT escape sequences. (E.g. FinalTerm's
# escape sequences.)
if "[ZeroWidthEscape]" in style:
new_screen.zero_width_escapes[y + ypos][x + xpos] += text
continue
for c in text:
char = _CHAR_CACHE[c, style]
char_width = char.width
# Wrap when the line width is exceeded.
if wrap_lines and x + char_width > width:
visible_line_to_row_col[y + 1] = (
lineno,
visible_line_to_row_col[y][1] + x,
)
y += 1
wrap_count += 1
x = 0
# Insert line prefix (continuation prompt).
if is_input and get_line_prefix:
prompt = to_formatted_text(
get_line_prefix(lineno, wrap_count)
)
x, y = copy_line(prompt, lineno, x, y, is_input=False)
new_buffer_row = new_buffer[y + ypos]
if y >= write_position.height:
return x, y # Break out of all for loops.
# Set character in screen and shift 'x'.
if x >= 0 and y >= 0 and x < width:
new_buffer_row[x + xpos] = char
# When we print a multi width character, make sure
# to erase the neighbours positions in the screen.
# (The empty string if different from everything,
# so next redraw this cell will repaint anyway.)
if char_width > 1:
for i in range(1, char_width):
new_buffer_row[x + xpos + i] = empty_char
# If this is a zero width characters, then it's
# probably part of a decomposed unicode character.
# See: https://en.wikipedia.org/wiki/Unicode_equivalence
# Merge it in the previous cell.
elif char_width == 0:
# Handle all character widths. If the previous
# character is a multiwidth character, then
# merge it two positions back.
for pw in [2, 1]: # Previous character width.
if (
x - pw >= 0
and new_buffer_row[x + xpos - pw].width == pw
):
prev_char = new_buffer_row[x + xpos - pw]
char2 = _CHAR_CACHE[
prev_char.char + c, prev_char.style
]
new_buffer_row[x + xpos - pw] = char2
# Keep track of write position for each character.
current_rowcol_to_yx[lineno, col + skipped] = (
y + ypos,
x + xpos,
)
col += 1
x += char_width
return x, y
# Copy content.
def copy() -> int:
y = -vertical_scroll_2
lineno = vertical_scroll
while y < write_position.height and lineno < line_count:
# Take the next line and copy it in the real screen.
line = ui_content.get_line(lineno)
visible_line_to_row_col[y] = (lineno, horizontal_scroll)
# Copy margin and actual line.
x = 0
x, y = copy_line(line, lineno, x, y, is_input=True)
lineno += 1
y += 1
return y
copy()
def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
"Translate row/col from UIContent to real Screen coordinates."
try:
y, x = rowcol_to_yx[row, col]
except KeyError:
# Normally this should never happen. (It is a bug, if it happens.)
# But to be sure, return (0, 0)
return Point(x=0, y=0)
# raise ValueError(
# 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
# 'horizontal_scroll=%r, height=%r' %
# (row, col, vertical_scroll, horizontal_scroll, write_position.height))
else:
return Point(x=x, y=y)
# Set cursor and menu positions.
if ui_content.cursor_position:
screen_cursor_position = cursor_pos_to_screen_pos(
ui_content.cursor_position.y, ui_content.cursor_position.x
)
if has_focus:
new_screen.set_cursor_position(self, screen_cursor_position)
if always_hide_cursor:
new_screen.show_cursor = False
else:
new_screen.show_cursor = ui_content.show_cursor
self._highlight_digraph(new_screen)
if highlight_lines:
self._highlight_cursorlines(
new_screen,
screen_cursor_position,
xpos,
ypos,
width,
write_position.height,
)
# Draw input characters from the input processor queue.
if has_focus and ui_content.cursor_position:
self._show_key_processor_key_buffer(new_screen)
# Set menu position.
if ui_content.menu_position:
new_screen.set_menu_position(
self,
cursor_pos_to_screen_pos(
ui_content.menu_position.y, ui_content.menu_position.x
),
)
# Update output screen height.
new_screen.height = max(new_screen.height, ypos + write_position.height)
return visible_line_to_row_col, rowcol_to_yx
def _fill_bg(
self, screen: Screen, write_position: WritePosition, erase_bg: bool
) -> None:
"""
Erase/fill the background.
(Useful for floats and when a `char` has been given.)
"""
char: str | None
if callable(self.char):
char = self.char()
else:
char = self.char
if erase_bg or char:
wp = write_position
char_obj = _CHAR_CACHE[char or " ", ""]
for y in range(wp.ypos, wp.ypos + wp.height):
row = screen.data_buffer[y]
for x in range(wp.xpos, wp.xpos + wp.width):
row[x] = char_obj
def _apply_style(
self, new_screen: Screen, write_position: WritePosition, parent_style: str
) -> None:
# Apply `self.style`.
style = parent_style + " " + to_str(self.style)
new_screen.fill_area(write_position, style=style, after=False)
# Apply the 'last-line' class to the last line of each Window. This can
# be used to apply an 'underline' to the user control.
wp = WritePosition(
write_position.xpos,
write_position.ypos + write_position.height - 1,
write_position.width,
1,
)
new_screen.fill_area(wp, "class:last-line", after=True)
def _highlight_digraph(self, new_screen: Screen) -> None:
"""
When we are in Vi digraph mode, put a question mark underneath the
cursor.
"""
digraph_char = self._get_digraph_char()
if digraph_char:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
digraph_char, "class:digraph"
]
def _show_key_processor_key_buffer(self, new_screen: Screen) -> None:
"""
When the user is typing a key binding that consists of several keys,
display the last pressed key if the user is in insert mode and the key
is meaningful to be displayed.
E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
first 'j' needs to be displayed in order to get some feedback.
"""
app = get_app()
key_buffer = app.key_processor.key_buffer
if key_buffer and _in_insert_mode() and not app.is_done:
# The textual data for the given key. (Can be a VT100 escape
# sequence.)
data = key_buffer[-1].data
# Display only if this is a 1 cell width character.
if get_cwidth(data) == 1:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
data, "class:partial-key-binding"
]
def _highlight_cursorlines(
self, new_screen: Screen, cpos: Point, x: int, y: int, width: int, height: int
) -> None:
"""
Highlight cursor row/column.
"""
cursor_line_style = " class:cursor-line "
cursor_column_style = " class:cursor-column "
data_buffer = new_screen.data_buffer
# Highlight cursor line.
if self.cursorline():
row = data_buffer[cpos.y]
for x in range(x, x + width):
original_char = row[x]
row[x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_line_style
]
# Highlight cursor column.
if self.cursorcolumn():
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[cpos.x]
row[cpos.x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_column_style
]
# Highlight color columns
colorcolumns = self.colorcolumns
if callable(colorcolumns):
colorcolumns = colorcolumns()
for cc in colorcolumns:
assert isinstance(cc, ColorColumn)
column = cc.position
if column < x + width: # Only draw when visible.
color_column_style = " " + cc.style
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[column + x]
row[column + x] = _CHAR_CACHE[
original_char.char, original_char.style + color_column_style
]
def _copy_margin(
self,
margin_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
) -> None:
"""
Copy characters from the margin screen to the real screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
self._copy_body(margin_content, new_screen, margin_write_position, 0, width)
def _scroll(self, ui_content: UIContent, width: int, height: int) -> None:
"""
Scroll body. Ensure that the cursor is visible.
"""
if self.wrap_lines():
func = self._scroll_when_linewrapping
else:
func = self._scroll_without_linewrapping
func(ui_content, width, height)
def _scroll_when_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
scroll_offsets_bottom = self.scroll_offsets.bottom
scroll_offsets_top = self.scroll_offsets.top
# We don't have horizontal scrolling.
self.horizontal_scroll = 0
def get_line_height(lineno: int) -> int:
return ui_content.get_height_for_line(lineno, width, self.get_line_prefix)
# When there is no space, reset `vertical_scroll_2` to zero and abort.
# This can happen if the margin is bigger than the window width.
# Otherwise the text height will become "infinite" (a big number) and
# the copy_line will spend a huge amount of iterations trying to render
# nothing.
if width <= 0:
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = 0
return
# If the current line consumes more than the whole window height,
# then we have to scroll vertically inside this line. (We don't take
# the scroll offsets into account for this.)
# Also, ignore the scroll offsets in this case. Just set the vertical
# scroll to this line.
line_height = get_line_height(ui_content.cursor_position.y)
if line_height > height - scroll_offsets_top:
# Calculate the height of the text before the cursor (including
# line prefixes).
text_before_height = ui_content.get_height_for_line(
ui_content.cursor_position.y,
width,
self.get_line_prefix,
slice_stop=ui_content.cursor_position.x,
)
# Adjust scroll offset.
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = min(
text_before_height - 1, # Keep the cursor visible.
line_height
- height, # Avoid blank lines at the bottom when scolling up again.
self.vertical_scroll_2,
)
self.vertical_scroll_2 = max(
0, text_before_height - height, self.vertical_scroll_2
)
return
else:
self.vertical_scroll_2 = 0
# Current line doesn't consume the whole height. Take scroll offsets into account.
def get_min_vertical_scroll() -> int:
# Make sure that the cursor line is not below the bottom.
# (Calculate how many lines can be shown between the cursor and the .)
used_height = 0
prev_lineno = ui_content.cursor_position.y
for lineno in range(ui_content.cursor_position.y, -1, -1):
used_height += get_line_height(lineno)
if used_height > height - scroll_offsets_bottom:
return prev_lineno
else:
prev_lineno = lineno
return 0
def get_max_vertical_scroll() -> int:
# Make sure that the cursor line is not above the top.
prev_lineno = ui_content.cursor_position.y
used_height = 0
for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > scroll_offsets_top:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
def get_topmost_visible() -> int:
"""
Calculate the upper most line that can be visible, while the bottom
is still visible. We should not allow scroll more than this if
`allow_scroll_beyond_bottom` is false.
"""
prev_lineno = ui_content.line_count - 1
used_height = 0
for lineno in range(ui_content.line_count - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > height:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
# Scroll vertically. (Make sure that the whole line which contains the
# cursor is visible.
topmost_visible = get_topmost_visible()
# Note: the `min(topmost_visible, ...)` is to make sure that we
# don't require scrolling up because of the bottom scroll offset,
# when we are at the end of the document.
self.vertical_scroll = max(
self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll())
)
self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
# Disallow scrolling beyond bottom?
if not self.allow_scroll_beyond_bottom():
self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
def _scroll_without_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
cursor_position = ui_content.cursor_position or Point(x=0, y=0)
# Without line wrapping, we will never have to scroll vertically inside
# a single line.
self.vertical_scroll_2 = 0
if ui_content.line_count == 0:
self.vertical_scroll = 0
self.horizontal_scroll = 0
return
else:
current_line_text = fragment_list_to_text(
ui_content.get_line(cursor_position.y)
)
def do_scroll(
current_scroll: int,
scroll_offset_start: int,
scroll_offset_end: int,
cursor_pos: int,
window_size: int,
content_size: int,
) -> int:
"Scrolling algorithm. Used for both horizontal and vertical scrolling."
# Calculate the scroll offset to apply.
# This can obviously never be more than have the screen size. Also, when the
# cursor appears at the top or bottom, we don't apply the offset.
scroll_offset_start = int(
min(scroll_offset_start, window_size / 2, cursor_pos)
)
scroll_offset_end = int(
min(scroll_offset_end, window_size / 2, content_size - 1 - cursor_pos)
)
# Prevent negative scroll offsets.
if current_scroll < 0:
current_scroll = 0
# Scroll back if we scrolled to much and there's still space to show more of the document.
if (
not self.allow_scroll_beyond_bottom()
and current_scroll > content_size - window_size
):
current_scroll = max(0, content_size - window_size)
# Scroll up if cursor is before visible part.
if current_scroll > cursor_pos - scroll_offset_start:
current_scroll = max(0, cursor_pos - scroll_offset_start)
# Scroll down if cursor is after visible part.
if current_scroll < (cursor_pos + 1) - window_size + scroll_offset_end:
current_scroll = (cursor_pos + 1) - window_size + scroll_offset_end
return current_scroll
# When a preferred scroll is given, take that first into account.
if self.get_vertical_scroll:
self.vertical_scroll = self.get_vertical_scroll(self)
assert isinstance(self.vertical_scroll, int)
if self.get_horizontal_scroll:
self.horizontal_scroll = self.get_horizontal_scroll(self)
assert isinstance(self.horizontal_scroll, int)
# Update horizontal/vertical scroll to make sure that the cursor
# remains visible.
offsets = self.scroll_offsets
self.vertical_scroll = do_scroll(
current_scroll=self.vertical_scroll,
scroll_offset_start=offsets.top,
scroll_offset_end=offsets.bottom,
cursor_pos=ui_content.cursor_position.y,
window_size=height,
content_size=ui_content.line_count,
)
if self.get_line_prefix:
current_line_prefix_width = fragment_list_width(
to_formatted_text(self.get_line_prefix(ui_content.cursor_position.y, 0))
)
else:
current_line_prefix_width = 0
self.horizontal_scroll = do_scroll(
current_scroll=self.horizontal_scroll,
scroll_offset_start=offsets.left,
scroll_offset_end=offsets.right,
cursor_pos=get_cwidth(current_line_text[: ui_content.cursor_position.x]),
window_size=width - current_line_prefix_width,
# We can only analyse the current line. Calculating the width off
# all the lines is too expensive.
content_size=max(
get_cwidth(current_line_text), self.horizontal_scroll + width
),
)
def _mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Mouse handler. Called when the UI control doesn't handle this
particular event.
Return `NotImplemented` if nothing was done as a consequence of this
key binding (no UI invalidate required in that case).
"""
if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
self._scroll_down()
return None
elif mouse_event.event_type == MouseEventType.SCROLL_UP:
self._scroll_up()
return None
return NotImplemented
def _scroll_down(self) -> None:
"Scroll window down."
info = self.render_info
if info is None:
return
if self.vertical_scroll < info.content_height - info.window_height:
if info.cursor_position.y <= info.configured_scroll_offsets.top:
self.content.move_cursor_down()
self.vertical_scroll += 1
def _scroll_up(self) -> None:
"Scroll window up."
info = self.render_info
if info is None:
return
if info.vertical_scroll > 0:
# TODO: not entirely correct yet in case of line wrapping and long lines.
if (
info.cursor_position.y
>= info.window_height - 1 - info.configured_scroll_offsets.bottom
):
self.content.move_cursor_up()
self.vertical_scroll -= 1
def get_key_bindings(self) -> KeyBindingsBase | None:
return self.content.get_key_bindings()
def get_children(self) -> list[Container]:
return []
def to_container(container: AnyContainer) -> Container:
"""
Make sure that the given object is a :class:`.Container`.
"""
if isinstance(container, Container):
return container
elif hasattr(container, "__pt_container__"):
return to_container(container.__pt_container__())
else:
raise ValueError(f"Not a container object: {container!r}")
class UIControl(metaclass=ABCMeta):
"""
Base class for all user interface controls.
"""
def reset(self) -> None:
# Default reset. (Doesn't have to be implemented.)
pass
def preferred_width(self, max_available_width: int) -> int | None:
return None
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int | None:
return None
def is_focusable(self) -> bool:
"""
Tell whether this user control is focusable.
"""
return False
def create_content(self, width: int, height: int) -> UIContent:
"""
Generate the content for this user control.
Returns a :class:`.UIContent` instance.
"""
def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Handle mouse events.
When `NotImplemented` is returned, it means that the given event is not
handled by the `UIControl` itself. The `Window` or key bindings can
decide to handle this event as scrolling or changing focus.
:param mouse_event: `MouseEvent` instance.
"""
return NotImplemented
def move_cursor_down(self) -> None:
"""
Request to move the cursor down.
This happens when scrolling down and the cursor is completely at the
top.
"""
def move_cursor_up(self) -> None:
"""
Request to move the cursor up.
"""
def get_key_bindings(self) -> KeyBindingsBase | None:
"""
The key bindings that are specific for this user control.
Return a :class:`.KeyBindings` object if some key bindings are
specified, or `None` otherwise.
"""
def get_invalidate_events(self) -> Iterable[Event[object]]:
"""
Return a list of `Event` objects. This can be a generator.
(The application collects all these events, in order to bind redraw
handlers to these events.)
"""
return []
The provided code snippet includes necessary dependencies for implementing the `has_focus` function. Write a Python function `def has_focus(value: FocusableElement) -> Condition` to solve the following problem:
Enable when this buffer has the focus.
Here is the function:
def has_focus(value: FocusableElement) -> Condition:
"""
Enable when this buffer has the focus.
"""
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.layout import walk
from prompt_toolkit.layout.containers import Container, Window, to_container
from prompt_toolkit.layout.controls import UIControl
if isinstance(value, str):
def test() -> bool:
return get_app().current_buffer.name == value
elif isinstance(value, Buffer):
def test() -> bool:
return get_app().current_buffer == value
elif isinstance(value, UIControl):
def test() -> bool:
return get_app().layout.current_control == value
else:
value = to_container(value)
if isinstance(value, Window):
def test() -> bool:
return get_app().layout.current_window == value
else:
def test() -> bool:
# Consider focused when any window inside this container is
# focused.
current_window = get_app().layout.current_window
for c in walk(cast(Container, value)):
if isinstance(c, Window) and c == current_window:
return True
return False
@Condition
def has_focus_filter() -> bool:
return test()
return has_focus_filter | Enable when this buffer has the focus. |
172,144 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `buffer_has_focus` function. Write a Python function `def buffer_has_focus() -> bool` to solve the following problem:
Enabled when the currently focused control is a `BufferControl`.
Here is the function:
def buffer_has_focus() -> bool:
"""
Enabled when the currently focused control is a `BufferControl`.
"""
return get_app().layout.buffer_has_focus | Enabled when the currently focused control is a `BufferControl`. |
172,145 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `has_selection` function. Write a Python function `def has_selection() -> bool` to solve the following problem:
Enable when the current buffer has a selection.
Here is the function:
def has_selection() -> bool:
"""
Enable when the current buffer has a selection.
"""
return bool(get_app().current_buffer.selection_state) | Enable when the current buffer has a selection. |
172,146 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `has_suggestion` function. Write a Python function `def has_suggestion() -> bool` to solve the following problem:
Enable when the current buffer has a suggestion.
Here is the function:
def has_suggestion() -> bool:
"""
Enable when the current buffer has a suggestion.
"""
buffer = get_app().current_buffer
return buffer.suggestion is not None and buffer.suggestion.text != "" | Enable when the current buffer has a suggestion. |
172,147 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `has_completions` function. Write a Python function `def has_completions() -> bool` to solve the following problem:
Enable when the current buffer has completions.
Here is the function:
def has_completions() -> bool:
"""
Enable when the current buffer has completions.
"""
state = get_app().current_buffer.complete_state
return state is not None and len(state.completions) > 0 | Enable when the current buffer has completions. |
172,148 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `completion_is_selected` function. Write a Python function `def completion_is_selected() -> bool` to solve the following problem:
True when the user selected a completion.
Here is the function:
def completion_is_selected() -> bool:
"""
True when the user selected a completion.
"""
complete_state = get_app().current_buffer.complete_state
return complete_state is not None and complete_state.current_completion is not None | True when the user selected a completion. |
172,149 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `has_validation_error` function. Write a Python function `def has_validation_error() -> bool` to solve the following problem:
Current buffer has validation error.
Here is the function:
def has_validation_error() -> bool:
"Current buffer has validation error."
return get_app().current_buffer.validation_error is not None | Current buffer has validation error. |
172,150 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `is_done` function. Write a Python function `def is_done() -> bool` to solve the following problem:
True when the CLI is returning, aborting or exiting.
Here is the function:
def is_done() -> bool:
"""
True when the CLI is returning, aborting or exiting.
"""
return get_app().is_done | True when the CLI is returning, aborting or exiting. |
172,151 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
The provided code snippet includes necessary dependencies for implementing the `renderer_height_is_known` function. Write a Python function `def renderer_height_is_known() -> bool` to solve the following problem:
Only True when the renderer knows it's real height. (On VT100 terminals, we have to wait for a CPR response, before we can be sure of the available height between the cursor position and the bottom of the terminal. And usually it's nicer to wait with drawing bottom toolbars until we receive the height, in order to avoid flickering -- first drawing somewhere in the middle, and then again at the bottom.)
Here is the function:
def renderer_height_is_known() -> bool:
"""
Only True when the renderer knows it's real height.
(On VT100 terminals, we have to wait for a CPR response, before we can be
sure of the available height between the cursor position and the bottom of
the terminal. And usually it's nicer to wait with drawing bottom toolbars
until we receive the height, in order to avoid flickering -- first drawing
somewhere in the middle, and then again at the bottom.)
"""
return get_app().renderer.height_is_known | Only True when the renderer knows it's real height. (On VT100 terminals, we have to wait for a CPR response, before we can be sure of the available height between the cursor position and the bottom of the terminal. And usually it's nicer to wait with drawing bottom toolbars until we receive the height, in order to avoid flickering -- first drawing somewhere in the middle, and then again at the bottom.) |
172,152 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
class Condition(Filter):
"""
Turn any callable into a Filter. The callable is supposed to not take any
arguments.
This can be used as a decorator::
def feature_is_active(): # `feature_is_active` becomes a Filter.
return True
:param func: Callable which takes no inputs and returns a boolean.
"""
def __init__(self, func: Callable[[], bool]) -> None:
super().__init__()
self.func = func
def __call__(self) -> bool:
return self.func()
def __repr__(self) -> str:
return "Condition(%r)" % self.func
The provided code snippet includes necessary dependencies for implementing the `in_editing_mode` function. Write a Python function `def in_editing_mode(editing_mode: EditingMode) -> Condition` to solve the following problem:
Check whether a given editing mode is active. (Vi or Emacs.)
Here is the function:
def in_editing_mode(editing_mode: EditingMode) -> Condition:
"""
Check whether a given editing mode is active. (Vi or Emacs.)
"""
@Condition
def in_editing_mode_filter() -> bool:
return get_app().editing_mode == editing_mode
return in_editing_mode_filter | Check whether a given editing mode is active. (Vi or Emacs.) |
172,153 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
The provided code snippet includes necessary dependencies for implementing the `emacs_mode` function. Write a Python function `def emacs_mode() -> bool` to solve the following problem:
When the Emacs bindings are active.
Here is the function:
def emacs_mode() -> bool:
"When the Emacs bindings are active."
return get_app().editing_mode == EditingMode.EMACS | When the Emacs bindings are active. |
172,154 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
def emacs_insert_mode() -> bool:
app = get_app()
if (
app.editing_mode != EditingMode.EMACS
or app.current_buffer.selection_state
or app.current_buffer.read_only()
):
return False
return True | null |
172,155 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
def emacs_selection_mode() -> bool:
app = get_app()
return bool(
app.editing_mode == EditingMode.EMACS and app.current_buffer.selection_state
) | null |
172,156 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
def shift_selection_mode() -> bool:
app = get_app()
return bool(
app.current_buffer.selection_state
and app.current_buffer.selection_state.shift_mode
) | null |
172,157 | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import memoized
from prompt_toolkit.enums import EditingMode
from .base import Condition
def get_app() -> Application[Any]:
"""
Get the current active (running) Application.
An :class:`.Application` is active during the
:meth:`.Application.run_async` call.
We assume that there can only be one :class:`.Application` active at the
same time. There is only one terminal window, with only one stdin and
stdout. This makes the code significantly easier than passing around the
:class:`.Application` everywhere.
If no :class:`.Application` is running, then return by default a
:class:`.DummyApplication`. For practical reasons, we prefer to not raise
an exception. This way, we don't have to check all over the place whether
an actual `Application` was returned.
(For applications like pymux where we can have more than one `Application`,
we'll use a work-around to handle that.)
"""
session = _current_app_session.get()
if session.app is not None:
return session.app
from .dummy import DummyApplication
return DummyApplication()
class BufferControl(UIControl):
"""
Control for visualising the content of a :class:`.Buffer`.
:param buffer: The :class:`.Buffer` object to be displayed.
:param input_processors: A list of
:class:`~prompt_toolkit.layout.processors.Processor` objects.
:param include_default_input_processors: When True, include the default
processors for highlighting of selection, search and displaying of
multiple cursors.
:param lexer: :class:`.Lexer` instance for syntax highlighting.
:param preview_search: `bool` or :class:`.Filter`: Show search while
typing. When this is `True`, probably you want to add a
``HighlightIncrementalSearchProcessor`` as well. Otherwise only the
cursor position will move, but the text won't be highlighted.
:param focusable: `bool` or :class:`.Filter`: Tell whether this control is focusable.
:param focus_on_click: Focus this buffer when it's click, but not yet focused.
:param key_bindings: a :class:`.KeyBindings` object.
"""
def __init__(
self,
buffer: Buffer | None = None,
input_processors: list[Processor] | None = None,
include_default_input_processors: bool = True,
lexer: Lexer | None = None,
preview_search: FilterOrBool = False,
focusable: FilterOrBool = True,
search_buffer_control: (
None | SearchBufferControl | Callable[[], SearchBufferControl]
) = None,
menu_position: Callable[[], int | None] | None = None,
focus_on_click: FilterOrBool = False,
key_bindings: KeyBindingsBase | None = None,
):
self.input_processors = input_processors
self.include_default_input_processors = include_default_input_processors
self.default_input_processors = [
HighlightSearchProcessor(),
HighlightIncrementalSearchProcessor(),
HighlightSelectionProcessor(),
DisplayMultipleCursors(),
]
self.preview_search = to_filter(preview_search)
self.focusable = to_filter(focusable)
self.focus_on_click = to_filter(focus_on_click)
self.buffer = buffer or Buffer()
self.menu_position = menu_position
self.lexer = lexer or SimpleLexer()
self.key_bindings = key_bindings
self._search_buffer_control = search_buffer_control
#: Cache for the lexer.
#: Often, due to cursor movement, undo/redo and window resizing
#: operations, it happens that a short time, the same document has to be
#: lexed. This is a fairly easy way to cache such an expensive operation.
self._fragment_cache: SimpleCache[
Hashable, Callable[[int], StyleAndTextTuples]
] = SimpleCache(maxsize=8)
self._last_click_timestamp: float | None = None
self._last_get_processed_line: Callable[[int], _ProcessedLine] | None = None
def __repr__(self) -> str:
return f"<{self.__class__.__name__} buffer={self.buffer!r} at {id(self)!r}>"
def search_buffer_control(self) -> SearchBufferControl | None:
result: SearchBufferControl | None
if callable(self._search_buffer_control):
result = self._search_buffer_control()
else:
result = self._search_buffer_control
assert result is None or isinstance(result, SearchBufferControl)
return result
def search_buffer(self) -> Buffer | None:
control = self.search_buffer_control
if control is not None:
return control.buffer
return None
def search_state(self) -> SearchState:
"""
Return the `SearchState` for searching this `BufferControl`. This is
always associated with the search control. If one search bar is used
for searching multiple `BufferControls`, then they share the same
`SearchState`.
"""
search_buffer_control = self.search_buffer_control
if search_buffer_control:
return search_buffer_control.searcher_search_state
else:
return SearchState()
def is_focusable(self) -> bool:
return self.focusable()
def preferred_width(self, max_available_width: int) -> int | None:
"""
This should return the preferred width.
Note: We don't specify a preferred width according to the content,
because it would be too expensive. Calculating the preferred
width can be done by calculating the longest line, but this would
require applying all the processors to each line. This is
unfeasible for a larger document, and doing it for small
documents only would result in inconsistent behaviour.
"""
return None
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int | None:
# Calculate the content height, if it was drawn on a screen with the
# given width.
height = 0
content = self.create_content(width, height=1) # Pass a dummy '1' as height.
# When line wrapping is off, the height should be equal to the amount
# of lines.
if not wrap_lines:
return content.line_count
# When the number of lines exceeds the max_available_height, just
# return max_available_height. No need to calculate anything.
if content.line_count >= max_available_height:
return max_available_height
for i in range(content.line_count):
height += content.get_height_for_line(i, width, get_line_prefix)
if height >= max_available_height:
return max_available_height
return height
def _get_formatted_text_for_line_func(
self, document: Document
) -> Callable[[int], StyleAndTextTuples]:
"""
Create a function that returns the fragments for a given line.
"""
# Cache using `document.text`.
def get_formatted_text_for_line() -> Callable[[int], StyleAndTextTuples]:
return self.lexer.lex_document(document)
key = (document.text, self.lexer.invalidation_hash())
return self._fragment_cache.get(key, get_formatted_text_for_line)
def _create_get_processed_line_func(
self, document: Document, width: int, height: int
) -> Callable[[int], _ProcessedLine]:
"""
Create a function that takes a line number of the current document and
returns a _ProcessedLine(processed_fragments, source_to_display, display_to_source)
tuple.
"""
# Merge all input processors together.
input_processors = self.input_processors or []
if self.include_default_input_processors:
input_processors = self.default_input_processors + input_processors
merged_processor = merge_processors(input_processors)
def transform(lineno: int, fragments: StyleAndTextTuples) -> _ProcessedLine:
"Transform the fragments for a given line number."
# Get cursor position at this line.
def source_to_display(i: int) -> int:
"""X position from the buffer to the x position in the
processed fragment list. By default, we start from the 'identity'
operation."""
return i
transformation = merged_processor.apply_transformation(
TransformationInput(
self, document, lineno, source_to_display, fragments, width, height
)
)
return _ProcessedLine(
transformation.fragments,
transformation.source_to_display,
transformation.display_to_source,
)
def create_func() -> Callable[[int], _ProcessedLine]:
get_line = self._get_formatted_text_for_line_func(document)
cache: dict[int, _ProcessedLine] = {}
def get_processed_line(i: int) -> _ProcessedLine:
try:
return cache[i]
except KeyError:
processed_line = transform(i, get_line(i))
cache[i] = processed_line
return processed_line
return get_processed_line
return create_func()
def create_content(
self, width: int, height: int, preview_search: bool = False
) -> UIContent:
"""
Create a UIContent.
"""
buffer = self.buffer
# Trigger history loading of the buffer. We do this during the
# rendering of the UI here, because it needs to happen when an
# `Application` with its event loop is running. During the rendering of
# the buffer control is the earliest place we can achieve this, where
# we're sure the right event loop is active, and don't require user
# interaction (like in a key binding).
buffer.load_history_if_not_yet_loaded()
# Get the document to be shown. If we are currently searching (the
# search buffer has focus, and the preview_search filter is enabled),
# then use the search document, which has possibly a different
# text/cursor position.)
search_control = self.search_buffer_control
preview_now = preview_search or bool(
# Only if this feature is enabled.
self.preview_search()
and
# And something was typed in the associated search field.
search_control
and search_control.buffer.text
and
# And we are searching in this control. (Many controls can point to
# the same search field, like in Pyvim.)
get_app().layout.search_target_buffer_control == self
)
if preview_now and search_control is not None:
ss = self.search_state
document = buffer.document_for_search(
SearchState(
text=search_control.buffer.text,
direction=ss.direction,
ignore_case=ss.ignore_case,
)
)
else:
document = buffer.document
get_processed_line = self._create_get_processed_line_func(
document, width, height
)
self._last_get_processed_line = get_processed_line
def translate_rowcol(row: int, col: int) -> Point:
"Return the content column for this coordinate."
return Point(x=get_processed_line(row).source_to_display(col), y=row)
def get_line(i: int) -> StyleAndTextTuples:
"Return the fragments for a given line number."
fragments = get_processed_line(i).fragments
# Add a space at the end, because that is a possible cursor
# position. (When inserting after the input.) We should do this on
# all the lines, not just the line containing the cursor. (Because
# otherwise, line wrapping/scrolling could change when moving the
# cursor around.)
fragments = fragments + [("", " ")]
return fragments
content = UIContent(
get_line=get_line,
line_count=document.line_count,
cursor_position=translate_rowcol(
document.cursor_position_row, document.cursor_position_col
),
)
# If there is an auto completion going on, use that start point for a
# pop-up menu position. (But only when this buffer has the focus --
# there is only one place for a menu, determined by the focused buffer.)
if get_app().layout.current_control == self:
menu_position = self.menu_position() if self.menu_position else None
if menu_position is not None:
assert isinstance(menu_position, int)
menu_row, menu_col = buffer.document.translate_index_to_position(
menu_position
)
content.menu_position = translate_rowcol(menu_row, menu_col)
elif buffer.complete_state:
# Position for completion menu.
# Note: We use 'min', because the original cursor position could be
# behind the input string when the actual completion is for
# some reason shorter than the text we had before. (A completion
# can change and shorten the input.)
menu_row, menu_col = buffer.document.translate_index_to_position(
min(
buffer.cursor_position,
buffer.complete_state.original_document.cursor_position,
)
)
content.menu_position = translate_rowcol(menu_row, menu_col)
else:
content.menu_position = None
return content
def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Mouse handler for this control.
"""
buffer = self.buffer
position = mouse_event.position
# Focus buffer when clicked.
if get_app().layout.current_control == self:
if self._last_get_processed_line:
processed_line = self._last_get_processed_line(position.y)
# Translate coordinates back to the cursor position of the
# original input.
xpos = processed_line.display_to_source(position.x)
index = buffer.document.translate_row_col_to_index(position.y, xpos)
# Set the cursor position.
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
buffer.exit_selection()
buffer.cursor_position = index
elif (
mouse_event.event_type == MouseEventType.MOUSE_MOVE
and mouse_event.button != MouseButton.NONE
):
# Click and drag to highlight a selection
if (
buffer.selection_state is None
and abs(buffer.cursor_position - index) > 0
):
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position = index
elif mouse_event.event_type == MouseEventType.MOUSE_UP:
# When the cursor was moved to another place, select the text.
# (The >1 is actually a small but acceptable workaround for
# selecting text in Vi navigation mode. In navigation mode,
# the cursor can never be after the text, so the cursor
# will be repositioned automatically.)
if abs(buffer.cursor_position - index) > 1:
if buffer.selection_state is None:
buffer.start_selection(
selection_type=SelectionType.CHARACTERS
)
buffer.cursor_position = index
# Select word around cursor on double click.
# Two MOUSE_UP events in a short timespan are considered a double click.
double_click = (
self._last_click_timestamp
and time.time() - self._last_click_timestamp < 0.3
)
self._last_click_timestamp = time.time()
if double_click:
start, end = buffer.document.find_boundaries_of_current_word()
buffer.cursor_position += start
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position += end - start
else:
# Don't handle scroll events here.
return NotImplemented
# Not focused, but focusing on click events.
else:
if (
self.focus_on_click()
and mouse_event.event_type == MouseEventType.MOUSE_UP
):
# Focus happens on mouseup. (If we did this on mousedown, the
# up event will be received at the point where this widget is
# focused and be handled anyway.)
get_app().layout.current_control = self
else:
return NotImplemented
return None
def move_cursor_down(self) -> None:
b = self.buffer
b.cursor_position += b.document.get_cursor_down_position()
def move_cursor_up(self) -> None:
b = self.buffer
b.cursor_position += b.document.get_cursor_up_position()
def get_key_bindings(self) -> KeyBindingsBase | None:
"""
When additional key bindings are given. Return these.
"""
return self.key_bindings
def get_invalidate_events(self) -> Iterable[Event[object]]:
"""
Return the Window invalidate events.
"""
# Whenever the buffer changes, the UI has to be updated.
yield self.buffer.on_text_changed
yield self.buffer.on_cursor_position_changed
yield self.buffer.on_completions_changed
yield self.buffer.on_suggestion_set
The provided code snippet includes necessary dependencies for implementing the `control_is_searchable` function. Write a Python function `def control_is_searchable() -> bool` to solve the following problem:
When the current UIControl is searchable.
Here is the function:
def control_is_searchable() -> bool:
"When the current UIControl is searchable."
from prompt_toolkit.layout.controls import BufferControl
control = get_app().layout.current_control
return (
isinstance(control, BufferControl) and control.search_buffer_control is not None
) | When the current UIControl is searchable. |
172,158 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
class Filter(metaclass=ABCMeta):
"""
Base class for any filter to activate/deactivate a feature, depending on a
condition.
The return value of ``__call__`` will tell if the feature should be active.
"""
def __init__(self) -> None:
self._and_cache: dict[Filter, Filter] = {}
self._or_cache: dict[Filter, Filter] = {}
self._invert_result: Filter | None = None
def __call__(self) -> bool:
"""
The actual call to evaluate the filter.
"""
return True
def __and__(self, other: Filter) -> Filter:
"""
Chaining of filters using the & operator.
"""
assert isinstance(other, Filter), "Expecting filter, got %r" % other
if isinstance(other, Always):
return self
if isinstance(other, Never):
return other
if other in self._and_cache:
return self._and_cache[other]
result = _AndList.create([self, other])
self._and_cache[other] = result
return result
def __or__(self, other: Filter) -> Filter:
"""
Chaining of filters using the | operator.
"""
assert isinstance(other, Filter), "Expecting filter, got %r" % other
if isinstance(other, Always):
return other
if isinstance(other, Never):
return self
if other in self._or_cache:
return self._or_cache[other]
result = _OrList.create([self, other])
self._or_cache[other] = result
return result
def __invert__(self) -> Filter:
"""
Inverting of filters using the ~ operator.
"""
if self._invert_result is None:
self._invert_result = _Invert(self)
return self._invert_result
def __bool__(self) -> None:
"""
By purpose, we don't allow bool(...) operations directly on a filter,
because the meaning is ambiguous.
Executing a filter has to be done always by calling it. Providing
defaults for `None` values should be done through an `is None` check
instead of for instance ``filter1 or Always()``.
"""
raise ValueError(
"The truth value of a Filter is ambiguous. "
"Instead, call it as a function."
)
def _remove_duplicates(filters: list[Filter]) -> list[Filter]:
result = []
for f in filters:
if f not in result:
result.append(f)
return result | null |
172,159 | from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Type
from .style import Style
def style_from_pygments_dict(pygments_dict: dict[Token, str]) -> Style:
"""
Create a :class:`.Style` instance from a Pygments style dictionary.
(One that maps Token objects to style strings.)
"""
pygments_style = []
for token, style in pygments_dict.items():
pygments_style.append((pygments_token_to_classname(token), style))
return Style(pygments_style)
class Style(BaseStyle):
"""
Create a ``Style`` instance from a list of style rules.
The `style_rules` is supposed to be a list of ('classnames', 'style') tuples.
The classnames are a whitespace separated string of class names and the
style string is just like a Pygments style definition, but with a few
additions: it supports 'reverse' and 'blink'.
Later rules always override previous rules.
Usage::
Style([
('title', '#ff0000 bold underline'),
('something-else', 'reverse'),
('class1 class2', 'reverse'),
])
The ``from_dict`` classmethod is similar, but takes a dictionary as input.
"""
def __init__(self, style_rules: list[tuple[str, str]]) -> None:
class_names_and_attrs = []
# Loop through the rules in the order they were defined.
# Rules that are defined later get priority.
for class_names, style_str in style_rules:
assert CLASS_NAMES_RE.match(class_names), repr(class_names)
# The order of the class names doesn't matter.
# (But the order of rules does matter.)
class_names_set = frozenset(class_names.lower().split())
attrs = _parse_style_str(style_str)
class_names_and_attrs.append((class_names_set, attrs))
self._style_rules = style_rules
self.class_names_and_attrs = class_names_and_attrs
def style_rules(self) -> list[tuple[str, str]]:
return self._style_rules
def from_dict(
cls, style_dict: dict[str, str], priority: Priority = default_priority
) -> Style:
"""
:param style_dict: Style dictionary.
:param priority: `Priority` value.
"""
if priority == Priority.MOST_PRECISE:
def key(item: tuple[str, str]) -> int:
# Split on '.' and whitespace. Count elements.
return sum(len(i.split(".")) for i in item[0].split())
return cls(sorted(style_dict.items(), key=key))
else:
return cls(list(style_dict.items()))
def get_attrs_for_style_str(
self, style_str: str, default: Attrs = DEFAULT_ATTRS
) -> Attrs:
"""
Get `Attrs` for the given style string.
"""
list_of_attrs = [default]
class_names: set[str] = set()
# Apply default styling.
for names, attr in self.class_names_and_attrs:
if not names:
list_of_attrs.append(attr)
# Go from left to right through the style string. Things on the right
# take precedence.
for part in style_str.split():
# This part represents a class.
# Do lookup of this class name in the style definition, as well
# as all class combinations that we have so far.
if part.startswith("class:"):
# Expand all class names (comma separated list).
new_class_names = []
for p in part[6:].lower().split(","):
new_class_names.extend(_expand_classname(p))
for new_name in new_class_names:
# Build a set of all possible class combinations to be applied.
combos = set()
combos.add(frozenset([new_name]))
for count in range(1, len(class_names) + 1):
for c2 in itertools.combinations(class_names, count):
combos.add(frozenset(c2 + (new_name,)))
# Apply the styles that match these class names.
for names, attr in self.class_names_and_attrs:
if names in combos:
list_of_attrs.append(attr)
class_names.add(new_name)
# Process inline style.
else:
inline_attrs = _parse_style_str(part)
list_of_attrs.append(inline_attrs)
return _merge_attrs(list_of_attrs)
def invalidation_hash(self) -> Hashable:
return id(self.class_names_and_attrs)
class Style(metaclass=StyleMeta):
#: overall background color (``None`` means transparent)
background_color = '#ffffff'
#: highlight background color
highlight_color = '#ffffcc'
#: line number font color
line_number_color = 'inherit'
#: line number background color
line_number_background_color = 'transparent'
#: special line number font color
line_number_special_color = '#000000'
#: special line number background color
line_number_special_background_color = '#ffffc0'
#: Style definitions for individual token types.
styles = {}
# Attribute for lexers defined within Pygments. If set
# to True, the style is not shown in the style gallery
# on the website. This is intended for language-specific
# styles.
web_style_gallery_exclude = False
The provided code snippet includes necessary dependencies for implementing the `style_from_pygments_cls` function. Write a Python function `def style_from_pygments_cls(pygments_style_cls: type[PygmentsStyle]) -> Style` to solve the following problem:
Shortcut to create a :class:`.Style` instance from a Pygments style class and a style dictionary. Example:: from prompt_toolkit.styles.from_pygments import style_from_pygments_cls from pygments.styles import get_style_by_name style = style_from_pygments_cls(get_style_by_name('monokai')) :param pygments_style_cls: Pygments style class to start from.
Here is the function:
def style_from_pygments_cls(pygments_style_cls: type[PygmentsStyle]) -> Style:
"""
Shortcut to create a :class:`.Style` instance from a Pygments style class
and a style dictionary.
Example::
from prompt_toolkit.styles.from_pygments import style_from_pygments_cls
from pygments.styles import get_style_by_name
style = style_from_pygments_cls(get_style_by_name('monokai'))
:param pygments_style_cls: Pygments style class to start from.
"""
# Import inline.
from pygments.style import Style as PygmentsStyle
assert issubclass(pygments_style_cls, PygmentsStyle)
return style_from_pygments_dict(pygments_style_cls.styles) | Shortcut to create a :class:`.Style` instance from a Pygments style class and a style dictionary. Example:: from prompt_toolkit.styles.from_pygments import style_from_pygments_cls from pygments.styles import get_style_by_name style = style_from_pygments_cls(get_style_by_name('monokai')) :param pygments_style_cls: Pygments style class to start from. |
172,160 | from __future__ import annotations
import itertools
import re
from enum import Enum
from typing import Dict, Hashable, List, Set, Tuple, TypeVar
from prompt_toolkit.cache import SimpleCache
from .base import (
ANSI_COLOR_NAMES,
ANSI_COLOR_NAMES_ALIASES,
DEFAULT_ATTRS,
Attrs,
BaseStyle,
)
from .named_colors import NAMED_COLORS
The provided code snippet includes necessary dependencies for implementing the `_expand_classname` function. Write a Python function `def _expand_classname(classname: str) -> list[str]` to solve the following problem:
Split a single class name at the `.` operator, and build a list of classes. E.g. 'a.b.c' becomes ['a', 'a.b', 'a.b.c']
Here is the function:
def _expand_classname(classname: str) -> list[str]:
"""
Split a single class name at the `.` operator, and build a list of classes.
E.g. 'a.b.c' becomes ['a', 'a.b', 'a.b.c']
"""
result = []
parts = classname.split(".")
for i in range(1, len(parts) + 1):
result.append(".".join(parts[:i]).lower())
return result | Split a single class name at the `.` operator, and build a list of classes. E.g. 'a.b.c' becomes ['a', 'a.b', 'a.b.c'] |
172,161 | from __future__ import annotations
import itertools
import re
from enum import Enum
from typing import Dict, Hashable, List, Set, Tuple, TypeVar
from prompt_toolkit.cache import SimpleCache
from .base import (
ANSI_COLOR_NAMES,
ANSI_COLOR_NAMES_ALIASES,
DEFAULT_ATTRS,
Attrs,
BaseStyle,
)
from .named_colors import NAMED_COLORS
def parse_color(text: str) -> str:
"""
Parse/validate color format.
Like in Pygments, but also support the ANSI color names.
(These will map to the colors of the 16 color palette.)
"""
# ANSI color names.
if text in ANSI_COLOR_NAMES:
return text
if text in ANSI_COLOR_NAMES_ALIASES:
return ANSI_COLOR_NAMES_ALIASES[text]
# 140 named colors.
try:
# Replace by 'hex' value.
return _named_colors_lowercase[text.lower()]
except KeyError:
pass
# Hex codes.
if text[0:1] == "#":
col = text[1:]
# Keep this for backwards-compatibility (Pygments does it).
# I don't like the '#' prefix for named colors.
if col in ANSI_COLOR_NAMES:
return col
elif col in ANSI_COLOR_NAMES_ALIASES:
return ANSI_COLOR_NAMES_ALIASES[col]
# 6 digit hex color.
elif len(col) == 6:
return col
# 3 digit hex color.
elif len(col) == 3:
return col[0] * 2 + col[1] * 2 + col[2] * 2
# Default.
elif text in ("", "default"):
return text
raise ValueError("Wrong color format %r" % text)
_EMPTY_ATTRS = Attrs(
color=None,
bgcolor=None,
bold=None,
underline=None,
strike=None,
italic=None,
blink=None,
reverse=None,
hidden=None,
)
class Attrs(NamedTuple):
color: str | None
bgcolor: str | None
bold: bool | None
underline: bool | None
strike: bool | None
italic: bool | None
blink: bool | None
reverse: bool | None
hidden: bool | None
DEFAULT_ATTRS = Attrs(
color="",
bgcolor="",
bold=False,
underline=False,
strike=False,
italic=False,
blink=False,
reverse=False,
hidden=False,
)
The provided code snippet includes necessary dependencies for implementing the `_parse_style_str` function. Write a Python function `def _parse_style_str(style_str: str) -> Attrs` to solve the following problem:
Take a style string, e.g. 'bg:red #88ff00 class:title' and return a `Attrs` instance.
Here is the function:
def _parse_style_str(style_str: str) -> Attrs:
"""
Take a style string, e.g. 'bg:red #88ff00 class:title'
and return a `Attrs` instance.
"""
# Start from default Attrs.
if "noinherit" in style_str:
attrs = DEFAULT_ATTRS
else:
attrs = _EMPTY_ATTRS
# Now update with the given attributes.
for part in style_str.split():
if part == "noinherit":
pass
elif part == "bold":
attrs = attrs._replace(bold=True)
elif part == "nobold":
attrs = attrs._replace(bold=False)
elif part == "italic":
attrs = attrs._replace(italic=True)
elif part == "noitalic":
attrs = attrs._replace(italic=False)
elif part == "underline":
attrs = attrs._replace(underline=True)
elif part == "nounderline":
attrs = attrs._replace(underline=False)
elif part == "strike":
attrs = attrs._replace(strike=True)
elif part == "nostrike":
attrs = attrs._replace(strike=False)
# prompt_toolkit extensions. Not in Pygments.
elif part == "blink":
attrs = attrs._replace(blink=True)
elif part == "noblink":
attrs = attrs._replace(blink=False)
elif part == "reverse":
attrs = attrs._replace(reverse=True)
elif part == "noreverse":
attrs = attrs._replace(reverse=False)
elif part == "hidden":
attrs = attrs._replace(hidden=True)
elif part == "nohidden":
attrs = attrs._replace(hidden=False)
# Pygments properties that we ignore.
elif part in ("roman", "sans", "mono"):
pass
elif part.startswith("border:"):
pass
# Ignore pieces in between square brackets. This is internal stuff.
# Like '[transparent]' or '[set-cursor-position]'.
elif part.startswith("[") and part.endswith("]"):
pass
# Colors.
elif part.startswith("bg:"):
attrs = attrs._replace(bgcolor=parse_color(part[3:]))
elif part.startswith("fg:"): # The 'fg:' prefix is optional.
attrs = attrs._replace(color=parse_color(part[3:]))
else:
attrs = attrs._replace(color=parse_color(part))
return attrs | Take a style string, e.g. 'bg:red #88ff00 class:title' and return a `Attrs` instance. |
172,162 | from __future__ import annotations
import itertools
import re
from enum import Enum
from typing import Dict, Hashable, List, Set, Tuple, TypeVar
from prompt_toolkit.cache import SimpleCache
from .base import (
ANSI_COLOR_NAMES,
ANSI_COLOR_NAMES_ALIASES,
DEFAULT_ATTRS,
Attrs,
BaseStyle,
)
from .named_colors import NAMED_COLORS
_T = TypeVar("_T")
class Attrs(NamedTuple):
color: str | None
bgcolor: str | None
bold: bool | None
underline: bool | None
strike: bool | None
italic: bool | None
blink: bool | None
reverse: bool | None
hidden: bool | None
The provided code snippet includes necessary dependencies for implementing the `_merge_attrs` function. Write a Python function `def _merge_attrs(list_of_attrs: list[Attrs]) -> Attrs` to solve the following problem:
Take a list of :class:`.Attrs` instances and merge them into one. Every `Attr` in the list can override the styling of the previous one. So, the last one has highest priority.
Here is the function:
def _merge_attrs(list_of_attrs: list[Attrs]) -> Attrs:
"""
Take a list of :class:`.Attrs` instances and merge them into one.
Every `Attr` in the list can override the styling of the previous one. So,
the last one has highest priority.
"""
def _or(*values: _T) -> _T:
"Take first not-None value, starting at the end."
for v in values[::-1]:
if v is not None:
return v
raise ValueError # Should not happen, there's always one non-null value.
return Attrs(
color=_or("", *[a.color for a in list_of_attrs]),
bgcolor=_or("", *[a.bgcolor for a in list_of_attrs]),
bold=_or(False, *[a.bold for a in list_of_attrs]),
underline=_or(False, *[a.underline for a in list_of_attrs]),
strike=_or(False, *[a.strike for a in list_of_attrs]),
italic=_or(False, *[a.italic for a in list_of_attrs]),
blink=_or(False, *[a.blink for a in list_of_attrs]),
reverse=_or(False, *[a.reverse for a in list_of_attrs]),
hidden=_or(False, *[a.hidden for a in list_of_attrs]),
) | Take a list of :class:`.Attrs` instances and merge them into one. Every `Attr` in the list can override the styling of the previous one. So, the last one has highest priority. |
172,163 | from __future__ import annotations
from prompt_toolkit.cache import memoized
from .base import ANSI_COLOR_NAMES, BaseStyle
from .named_colors import NAMED_COLORS
from .style import Style, merge_styles
PROMPT_TOOLKIT_STYLE = [
# Highlighting of search matches in document.
("search", "bg:ansibrightyellow ansiblack"),
("search.current", ""),
# Incremental search.
("incsearch", ""),
("incsearch.current", "reverse"),
# Highlighting of select text in document.
("selected", "reverse"),
("cursor-column", "bg:#dddddd"),
("cursor-line", "underline"),
("color-column", "bg:#ccaacc"),
# Highlighting of matching brackets.
("matching-bracket", ""),
("matching-bracket.other", "#000000 bg:#aacccc"),
("matching-bracket.cursor", "#ff8888 bg:#880000"),
# Styling of other cursors, in case of block editing.
("multiple-cursors", "#000000 bg:#ccccaa"),
# Line numbers.
("line-number", "#888888"),
("line-number.current", "bold"),
("tilde", "#8888ff"),
# Default prompt.
("prompt", ""),
("prompt.arg", "noinherit"),
("prompt.arg.text", ""),
("prompt.search", "noinherit"),
("prompt.search.text", ""),
# Search toolbar.
("search-toolbar", "bold"),
("search-toolbar.text", "nobold"),
# System toolbar
("system-toolbar", "bold"),
("system-toolbar.text", "nobold"),
# "arg" toolbar.
("arg-toolbar", "bold"),
("arg-toolbar.text", "nobold"),
# Validation toolbar.
("validation-toolbar", "bg:#550000 #ffffff"),
("window-too-small", "bg:#550000 #ffffff"),
# Completions toolbar.
("completion-toolbar", "bg:#bbbbbb #000000"),
("completion-toolbar.arrow", "bg:#bbbbbb #000000 bold"),
("completion-toolbar.completion", "bg:#bbbbbb #000000"),
("completion-toolbar.completion.current", "bg:#444444 #ffffff"),
# Completions menu.
("completion-menu", "bg:#bbbbbb #000000"),
("completion-menu.completion", ""),
("completion-menu.completion.current", "bg:#888888 #ffffff"),
("completion-menu.meta.completion", "bg:#999999 #000000"),
("completion-menu.meta.completion.current", "bg:#aaaaaa #000000"),
("completion-menu.multi-column-meta", "bg:#aaaaaa #000000"),
# Fuzzy matches in completion menu (for FuzzyCompleter).
("completion-menu.completion fuzzymatch.outside", "fg:#444444"),
("completion-menu.completion fuzzymatch.inside", "bold"),
("completion-menu.completion fuzzymatch.inside.character", "underline"),
("completion-menu.completion.current fuzzymatch.outside", "fg:default"),
("completion-menu.completion.current fuzzymatch.inside", "nobold"),
# Styling of readline-like completions.
("readline-like-completions", ""),
("readline-like-completions.completion", ""),
("readline-like-completions.completion fuzzymatch.outside", "#888888"),
("readline-like-completions.completion fuzzymatch.inside", ""),
("readline-like-completions.completion fuzzymatch.inside.character", "underline"),
# Scrollbars.
("scrollbar.background", "bg:#aaaaaa"),
("scrollbar.button", "bg:#444444"),
("scrollbar.arrow", "noinherit bold"),
# Start/end of scrollbars. Adding 'underline' here provides a nice little
# detail to the progress bar, but it doesn't look good on all terminals.
# ('scrollbar.start', 'underline #ffffff'),
# ('scrollbar.end', 'underline #000000'),
# Auto suggestion text.
("auto-suggestion", "#666666"),
# Trailing whitespace and tabs.
("trailing-whitespace", "#999999"),
("tab", "#999999"),
# When Control-C/D has been pressed. Grayed.
("aborting", "#888888 bg:default noreverse noitalic nounderline noblink"),
("exiting", "#888888 bg:default noreverse noitalic nounderline noblink"),
# Entering a Vi digraph.
("digraph", "#4444ff"),
# Control characters, like ^C, ^X.
("control-character", "ansiblue"),
# Non-breaking space.
("nbsp", "underline ansiyellow"),
# Default styling of HTML elements.
("i", "italic"),
("u", "underline"),
("s", "strike"),
("b", "bold"),
("em", "italic"),
("strong", "bold"),
("del", "strike"),
("hidden", "hidden"),
# It should be possible to use the style names in HTML.
# <reverse>...</reverse> or <noreverse>...</noreverse>.
("italic", "italic"),
("underline", "underline"),
("strike", "strike"),
("bold", "bold"),
("reverse", "reverse"),
("noitalic", "noitalic"),
("nounderline", "nounderline"),
("nostrike", "nostrike"),
("nobold", "nobold"),
("noreverse", "noreverse"),
# Prompt bottom toolbar
("bottom-toolbar", "reverse"),
]
COLORS_STYLE = [(name, "fg:" + name) for name in ANSI_COLOR_NAMES] + [
(name.lower(), "fg:" + name) for name in NAMED_COLORS
]
WIDGETS_STYLE = [
# Dialog windows.
("dialog", "bg:#4444ff"),
("dialog.body", "bg:#ffffff #000000"),
("dialog.body text-area", "bg:#cccccc"),
("dialog.body text-area last-line", "underline"),
("dialog frame.label", "#ff0000 bold"),
# Scrollbars in dialogs.
("dialog.body scrollbar.background", ""),
("dialog.body scrollbar.button", "bg:#000000"),
("dialog.body scrollbar.arrow", ""),
("dialog.body scrollbar.start", "nounderline"),
("dialog.body scrollbar.end", "nounderline"),
# Buttons.
("button", ""),
("button.arrow", "bold"),
("button.focused", "bg:#aa0000 #ffffff"),
# Menu bars.
("menu-bar", "bg:#aaaaaa #000000"),
("menu-bar.selected-item", "bg:#ffffff #000000"),
("menu", "bg:#888888 #ffffff"),
("menu.border", "#aaaaaa"),
("menu.border shadow", "#444444"),
# Shadows.
("dialog shadow", "bg:#000088"),
("dialog.body shadow", "bg:#aaaaaa"),
("progress-bar", "bg:#000088"),
("progress-bar.used", "bg:#ff0000"),
]
class BaseStyle(metaclass=ABCMeta):
"""
Abstract base class for prompt_toolkit styles.
"""
def get_attrs_for_style_str(
self, style_str: str, default: Attrs = DEFAULT_ATTRS
) -> Attrs:
"""
Return :class:`.Attrs` for the given style string.
:param style_str: The style string. This can contain inline styling as
well as classnames (e.g. "class:title").
:param default: `Attrs` to be used if no styling was defined.
"""
def style_rules(self) -> list[tuple[str, str]]:
"""
The list of style rules, used to create this style.
(Required for `DynamicStyle` and `_MergedStyle` to work.)
"""
return []
def invalidation_hash(self) -> Hashable:
"""
Invalidation hash for the style. When this changes over time, the
renderer knows that something in the style changed, and that everything
has to be redrawn.
"""
class Style(BaseStyle):
"""
Create a ``Style`` instance from a list of style rules.
The `style_rules` is supposed to be a list of ('classnames', 'style') tuples.
The classnames are a whitespace separated string of class names and the
style string is just like a Pygments style definition, but with a few
additions: it supports 'reverse' and 'blink'.
Later rules always override previous rules.
Usage::
Style([
('title', '#ff0000 bold underline'),
('something-else', 'reverse'),
('class1 class2', 'reverse'),
])
The ``from_dict`` classmethod is similar, but takes a dictionary as input.
"""
def __init__(self, style_rules: list[tuple[str, str]]) -> None:
class_names_and_attrs = []
# Loop through the rules in the order they were defined.
# Rules that are defined later get priority.
for class_names, style_str in style_rules:
assert CLASS_NAMES_RE.match(class_names), repr(class_names)
# The order of the class names doesn't matter.
# (But the order of rules does matter.)
class_names_set = frozenset(class_names.lower().split())
attrs = _parse_style_str(style_str)
class_names_and_attrs.append((class_names_set, attrs))
self._style_rules = style_rules
self.class_names_and_attrs = class_names_and_attrs
def style_rules(self) -> list[tuple[str, str]]:
return self._style_rules
def from_dict(
cls, style_dict: dict[str, str], priority: Priority = default_priority
) -> Style:
"""
:param style_dict: Style dictionary.
:param priority: `Priority` value.
"""
if priority == Priority.MOST_PRECISE:
def key(item: tuple[str, str]) -> int:
# Split on '.' and whitespace. Count elements.
return sum(len(i.split(".")) for i in item[0].split())
return cls(sorted(style_dict.items(), key=key))
else:
return cls(list(style_dict.items()))
def get_attrs_for_style_str(
self, style_str: str, default: Attrs = DEFAULT_ATTRS
) -> Attrs:
"""
Get `Attrs` for the given style string.
"""
list_of_attrs = [default]
class_names: set[str] = set()
# Apply default styling.
for names, attr in self.class_names_and_attrs:
if not names:
list_of_attrs.append(attr)
# Go from left to right through the style string. Things on the right
# take precedence.
for part in style_str.split():
# This part represents a class.
# Do lookup of this class name in the style definition, as well
# as all class combinations that we have so far.
if part.startswith("class:"):
# Expand all class names (comma separated list).
new_class_names = []
for p in part[6:].lower().split(","):
new_class_names.extend(_expand_classname(p))
for new_name in new_class_names:
# Build a set of all possible class combinations to be applied.
combos = set()
combos.add(frozenset([new_name]))
for count in range(1, len(class_names) + 1):
for c2 in itertools.combinations(class_names, count):
combos.add(frozenset(c2 + (new_name,)))
# Apply the styles that match these class names.
for names, attr in self.class_names_and_attrs:
if names in combos:
list_of_attrs.append(attr)
class_names.add(new_name)
# Process inline style.
else:
inline_attrs = _parse_style_str(part)
list_of_attrs.append(inline_attrs)
return _merge_attrs(list_of_attrs)
def invalidation_hash(self) -> Hashable:
return id(self.class_names_and_attrs)
def merge_styles(styles: list[BaseStyle]) -> _MergedStyle:
"""
Merge multiple `Style` objects.
"""
styles = [s for s in styles if s is not None]
return _MergedStyle(styles)
The provided code snippet includes necessary dependencies for implementing the `default_ui_style` function. Write a Python function `def default_ui_style() -> BaseStyle` to solve the following problem:
Create a default `Style` object.
Here is the function:
def default_ui_style() -> BaseStyle:
"""
Create a default `Style` object.
"""
return merge_styles(
[
Style(PROMPT_TOOLKIT_STYLE),
Style(COLORS_STYLE),
Style(WIDGETS_STYLE),
]
) | Create a default `Style` object. |
172,164 | from __future__ import annotations
from prompt_toolkit.cache import memoized
from .base import ANSI_COLOR_NAMES, BaseStyle
from .named_colors import NAMED_COLORS
from .style import Style, merge_styles
PYGMENTS_DEFAULT_STYLE = {
"pygments.whitespace": "#bbbbbb",
"pygments.comment": "italic #408080",
"pygments.comment.preproc": "noitalic #bc7a00",
"pygments.keyword": "bold #008000",
"pygments.keyword.pseudo": "nobold",
"pygments.keyword.type": "nobold #b00040",
"pygments.operator": "#666666",
"pygments.operator.word": "bold #aa22ff",
"pygments.name.builtin": "#008000",
"pygments.name.function": "#0000ff",
"pygments.name.class": "bold #0000ff",
"pygments.name.namespace": "bold #0000ff",
"pygments.name.exception": "bold #d2413a",
"pygments.name.variable": "#19177c",
"pygments.name.constant": "#880000",
"pygments.name.label": "#a0a000",
"pygments.name.entity": "bold #999999",
"pygments.name.attribute": "#7d9029",
"pygments.name.tag": "bold #008000",
"pygments.name.decorator": "#aa22ff",
# Note: In Pygments, Token.String is an alias for Token.Literal.String,
# and Token.Number as an alias for Token.Literal.Number.
"pygments.literal.string": "#ba2121",
"pygments.literal.string.doc": "italic",
"pygments.literal.string.interpol": "bold #bb6688",
"pygments.literal.string.escape": "bold #bb6622",
"pygments.literal.string.regex": "#bb6688",
"pygments.literal.string.symbol": "#19177c",
"pygments.literal.string.other": "#008000",
"pygments.literal.number": "#666666",
"pygments.generic.heading": "bold #000080",
"pygments.generic.subheading": "bold #800080",
"pygments.generic.deleted": "#a00000",
"pygments.generic.inserted": "#00a000",
"pygments.generic.error": "#ff0000",
"pygments.generic.emph": "italic",
"pygments.generic.strong": "bold",
"pygments.generic.prompt": "bold #000080",
"pygments.generic.output": "#888",
"pygments.generic.traceback": "#04d",
"pygments.error": "border:#ff0000",
}
class Style(BaseStyle):
"""
Create a ``Style`` instance from a list of style rules.
The `style_rules` is supposed to be a list of ('classnames', 'style') tuples.
The classnames are a whitespace separated string of class names and the
style string is just like a Pygments style definition, but with a few
additions: it supports 'reverse' and 'blink'.
Later rules always override previous rules.
Usage::
Style([
('title', '#ff0000 bold underline'),
('something-else', 'reverse'),
('class1 class2', 'reverse'),
])
The ``from_dict`` classmethod is similar, but takes a dictionary as input.
"""
def __init__(self, style_rules: list[tuple[str, str]]) -> None:
class_names_and_attrs = []
# Loop through the rules in the order they were defined.
# Rules that are defined later get priority.
for class_names, style_str in style_rules:
assert CLASS_NAMES_RE.match(class_names), repr(class_names)
# The order of the class names doesn't matter.
# (But the order of rules does matter.)
class_names_set = frozenset(class_names.lower().split())
attrs = _parse_style_str(style_str)
class_names_and_attrs.append((class_names_set, attrs))
self._style_rules = style_rules
self.class_names_and_attrs = class_names_and_attrs
def style_rules(self) -> list[tuple[str, str]]:
return self._style_rules
def from_dict(
cls, style_dict: dict[str, str], priority: Priority = default_priority
) -> Style:
"""
:param style_dict: Style dictionary.
:param priority: `Priority` value.
"""
if priority == Priority.MOST_PRECISE:
def key(item: tuple[str, str]) -> int:
# Split on '.' and whitespace. Count elements.
return sum(len(i.split(".")) for i in item[0].split())
return cls(sorted(style_dict.items(), key=key))
else:
return cls(list(style_dict.items()))
def get_attrs_for_style_str(
self, style_str: str, default: Attrs = DEFAULT_ATTRS
) -> Attrs:
"""
Get `Attrs` for the given style string.
"""
list_of_attrs = [default]
class_names: set[str] = set()
# Apply default styling.
for names, attr in self.class_names_and_attrs:
if not names:
list_of_attrs.append(attr)
# Go from left to right through the style string. Things on the right
# take precedence.
for part in style_str.split():
# This part represents a class.
# Do lookup of this class name in the style definition, as well
# as all class combinations that we have so far.
if part.startswith("class:"):
# Expand all class names (comma separated list).
new_class_names = []
for p in part[6:].lower().split(","):
new_class_names.extend(_expand_classname(p))
for new_name in new_class_names:
# Build a set of all possible class combinations to be applied.
combos = set()
combos.add(frozenset([new_name]))
for count in range(1, len(class_names) + 1):
for c2 in itertools.combinations(class_names, count):
combos.add(frozenset(c2 + (new_name,)))
# Apply the styles that match these class names.
for names, attr in self.class_names_and_attrs:
if names in combos:
list_of_attrs.append(attr)
class_names.add(new_name)
# Process inline style.
else:
inline_attrs = _parse_style_str(part)
list_of_attrs.append(inline_attrs)
return _merge_attrs(list_of_attrs)
def invalidation_hash(self) -> Hashable:
return id(self.class_names_and_attrs)
The provided code snippet includes necessary dependencies for implementing the `default_pygments_style` function. Write a Python function `def default_pygments_style() -> Style` to solve the following problem:
Create a `Style` object that contains the default Pygments style.
Here is the function:
def default_pygments_style() -> Style:
"""
Create a `Style` object that contains the default Pygments style.
"""
return Style.from_dict(PYGMENTS_DEFAULT_STYLE) | Create a `Style` object that contains the default Pygments style. |
172,165 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from colorsys import hls_to_rgb, rgb_to_hls
from typing import Callable, Hashable, Optional, Sequence, Tuple, Union
from prompt_toolkit.cache import memoized
from prompt_toolkit.filters import FilterOrBool, to_filter
from prompt_toolkit.utils import AnyFloat, to_float, to_str
from .base import ANSI_COLOR_NAMES, Attrs
from .style import parse_color
class StyleTransformation(metaclass=ABCMeta):
"""
Base class for any style transformation.
"""
def transform_attrs(self, attrs: Attrs) -> Attrs:
"""
Take an `Attrs` object and return a new `Attrs` object.
Remember that the color formats can be either "ansi..." or a 6 digit
lowercase hexadecimal color (without '#' prefix).
"""
def invalidation_hash(self) -> Hashable:
"""
When this changes, the cache should be invalidated.
"""
return f"{self.__class__.__name__}-{id(self)}"
class _MergedStyleTransformation(StyleTransformation):
def __init__(self, style_transformations: Sequence[StyleTransformation]) -> None:
self.style_transformations = style_transformations
def transform_attrs(self, attrs: Attrs) -> Attrs:
for transformation in self.style_transformations:
attrs = transformation.transform_attrs(attrs)
return attrs
def invalidation_hash(self) -> Hashable:
return tuple(t.invalidation_hash() for t in self.style_transformations)
class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]):
def __getitem__(self, i: int) -> _T_co: ...
def __getitem__(self, s: slice) -> Sequence[_T_co]: ...
# Mixin methods
def index(self, value: Any, start: int = ..., stop: int = ...) -> int: ...
def count(self, value: Any) -> int: ...
def __contains__(self, x: object) -> bool: ...
def __iter__(self) -> Iterator[_T_co]: ...
def __reversed__(self) -> Iterator[_T_co]: ...
The provided code snippet includes necessary dependencies for implementing the `merge_style_transformations` function. Write a Python function `def merge_style_transformations( style_transformations: Sequence[StyleTransformation], ) -> StyleTransformation` to solve the following problem:
Merge multiple transformations together.
Here is the function:
def merge_style_transformations(
style_transformations: Sequence[StyleTransformation],
) -> StyleTransformation:
"""
Merge multiple transformations together.
"""
return _MergedStyleTransformation(style_transformations) | Merge multiple transformations together. |
172,166 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from colorsys import hls_to_rgb, rgb_to_hls
from typing import Callable, Hashable, Optional, Sequence, Tuple, Union
from prompt_toolkit.cache import memoized
from prompt_toolkit.filters import FilterOrBool, to_filter
from prompt_toolkit.utils import AnyFloat, to_float, to_str
from .base import ANSI_COLOR_NAMES, Attrs
from .style import parse_color
OPPOSITE_ANSI_COLOR_NAMES = {
"ansidefault": "ansidefault",
"ansiblack": "ansiwhite",
"ansired": "ansibrightred",
"ansigreen": "ansibrightgreen",
"ansiyellow": "ansibrightyellow",
"ansiblue": "ansibrightblue",
"ansimagenta": "ansibrightmagenta",
"ansicyan": "ansibrightcyan",
"ansigray": "ansibrightblack",
"ansiwhite": "ansiblack",
"ansibrightred": "ansired",
"ansibrightgreen": "ansigreen",
"ansibrightyellow": "ansiyellow",
"ansibrightblue": "ansiblue",
"ansibrightmagenta": "ansimagenta",
"ansibrightcyan": "ansicyan",
"ansibrightblack": "ansigray",
}
def rgb_to_hls(r: float, g: float, b: float) -> Tuple[float, float, float]: ...
def hls_to_rgb(h: float, l: float, s: float) -> Tuple[float, float, float]: ...
The provided code snippet includes necessary dependencies for implementing the `get_opposite_color` function. Write a Python function `def get_opposite_color(colorname: str | None) -> str | None` to solve the following problem:
Take a color name in either 'ansi...' format or 6 digit RGB, return the color of opposite luminosity (same hue/saturation). This is used for turning color schemes that work on a light background usable on a dark background.
Here is the function:
def get_opposite_color(colorname: str | None) -> str | None:
"""
Take a color name in either 'ansi...' format or 6 digit RGB, return the
color of opposite luminosity (same hue/saturation).
This is used for turning color schemes that work on a light background
usable on a dark background.
"""
if colorname is None: # Because color/bgcolor can be None in `Attrs`.
return None
# Special values.
if colorname in ("", "default"):
return colorname
# Try ANSI color names.
try:
return OPPOSITE_ANSI_COLOR_NAMES[colorname]
except KeyError:
# Try 6 digit RGB colors.
r = int(colorname[:2], 16) / 255.0
g = int(colorname[2:4], 16) / 255.0
b = int(colorname[4:6], 16) / 255.0
h, l, s = rgb_to_hls(r, g, b)
l = 1 - l
r, g, b = hls_to_rgb(h, l, s)
r = int(r * 255)
g = int(g * 255)
b = int(b * 255)
return f"{r:02x}{g:02x}{b:02x}" | Take a color name in either 'ansi...' format or 6 digit RGB, return the color of opposite luminosity (same hue/saturation). This is used for turning color schemes that work on a light background usable on a dark background. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.