| 1 |
# Copyright 2000-2010 Michael Hudson-Doyle <[email protected]> |
| 2 |
# Antonio Cuni |
| 3 |
# Armin Rigo |
| 4 |
# |
| 5 |
# All Rights Reserved |
| 6 |
# |
| 7 |
# |
| 8 |
# Permission to use, copy, modify, and distribute this software and |
| 9 |
# its documentation for any purpose is hereby granted without fee, |
| 10 |
# provided that the above copyright notice appear in all copies and |
| 11 |
# that both that copyright notice and this permission notice appear in |
| 12 |
# supporting documentation. |
| 13 |
# |
| 14 |
# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO |
| 15 |
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY |
| 16 |
# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, |
| 17 |
# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER |
| 18 |
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF |
| 19 |
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN |
| 20 |
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 21 |
|
| 22 |
from __future__ import annotations |
| 23 |
|
| 24 |
import sys |
| 25 |
import _colorize |
| 26 |
|
| 27 |
from contextlib import contextmanager |
| 28 |
from dataclasses import dataclass, field, fields |
| 29 |
|
| 30 |
from . import commands, console, input |
| 31 |
from .utils import wlen, unbracket, disp_str, gen_colors, THEME |
| 32 |
from .trace import trace |
| 33 |
|
| 34 |
|
| 35 |
# types |
| 36 |
Command = commands.Command |
| 37 |
from .types import Callback, SimpleContextManager, KeySpec, CommandName |
| 38 |
|
| 39 |
|
| 40 |
# syntax classes |
| 41 |
SYNTAX_WHITESPACE, SYNTAX_WORD, SYNTAX_SYMBOL = range(3) |
| 42 |
|
| 43 |
|
| 44 |
def make_default_syntax_table() -> dict[str, int]: |
| 45 |
# XXX perhaps should use some unicodedata here? |
| 46 |
st: dict[str, int] = {} |
| 47 |
for c in map(chr, range(256)): |
| 48 |
st[c] = SYNTAX_SYMBOL |
| 49 |
for c in [a for a in map(chr, range(256)) if a.isalnum()]: |
| 50 |
st[c] = SYNTAX_WORD |
| 51 |
st["\n"] = st[" "] = SYNTAX_WHITESPACE |
| 52 |
return st |
| 53 |
|
| 54 |
|
| 55 |
def make_default_commands() -> dict[CommandName, type[Command]]: |
| 56 |
result: dict[CommandName, type[Command]] = {} |
| 57 |
for v in vars(commands).values(): |
| 58 |
if isinstance(v, type) and issubclass(v, Command) and v.__name__[0].islower(): |
| 59 |
result[v.__name__] = v |
| 60 |
result[v.__name__.replace("_", "-")] = v |
| 61 |
return result |
| 62 |
|
| 63 |
|
| 64 |
default_keymap: tuple[tuple[KeySpec, CommandName], ...] = tuple( |
| 65 |
[ |
| 66 |
(r"\C-a", "beginning-of-line"), |
| 67 |
(r"\C-b", "left"), |
| 68 |
(r"\C-c", "interrupt"), |
| 69 |
(r"\C-d", "delete"), |
| 70 |
(r"\C-e", "end-of-line"), |
| 71 |
(r"\C-f", "right"), |
| 72 |
(r"\C-g", "cancel"), |
| 73 |
(r"\C-h", "backspace"), |
| 74 |
(r"\C-j", "accept"), |
| 75 |
(r"\<return>", "accept"), |
| 76 |
(r"\C-k", "kill-line"), |
| 77 |
(r"\C-l", "clear-screen"), |
| 78 |
(r"\C-m", "accept"), |
| 79 |
(r"\C-t", "transpose-characters"), |
| 80 |
(r"\C-u", "unix-line-discard"), |
| 81 |
(r"\C-w", "unix-word-rubout"), |
| 82 |
(r"\C-x\C-u", "upcase-region"), |
| 83 |
(r"\C-y", "yank"), |
| 84 |
*(() if sys.platform == "win32" else ((r"\C-z", "suspend"), )), |
| 85 |
(r"\M-b", "backward-word"), |
| 86 |
(r"\M-c", "capitalize-word"), |
| 87 |
(r"\M-d", "kill-word"), |
| 88 |
(r"\M-f", "forward-word"), |
| 89 |
(r"\M-l", "downcase-word"), |
| 90 |
(r"\M-t", "transpose-words"), |
| 91 |
(r"\M-u", "upcase-word"), |
| 92 |
(r"\M-y", "yank-pop"), |
| 93 |
(r"\M--", "digit-arg"), |
| 94 |
(r"\M-0", "digit-arg"), |
| 95 |
(r"\M-1", "digit-arg"), |
| 96 |
(r"\M-2", "digit-arg"), |
| 97 |
(r"\M-3", "digit-arg"), |
| 98 |
(r"\M-4", "digit-arg"), |
| 99 |
(r"\M-5", "digit-arg"), |
| 100 |
(r"\M-6", "digit-arg"), |
| 101 |
(r"\M-7", "digit-arg"), |
| 102 |
(r"\M-8", "digit-arg"), |
| 103 |
(r"\M-9", "digit-arg"), |
| 104 |
(r"\M-\n", "accept"), |
| 105 |
("\\\\", "self-insert"), |
| 106 |
(r"\x1b[200~", "perform-bracketed-paste"), |
| 107 |
(r"\x03", "ctrl-c"), |
| 108 |
] |
| 109 |
+ [(c, "self-insert") for c in map(chr, range(32, 127)) if c != "\\"] |
| 110 |
+ [(c, "self-insert") for c in map(chr, range(128, 256)) if c.isalpha()] |
| 111 |
+ [ |
| 112 |
(r"\<up>", "up"), |
| 113 |
(r"\<down>", "down"), |
| 114 |
(r"\<left>", "left"), |
| 115 |
(r"\C-\<left>", "backward-word"), |
| 116 |
(r"\<right>", "right"), |
| 117 |
(r"\C-\<right>", "forward-word"), |
| 118 |
(r"\<delete>", "delete"), |
| 119 |
(r"\x1b[3~", "delete"), |
| 120 |
(r"\<backspace>", "backspace"), |
| 121 |
(r"\M-\<backspace>", "backward-kill-word"), |
| 122 |
(r"\<end>", "end-of-line"), # was 'end' |
| 123 |
(r"\<home>", "beginning-of-line"), # was 'home' |
| 124 |
(r"\<f1>", "help"), |
| 125 |
(r"\<f2>", "show-history"), |
| 126 |
(r"\<f3>", "paste-mode"), |
| 127 |
(r"\EOF", "end"), # the entries in the terminfo database for xterms |
| 128 |
(r"\EOH", "home"), # seem to be wrong. this is a less than ideal |
| 129 |
# workaround |
| 130 |
] |
| 131 |
) |
| 132 |
|
| 133 |
|
| 134 |
@dataclass(slots=True) |
| 135 |
class Reader: |
| 136 |
"""The Reader class implements the bare bones of a command reader, |
| 137 |
handling such details as editing and cursor motion. What it does |
| 138 |
not support are such things as completion or history support - |
| 139 |
these are implemented elsewhere. |
| 140 |
|
| 141 |
Instance variables of note include: |
| 142 |
|
| 143 |
* buffer: |
| 144 |
A per-character list containing all the characters that have been |
| 145 |
entered. Does not include color information. |
| 146 |
* console: |
| 147 |
Hopefully encapsulates the OS dependent stuff. |
| 148 |
* pos: |
| 149 |
A 0-based index into 'buffer' for where the insertion point |
| 150 |
is. |
| 151 |
* screeninfo: |
| 152 |
A list of screen position tuples. Each list element is a tuple |
| 153 |
representing information on visible line length for a given line. |
| 154 |
Allows for efficient skipping of color escape sequences. |
| 155 |
* cxy, lxy: |
| 156 |
the position of the insertion point in screen ... |
| 157 |
* syntax_table: |
| 158 |
Dictionary mapping characters to 'syntax class'; read the |
| 159 |
emacs docs to see what this means :-) |
| 160 |
* commands: |
| 161 |
Dictionary mapping command names to command classes. |
| 162 |
* arg: |
| 163 |
The emacs-style prefix argument. It will be None if no such |
| 164 |
argument has been provided. |
| 165 |
* dirty: |
| 166 |
True if we need to refresh the display. |
| 167 |
* kill_ring: |
| 168 |
The emacs-style kill-ring; manipulated with yank & yank-pop |
| 169 |
* ps1, ps2, ps3, ps4: |
| 170 |
prompts. ps1 is the prompt for a one-line input; for a |
| 171 |
multiline input it looks like: |
| 172 |
ps2> first line of input goes here |
| 173 |
ps3> second and further |
| 174 |
ps3> lines get ps3 |
| 175 |
... |
| 176 |
ps4> and the last one gets ps4 |
| 177 |
As with the usual top-level, you can set these to instances if |
| 178 |
you like; str() will be called on them (once) at the beginning |
| 179 |
of each command. Don't put really long or newline containing |
| 180 |
strings here, please! |
| 181 |
This is just the default policy; you can change it freely by |
| 182 |
overriding get_prompt() (and indeed some standard subclasses |
| 183 |
do). |
| 184 |
* finished: |
| 185 |
handle1 will set this to a true value if a command signals |
| 186 |
that we're done. |
| 187 |
""" |
| 188 |
|
| 189 |
console: console.Console |
| 190 |
|
| 191 |
## state |
| 192 |
buffer: list[str] = field(default_factory=list) |
| 193 |
pos: int = 0 |
| 194 |
ps1: str = "->> " |
| 195 |
ps2: str = "/>> " |
| 196 |
ps3: str = "|.. " |
| 197 |
ps4: str = R"\__ " |
| 198 |
kill_ring: list[list[str]] = field(default_factory=list) |
| 199 |
msg: str = "" |
| 200 |
arg: int | None = None |
| 201 |
dirty: bool = False |
| 202 |
finished: bool = False |
| 203 |
paste_mode: bool = False |
| 204 |
commands: dict[str, type[Command]] = field(default_factory=make_default_commands) |
| 205 |
last_command: type[Command] | None = None |
| 206 |
syntax_table: dict[str, int] = field(default_factory=make_default_syntax_table) |
| 207 |
keymap: tuple[tuple[str, str], ...] = () |
| 208 |
input_trans: input.KeymapTranslator = field(init=False) |
| 209 |
input_trans_stack: list[input.KeymapTranslator] = field(default_factory=list) |
| 210 |
screen: list[str] = field(default_factory=list) |
| 211 |
screeninfo: list[tuple[int, list[int]]] = field(init=False) |
| 212 |
cxy: tuple[int, int] = field(init=False) |
| 213 |
lxy: tuple[int, int] = field(init=False) |
| 214 |
scheduled_commands: list[str] = field(default_factory=list) |
| 215 |
can_colorize: bool = False |
| 216 |
threading_hook: Callback | None = None |
| 217 |
|
| 218 |
## cached metadata to speed up screen refreshes |
| 219 |
@dataclass |
| 220 |
class RefreshCache: |
| 221 |
screen: list[str] = field(default_factory=list) |
| 222 |
screeninfo: list[tuple[int, list[int]]] = field(init=False) |
| 223 |
line_end_offsets: list[int] = field(default_factory=list) |
| 224 |
pos: int = field(init=False) |
| 225 |
cxy: tuple[int, int] = field(init=False) |
| 226 |
dimensions: tuple[int, int] = field(init=False) |
| 227 |
invalidated: bool = False |
| 228 |
|
| 229 |
def update_cache(self, |
| 230 |
reader: Reader, |
| 231 |
screen: list[str], |
| 232 |
screeninfo: list[tuple[int, list[int]]], |
| 233 |
) -> None: |
| 234 |
self.screen = screen.copy() |
| 235 |
self.screeninfo = screeninfo.copy() |
| 236 |
self.pos = reader.pos |
| 237 |
self.cxy = reader.cxy |
| 238 |
self.dimensions = reader.console.width, reader.console.height |
| 239 |
self.invalidated = False |
| 240 |
|
| 241 |
def valid(self, reader: Reader) -> bool: |
| 242 |
if self.invalidated: |
| 243 |
return False |
| 244 |
dimensions = reader.console.width, reader.console.height |
| 245 |
dimensions_changed = dimensions != self.dimensions |
| 246 |
return not dimensions_changed |
| 247 |
|
| 248 |
def get_cached_location(self, reader: Reader) -> tuple[int, int]: |
| 249 |
if self.invalidated: |
| 250 |
raise ValueError("Cache is invalidated") |
| 251 |
offset = 0 |
| 252 |
earliest_common_pos = min(reader.pos, self.pos) |
| 253 |
num_common_lines = len(self.line_end_offsets) |
| 254 |
while num_common_lines > 0: |
| 255 |
offset = self.line_end_offsets[num_common_lines - 1] |
| 256 |
if earliest_common_pos > offset: |
| 257 |
break |
| 258 |
num_common_lines -= 1 |
| 259 |
else: |
| 260 |
offset = 0 |
| 261 |
return offset, num_common_lines |
| 262 |
|
| 263 |
last_refresh_cache: RefreshCache = field(default_factory=RefreshCache) |
| 264 |
|
| 265 |
def __post_init__(self) -> None: |
| 266 |
# Enable the use of `insert` without a `prepare` call - necessary to |
| 267 |
# facilitate the tab completion hack implemented for |
| 268 |
# <https://bugs.python.org/issue25660>. |
| 269 |
self.keymap = self.collect_keymap() |
| 270 |
self.input_trans = input.KeymapTranslator( |
| 271 |
self.keymap, invalid_cls="invalid-key", character_cls="self-insert" |
| 272 |
) |
| 273 |
self.screeninfo = [(0, [])] |
| 274 |
self.cxy = self.pos2xy() |
| 275 |
self.lxy = (self.pos, 0) |
| 276 |
self.can_colorize = _colorize.can_colorize() |
| 277 |
|
| 278 |
self.last_refresh_cache.screeninfo = self.screeninfo |
| 279 |
self.last_refresh_cache.pos = self.pos |
| 280 |
self.last_refresh_cache.cxy = self.cxy |
| 281 |
self.last_refresh_cache.dimensions = (0, 0) |
| 282 |
|
| 283 |
def collect_keymap(self) -> tuple[tuple[KeySpec, CommandName], ...]: |
| 284 |
return default_keymap |
| 285 |
|
| 286 |
def calc_screen(self) -> list[str]: |
| 287 |
"""Translate changes in self.buffer into changes in self.console.screen.""" |
| 288 |
# Since the last call to calc_screen: |
| 289 |
# screen and screeninfo may differ due to a completion menu being shown |
| 290 |
# pos and cxy may differ due to edits, cursor movements, or completion menus |
| 291 |
|
| 292 |
# Lines that are above both the old and new cursor position can't have changed, |
| 293 |
# unless the terminal has been resized (which might cause reflowing) or we've |
| 294 |
# entered or left paste mode (which changes prompts, causing reflowing). |
| 295 |
num_common_lines = 0 |
| 296 |
offset = 0 |
| 297 |
if self.last_refresh_cache.valid(self): |
| 298 |
offset, num_common_lines = self.last_refresh_cache.get_cached_location(self) |
| 299 |
|
| 300 |
screen = self.last_refresh_cache.screen |
| 301 |
del screen[num_common_lines:] |
| 302 |
|
| 303 |
screeninfo = self.last_refresh_cache.screeninfo |
| 304 |
del screeninfo[num_common_lines:] |
| 305 |
|
| 306 |
last_refresh_line_end_offsets = self.last_refresh_cache.line_end_offsets |
| 307 |
del last_refresh_line_end_offsets[num_common_lines:] |
| 308 |
|
| 309 |
pos = self.pos |
| 310 |
pos -= offset |
| 311 |
|
| 312 |
prompt_from_cache = (offset and self.buffer[offset - 1] != "\n") |
| 313 |
|
| 314 |
if self.can_colorize: |
| 315 |
colors = list(gen_colors(self.get_unicode())) |
| 316 |
else: |
| 317 |
colors = None |
| 318 |
trace("colors = {colors}", colors=colors) |
| 319 |
lines = "".join(self.buffer[offset:]).split("\n") |
| 320 |
cursor_found = False |
| 321 |
lines_beyond_cursor = 0 |
| 322 |
for ln, line in enumerate(lines, num_common_lines): |
| 323 |
line_len = len(line) |
| 324 |
if 0 <= pos <= line_len: |
| 325 |
self.lxy = pos, ln |
| 326 |
cursor_found = True |
| 327 |
elif cursor_found: |
| 328 |
lines_beyond_cursor += 1 |
| 329 |
if lines_beyond_cursor > self.console.height: |
| 330 |
# No need to keep formatting lines. |
| 331 |
# The console can't show them. |
| 332 |
break |
| 333 |
if prompt_from_cache: |
| 334 |
# Only the first line's prompt can come from the cache |
| 335 |
prompt_from_cache = False |
| 336 |
prompt = "" |
| 337 |
else: |
| 338 |
prompt = self.get_prompt(ln, line_len >= pos >= 0) |
| 339 |
while "\n" in prompt: |
| 340 |
pre_prompt, _, prompt = prompt.partition("\n") |
| 341 |
last_refresh_line_end_offsets.append(offset) |
| 342 |
screen.append(pre_prompt) |
| 343 |
screeninfo.append((0, [])) |
| 344 |
pos -= line_len + 1 |
| 345 |
prompt, prompt_len = self.process_prompt(prompt) |
| 346 |
chars, char_widths = disp_str(line, colors, offset) |
| 347 |
wrapcount = (sum(char_widths) + prompt_len) // self.console.width |
| 348 |
if wrapcount == 0 or not char_widths: |
| 349 |
offset += line_len + 1 # Takes all of the line plus the newline |
| 350 |
last_refresh_line_end_offsets.append(offset) |
| 351 |
screen.append(prompt + "".join(chars)) |
| 352 |
screeninfo.append((prompt_len, char_widths)) |
| 353 |
else: |
| 354 |
pre = prompt |
| 355 |
prelen = prompt_len |
| 356 |
for wrap in range(wrapcount + 1): |
| 357 |
index_to_wrap_before = 0 |
| 358 |
column = 0 |
| 359 |
for char_width in char_widths: |
| 360 |
if column + char_width + prelen >= self.console.width: |
| 361 |
break |
| 362 |
index_to_wrap_before += 1 |
| 363 |
column += char_width |
| 364 |
if len(chars) > index_to_wrap_before: |
| 365 |
offset += index_to_wrap_before |
| 366 |
post = "\\" |
| 367 |
after = [1] |
| 368 |
else: |
| 369 |
offset += index_to_wrap_before + 1 # Takes the newline |
| 370 |
post = "" |
| 371 |
after = [] |
| 372 |
last_refresh_line_end_offsets.append(offset) |
| 373 |
render = pre + "".join(chars[:index_to_wrap_before]) + post |
| 374 |
render_widths = char_widths[:index_to_wrap_before] + after |
| 375 |
screen.append(render) |
| 376 |
screeninfo.append((prelen, render_widths)) |
| 377 |
chars = chars[index_to_wrap_before:] |
| 378 |
char_widths = char_widths[index_to_wrap_before:] |
| 379 |
pre = "" |
| 380 |
prelen = 0 |
| 381 |
self.screeninfo = screeninfo |
| 382 |
self.cxy = self.pos2xy() |
| 383 |
if self.msg: |
| 384 |
for mline in self.msg.split("\n"): |
| 385 |
screen.append(mline) |
| 386 |
screeninfo.append((0, [])) |
| 387 |
|
| 388 |
self.last_refresh_cache.update_cache(self, screen, screeninfo) |
| 389 |
return screen |
| 390 |
|
| 391 |
@staticmethod |
| 392 |
def process_prompt(prompt: str) -> tuple[str, int]: |
| 393 |
r"""Return a tuple with the prompt string and its visible length. |
| 394 |
|
| 395 |
The prompt string has the zero-width brackets recognized by shells |
| 396 |
(\x01 and \x02) removed. The length ignores anything between those |
| 397 |
brackets as well as any ANSI escape sequences. |
| 398 |
""" |
| 399 |
out_prompt = unbracket(prompt, including_content=False) |
| 400 |
visible_prompt = unbracket(prompt, including_content=True) |
| 401 |
return out_prompt, wlen(visible_prompt) |
| 402 |
|
| 403 |
def bow(self, p: int | None = None) -> int: |
| 404 |
"""Return the 0-based index of the word break preceding p most |
| 405 |
immediately. |
| 406 |
|
| 407 |
p defaults to self.pos; word boundaries are determined using |
| 408 |
self.syntax_table.""" |
| 409 |
if p is None: |
| 410 |
p = self.pos |
| 411 |
st = self.syntax_table |
| 412 |
b = self.buffer |
| 413 |
p -= 1 |
| 414 |
while p >= 0 and st.get(b[p], SYNTAX_WORD) != SYNTAX_WORD: |
| 415 |
p -= 1 |
| 416 |
while p >= 0 and st.get(b[p], SYNTAX_WORD) == SYNTAX_WORD: |
| 417 |
p -= 1 |
| 418 |
return p + 1 |
| 419 |
|
| 420 |
def eow(self, p: int | None = None) -> int: |
| 421 |
"""Return the 0-based index of the word break following p most |
| 422 |
immediately. |
| 423 |
|
| 424 |
p defaults to self.pos; word boundaries are determined using |
| 425 |
self.syntax_table.""" |
| 426 |
if p is None: |
| 427 |
p = self.pos |
| 428 |
st = self.syntax_table |
| 429 |
b = self.buffer |
| 430 |
while p < len(b) and st.get(b[p], SYNTAX_WORD) != SYNTAX_WORD: |
| 431 |
p += 1 |
| 432 |
while p < len(b) and st.get(b[p], SYNTAX_WORD) == SYNTAX_WORD: |
| 433 |
p += 1 |
| 434 |
return p |
| 435 |
|
| 436 |
def bol(self, p: int | None = None) -> int: |
| 437 |
"""Return the 0-based index of the line break preceding p most |
| 438 |
immediately. |
| 439 |
|
| 440 |
p defaults to self.pos.""" |
| 441 |
if p is None: |
| 442 |
p = self.pos |
| 443 |
b = self.buffer |
| 444 |
p -= 1 |
| 445 |
while p >= 0 and b[p] != "\n": |
| 446 |
p -= 1 |
| 447 |
return p + 1 |
| 448 |
|
| 449 |
def eol(self, p: int | None = None) -> int: |
| 450 |
"""Return the 0-based index of the line break following p most |
| 451 |
immediately. |
| 452 |
|
| 453 |
p defaults to self.pos.""" |
| 454 |
if p is None: |
| 455 |
p = self.pos |
| 456 |
b = self.buffer |
| 457 |
while p < len(b) and b[p] != "\n": |
| 458 |
p += 1 |
| 459 |
return p |
| 460 |
|
| 461 |
def max_column(self, y: int) -> int: |
| 462 |
"""Return the last x-offset for line y""" |
| 463 |
return self.screeninfo[y][0] + sum(self.screeninfo[y][1]) |
| 464 |
|
| 465 |
def max_row(self) -> int: |
| 466 |
return len(self.screeninfo) - 1 |
| 467 |
|
| 468 |
def get_arg(self, default: int = 1) -> int: |
| 469 |
"""Return any prefix argument that the user has supplied, |
| 470 |
returning 'default' if there is None. Defaults to 1. |
| 471 |
""" |
| 472 |
if self.arg is None: |
| 473 |
return default |
| 474 |
return self.arg |
| 475 |
|
| 476 |
def get_prompt(self, lineno: int, cursor_on_line: bool) -> str: |
| 477 |
"""Return what should be in the left-hand margin for line |
| 478 |
'lineno'.""" |
| 479 |
if self.arg is not None and cursor_on_line: |
| 480 |
prompt = f"(arg: {self.arg}) " |
| 481 |
elif self.paste_mode: |
| 482 |
prompt = "(paste) " |
| 483 |
elif "\n" in self.buffer: |
| 484 |
if lineno == 0: |
| 485 |
prompt = self.ps2 |
| 486 |
elif self.ps4 and lineno == self.buffer.count("\n"): |
| 487 |
prompt = self.ps4 |
| 488 |
else: |
| 489 |
prompt = self.ps3 |
| 490 |
else: |
| 491 |
prompt = self.ps1 |
| 492 |
|
| 493 |
if self.can_colorize: |
| 494 |
t = THEME() |
| 495 |
prompt = f"{t.prompt}{prompt}{t.reset}" |
| 496 |
return prompt |
| 497 |
|
| 498 |
def push_input_trans(self, itrans: input.KeymapTranslator) -> None: |
| 499 |
self.input_trans_stack.append(self.input_trans) |
| 500 |
self.input_trans = itrans |
| 501 |
|
| 502 |
def pop_input_trans(self) -> None: |
| 503 |
self.input_trans = self.input_trans_stack.pop() |
| 504 |
|
| 505 |
def setpos_from_xy(self, x: int, y: int) -> None: |
| 506 |
"""Set pos according to coordinates x, y""" |
| 507 |
pos = 0 |
| 508 |
i = 0 |
| 509 |
while i < y: |
| 510 |
prompt_len, char_widths = self.screeninfo[i] |
| 511 |
offset = len(char_widths) |
| 512 |
in_wrapped_line = prompt_len + sum(char_widths) >= self.console.width |
| 513 |
if in_wrapped_line: |
| 514 |
pos += offset - 1 # -1 cause backslash is not in buffer |
| 515 |
else: |
| 516 |
pos += offset + 1 # +1 cause newline is in buffer |
| 517 |
i += 1 |
| 518 |
|
| 519 |
j = 0 |
| 520 |
cur_x = self.screeninfo[i][0] |
| 521 |
while cur_x < x: |
| 522 |
if self.screeninfo[i][1][j] == 0: |
| 523 |
j += 1 # prevent potential future infinite loop |
| 524 |
continue |
| 525 |
cur_x += self.screeninfo[i][1][j] |
| 526 |
j += 1 |
| 527 |
pos += 1 |
| 528 |
|
| 529 |
self.pos = pos |
| 530 |
|
| 531 |
def pos2xy(self) -> tuple[int, int]: |
| 532 |
"""Return the x, y coordinates of position 'pos'.""" |
| 533 |
|
| 534 |
prompt_len, y = 0, 0 |
| 535 |
char_widths: list[int] = [] |
| 536 |
pos = self.pos |
| 537 |
assert 0 <= pos <= len(self.buffer) |
| 538 |
|
| 539 |
# optimize for the common case: typing at the end of the buffer |
| 540 |
if pos == len(self.buffer) and len(self.screeninfo) > 0: |
| 541 |
y = len(self.screeninfo) - 1 |
| 542 |
prompt_len, char_widths = self.screeninfo[y] |
| 543 |
return prompt_len + sum(char_widths), y |
| 544 |
|
| 545 |
for prompt_len, char_widths in self.screeninfo: |
| 546 |
offset = len(char_widths) |
| 547 |
in_wrapped_line = prompt_len + sum(char_widths) >= self.console.width |
| 548 |
if in_wrapped_line: |
| 549 |
offset -= 1 # need to remove line-wrapping backslash |
| 550 |
|
| 551 |
if offset >= pos: |
| 552 |
break |
| 553 |
|
| 554 |
if not in_wrapped_line: |
| 555 |
offset += 1 # there's a newline in buffer |
| 556 |
|
| 557 |
pos -= offset |
| 558 |
y += 1 |
| 559 |
return prompt_len + sum(char_widths[:pos]), y |
| 560 |
|
| 561 |
def insert(self, text: str | list[str]) -> None: |
| 562 |
"""Insert 'text' at the insertion point.""" |
| 563 |
self.buffer[self.pos : self.pos] = list(text) |
| 564 |
self.pos += len(text) |
| 565 |
self.dirty = True |
| 566 |
|
| 567 |
def update_cursor(self) -> None: |
| 568 |
"""Move the cursor to reflect changes in self.pos""" |
| 569 |
self.cxy = self.pos2xy() |
| 570 |
trace("update_cursor({pos}) = {cxy}", pos=self.pos, cxy=self.cxy) |
| 571 |
self.console.move_cursor(*self.cxy) |
| 572 |
|
| 573 |
def after_command(self, cmd: Command) -> None: |
| 574 |
"""This function is called to allow post command cleanup.""" |
| 575 |
if getattr(cmd, "kills_digit_arg", True): |
| 576 |
if self.arg is not None: |
| 577 |
self.dirty = True |
| 578 |
self.arg = None |
| 579 |
|
| 580 |
def prepare(self) -> None: |
| 581 |
"""Get ready to run. Call restore when finished. You must not |
| 582 |
write to the console in between the calls to prepare and |
| 583 |
restore.""" |
| 584 |
try: |
| 585 |
self.console.prepare() |
| 586 |
self.arg = None |
| 587 |
self.finished = False |
| 588 |
del self.buffer[:] |
| 589 |
self.pos = 0 |
| 590 |
self.dirty = True |
| 591 |
self.last_command = None |
| 592 |
self.calc_screen() |
| 593 |
except BaseException: |
| 594 |
self.restore() |
| 595 |
raise |
| 596 |
|
| 597 |
while self.scheduled_commands: |
| 598 |
cmd = self.scheduled_commands.pop() |
| 599 |
self.do_cmd((cmd, [])) |
| 600 |
|
| 601 |
def last_command_is(self, cls: type) -> bool: |
| 602 |
if not self.last_command: |
| 603 |
return False |
| 604 |
return issubclass(cls, self.last_command) |
| 605 |
|
| 606 |
def restore(self) -> None: |
| 607 |
"""Clean up after a run.""" |
| 608 |
self.console.restore() |
| 609 |
|
| 610 |
@contextmanager |
| 611 |
def suspend(self) -> SimpleContextManager: |
| 612 |
"""A context manager to delegate to another reader.""" |
| 613 |
prev_state = {f.name: getattr(self, f.name) for f in fields(self)} |
| 614 |
try: |
| 615 |
self.restore() |
| 616 |
yield |
| 617 |
finally: |
| 618 |
for arg in ("msg", "ps1", "ps2", "ps3", "ps4", "paste_mode"): |
| 619 |
setattr(self, arg, prev_state[arg]) |
| 620 |
self.prepare() |
| 621 |
|
| 622 |
@contextmanager |
| 623 |
def suspend_colorization(self) -> SimpleContextManager: |
| 624 |
try: |
| 625 |
old_can_colorize = self.can_colorize |
| 626 |
self.can_colorize = False |
| 627 |
yield |
| 628 |
finally: |
| 629 |
self.can_colorize = old_can_colorize |
| 630 |
|
| 631 |
|
| 632 |
def finish(self) -> None: |
| 633 |
"""Called when a command signals that we're finished.""" |
| 634 |
pass |
| 635 |
|
| 636 |
def error(self, msg: str = "none") -> None: |
| 637 |
self.msg = "! " + msg + " " |
| 638 |
self.dirty = True |
| 639 |
self.console.beep() |
| 640 |
|
| 641 |
def update_screen(self) -> None: |
| 642 |
if self.dirty: |
| 643 |
self.refresh() |
| 644 |
|
| 645 |
def refresh(self) -> None: |
| 646 |
"""Recalculate and refresh the screen.""" |
| 647 |
self.console.height, self.console.width = self.console.getheightwidth() |
| 648 |
# this call sets up self.cxy, so call it first. |
| 649 |
self.screen = self.calc_screen() |
| 650 |
self.console.refresh(self.screen, self.cxy) |
| 651 |
self.dirty = False |
| 652 |
|
| 653 |
def do_cmd(self, cmd: tuple[str, list[str]]) -> None: |
| 654 |
"""`cmd` is a tuple of "event_name" and "event", which in the current |
| 655 |
implementation is always just the "buffer" which happens to be a list |
| 656 |
of single-character strings.""" |
| 657 |
|
| 658 |
trace("received command {cmd}", cmd=cmd) |
| 659 |
if isinstance(cmd[0], str): |
| 660 |
command_type = self.commands.get(cmd[0], commands.invalid_command) |
| 661 |
elif isinstance(cmd[0], type): |
| 662 |
command_type = cmd[0] |
| 663 |
else: |
| 664 |
return # nothing to do |
| 665 |
|
| 666 |
command = command_type(self, *cmd) # type: ignore[arg-type] |
| 667 |
command.do() |
| 668 |
|
| 669 |
self.after_command(command) |
| 670 |
|
| 671 |
if self.dirty: |
| 672 |
self.refresh() |
| 673 |
else: |
| 674 |
self.update_cursor() |
| 675 |
|
| 676 |
if not isinstance(cmd, commands.digit_arg): |
| 677 |
self.last_command = command_type |
| 678 |
|
| 679 |
self.finished = bool(command.finish) |
| 680 |
if self.finished: |
| 681 |
self.console.finish() |
| 682 |
self.finish() |
| 683 |
|
| 684 |
def run_hooks(self) -> None: |
| 685 |
threading_hook = self.threading_hook |
| 686 |
if threading_hook is None and 'threading' in sys.modules: |
| 687 |
from ._threading_handler import install_threading_hook |
| 688 |
install_threading_hook(self) |
| 689 |
if threading_hook is not None: |
| 690 |
try: |
| 691 |
threading_hook() |
| 692 |
except Exception: |
| 693 |
pass |
| 694 |
|
| 695 |
input_hook = self.console.input_hook |
| 696 |
if input_hook: |
| 697 |
try: |
| 698 |
input_hook() |
| 699 |
except Exception: |
| 700 |
pass |
| 701 |
|
| 702 |
def handle1(self, block: bool = True) -> bool: |
| 703 |
"""Handle a single event. Wait as long as it takes if block |
| 704 |
is true (the default), otherwise return False if no event is |
| 705 |
pending.""" |
| 706 |
|
| 707 |
if self.msg: |
| 708 |
self.msg = "" |
| 709 |
self.dirty = True |
| 710 |
|
| 711 |
while True: |
| 712 |
# We use the same timeout as in readline.c: 100ms |
| 713 |
self.run_hooks() |
| 714 |
self.console.wait(100) |
| 715 |
event = self.console.get_event(block=False) |
| 716 |
if not event: |
| 717 |
if block: |
| 718 |
continue |
| 719 |
return False |
| 720 |
|
| 721 |
translate = True |
| 722 |
|
| 723 |
if event.evt == "key": |
| 724 |
self.input_trans.push(event) |
| 725 |
elif event.evt == "scroll": |
| 726 |
self.refresh() |
| 727 |
elif event.evt == "resize": |
| 728 |
self.refresh() |
| 729 |
else: |
| 730 |
translate = False |
| 731 |
|
| 732 |
if translate: |
| 733 |
cmd = self.input_trans.get() |
| 734 |
else: |
| 735 |
cmd = [event.evt, event.data] |
| 736 |
|
| 737 |
if cmd is None: |
| 738 |
if block: |
| 739 |
continue |
| 740 |
return False |
| 741 |
|
| 742 |
self.do_cmd(cmd) |
| 743 |
return True |
| 744 |
|
| 745 |
def push_char(self, char: int | bytes) -> None: |
| 746 |
self.console.push_char(char) |
| 747 |
self.handle1(block=False) |
| 748 |
|
| 749 |
def readline(self, startup_hook: Callback | None = None) -> str: |
| 750 |
"""Read a line. The implementation of this method also shows |
| 751 |
how to drive Reader if you want more control over the event |
| 752 |
loop.""" |
| 753 |
self.prepare() |
| 754 |
try: |
| 755 |
if startup_hook is not None: |
| 756 |
startup_hook() |
| 757 |
self.refresh() |
| 758 |
while not self.finished: |
| 759 |
self.handle1() |
| 760 |
return self.get_unicode() |
| 761 |
|
| 762 |
finally: |
| 763 |
self.restore() |
| 764 |
|
| 765 |
def bind(self, spec: KeySpec, command: CommandName) -> None: |
| 766 |
self.keymap = self.keymap + ((spec, command),) |
| 767 |
self.input_trans = input.KeymapTranslator( |
| 768 |
self.keymap, invalid_cls="invalid-key", character_cls="self-insert" |
| 769 |
) |
| 770 |
|
| 771 |
def get_unicode(self) -> str: |
| 772 |
"""Return the current buffer as a unicode string.""" |
| 773 |
return "".join(self.buffer) |