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