| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Module providing 'sequence awareness'.""" |
| 3 |
# std imports |
| 4 |
import re |
| 5 |
import math |
| 6 |
import textwrap |
| 7 |
|
| 8 |
# 3rd party |
| 9 |
import six |
| 10 |
from wcwidth import wcwidth |
| 11 |
|
| 12 |
# local |
| 13 |
from blessed._capabilities import CAPABILITIES_CAUSE_MOVEMENT |
| 14 |
|
| 15 |
__all__ = ('Sequence', 'SequenceTextWrapper', 'iter_parse', 'measure_length') |
| 16 |
|
| 17 |
|
| 18 |
class Termcap(object): |
| 19 |
"""Terminal capability of given variable name and pattern.""" |
| 20 |
|
| 21 |
def __init__(self, name, pattern, attribute): |
| 22 |
""" |
| 23 |
Class initializer. |
| 24 |
|
| 25 |
:arg str name: name describing capability. |
| 26 |
:arg str pattern: regular expression string. |
| 27 |
:arg str attribute: :class:`~.Terminal` attribute used to build |
| 28 |
this terminal capability. |
| 29 |
""" |
| 30 |
self.name = name |
| 31 |
self.pattern = pattern |
| 32 |
self.attribute = attribute |
| 33 |
self._re_compiled = None |
| 34 |
|
| 35 |
def __repr__(self): |
| 36 |
# pylint: disable=redundant-keyword-arg |
| 37 |
return '<Termcap {self.name}:{self.pattern!r}>'.format(self=self) |
| 38 |
|
| 39 |
@property |
| 40 |
def named_pattern(self): |
| 41 |
"""Regular expression pattern for capability with named group.""" |
| 42 |
# pylint: disable=redundant-keyword-arg |
| 43 |
return '(?P<{self.name}>{self.pattern})'.format(self=self) |
| 44 |
|
| 45 |
@property |
| 46 |
def re_compiled(self): |
| 47 |
"""Compiled regular expression pattern for capability.""" |
| 48 |
if self._re_compiled is None: |
| 49 |
self._re_compiled = re.compile(self.pattern) |
| 50 |
return self._re_compiled |
| 51 |
|
| 52 |
@property |
| 53 |
def will_move(self): |
| 54 |
"""Whether capability causes cursor movement.""" |
| 55 |
return self.name in CAPABILITIES_CAUSE_MOVEMENT |
| 56 |
|
| 57 |
def horizontal_distance(self, text): |
| 58 |
""" |
| 59 |
Horizontal carriage adjusted by capability, may be negative. |
| 60 |
|
| 61 |
:rtype: int |
| 62 |
:arg str text: for capabilities *parm_left_cursor*, |
| 63 |
*parm_right_cursor*, provide the matching sequence |
| 64 |
text, its interpreted distance is returned. |
| 65 |
|
| 66 |
:returns: 0 except for matching ' |
| 67 |
""" |
| 68 |
value = { |
| 69 |
'cursor_left': -1, |
| 70 |
'backspace': -1, |
| 71 |
'cursor_right': 1, |
| 72 |
'tab': 8, |
| 73 |
'ascii_tab': 8, |
| 74 |
}.get(self.name, None) |
| 75 |
if value is not None: |
| 76 |
return value |
| 77 |
|
| 78 |
unit = { |
| 79 |
'parm_left_cursor': -1, |
| 80 |
'parm_right_cursor': 1 |
| 81 |
}.get(self.name, None) |
| 82 |
if unit is not None: |
| 83 |
value = int(self.re_compiled.match(text).group(1)) |
| 84 |
return unit * value |
| 85 |
|
| 86 |
return 0 |
| 87 |
|
| 88 |
# pylint: disable=too-many-arguments |
| 89 |
@classmethod |
| 90 |
def build(cls, name, capability, attribute, nparams=0, |
| 91 |
numeric=99, match_grouped=False, match_any=False, |
| 92 |
match_optional=False): |
| 93 |
r""" |
| 94 |
Class factory builder for given capability definition. |
| 95 |
|
| 96 |
:arg str name: Variable name given for this pattern. |
| 97 |
:arg str capability: A unicode string representing a terminal |
| 98 |
capability to build for. When ``nparams`` is non-zero, it |
| 99 |
must be a callable unicode string (such as the result from |
| 100 |
``getattr(term, 'bold')``. |
| 101 |
:arg str attribute: The terminfo(5) capability name by which this |
| 102 |
pattern is known. |
| 103 |
:arg int nparams: number of positional arguments for callable. |
| 104 |
:arg int numeric: Value to substitute into capability to when generating pattern |
| 105 |
:arg bool match_grouped: If the numeric pattern should be |
| 106 |
grouped, ``(\d+)`` when ``True``, ``\d+`` default. |
| 107 |
:arg bool match_any: When keyword argument ``nparams`` is given, |
| 108 |
*any* numeric found in output is suitable for building as |
| 109 |
pattern ``(\d+)``. Otherwise, only the first matching value of |
| 110 |
range *(numeric - 1)* through *(numeric + 1)* will be replaced by |
| 111 |
pattern ``(\d+)`` in builder. |
| 112 |
:arg bool match_optional: When ``True``, building of numeric patterns |
| 113 |
containing ``(\d+)`` will be built as optional, ``(\d+)?``. |
| 114 |
:rtype: blessed.sequences.Termcap |
| 115 |
:returns: Terminal capability instance for given capability definition |
| 116 |
""" |
| 117 |
_numeric_regex = r'\d+' |
| 118 |
if match_grouped: |
| 119 |
_numeric_regex = r'(\d+)' |
| 120 |
if match_optional: |
| 121 |
_numeric_regex = r'(\d+)?' |
| 122 |
numeric = 99 if numeric is None else numeric |
| 123 |
|
| 124 |
# basic capability attribute, not used as a callable |
| 125 |
if nparams == 0: |
| 126 |
return cls(name, re.escape(capability), attribute) |
| 127 |
|
| 128 |
# a callable capability accepting numeric argument |
| 129 |
_outp = re.escape(capability(*(numeric,) * nparams)) |
| 130 |
if not match_any: |
| 131 |
for num in range(numeric - 1, numeric + 2): |
| 132 |
if str(num) in _outp: |
| 133 |
pattern = _outp.replace(str(num), _numeric_regex) |
| 134 |
return cls(name, pattern, attribute) |
| 135 |
|
| 136 |
if match_grouped: |
| 137 |
pattern = re.sub(r'(\d+)', lambda x: _numeric_regex, _outp) |
| 138 |
else: |
| 139 |
pattern = re.sub(r'\d+', lambda x: _numeric_regex, _outp) |
| 140 |
return cls(name, pattern, attribute) |
| 141 |
|
| 142 |
|
| 143 |
class SequenceTextWrapper(textwrap.TextWrapper): |
| 144 |
"""Docstring overridden.""" |
| 145 |
|
| 146 |
def __init__(self, width, term, **kwargs): |
| 147 |
""" |
| 148 |
Class initializer. |
| 149 |
|
| 150 |
This class supports the :meth:`~.Terminal.wrap` method. |
| 151 |
""" |
| 152 |
self.term = term |
| 153 |
textwrap.TextWrapper.__init__(self, width, **kwargs) |
| 154 |
|
| 155 |
def _wrap_chunks(self, chunks): |
| 156 |
""" |
| 157 |
Sequence-aware variant of :meth:`textwrap.TextWrapper._wrap_chunks`. |
| 158 |
|
| 159 |
:raises ValueError: ``self.width`` is not a positive integer |
| 160 |
:rtype: list |
| 161 |
:returns: text chunks adjusted for width |
| 162 |
|
| 163 |
This simply ensures that word boundaries are not broken mid-sequence, as standard python |
| 164 |
textwrap would incorrectly determine the length of a string containing sequences, and may |
| 165 |
also break consider sequences part of a "word" that may be broken by hyphen (``-``), where |
| 166 |
this implementation corrects both. |
| 167 |
""" |
| 168 |
lines = [] |
| 169 |
if self.width <= 0 or not isinstance(self.width, int): |
| 170 |
raise ValueError( |
| 171 |
"invalid width {0!r}({1!r}) (must be integer > 0)" |
| 172 |
.format(self.width, type(self.width))) |
| 173 |
|
| 174 |
term = self.term |
| 175 |
drop_whitespace = not hasattr(self, 'drop_whitespace' |
| 176 |
) or self.drop_whitespace |
| 177 |
chunks.reverse() |
| 178 |
while chunks: |
| 179 |
cur_line = [] |
| 180 |
cur_len = 0 |
| 181 |
indent = self.subsequent_indent if lines else self.initial_indent |
| 182 |
width = self.width - len(indent) |
| 183 |
if drop_whitespace and ( |
| 184 |
Sequence(chunks[-1], term).strip() == '' and lines): |
| 185 |
del chunks[-1] |
| 186 |
while chunks: |
| 187 |
chunk_len = Sequence(chunks[-1], term).length() |
| 188 |
if cur_len + chunk_len > width: |
| 189 |
break |
| 190 |
cur_line.append(chunks.pop()) |
| 191 |
cur_len += chunk_len |
| 192 |
if chunks and Sequence(chunks[-1], term).length() > width: |
| 193 |
self._handle_long_word(chunks, cur_line, cur_len, width) |
| 194 |
if drop_whitespace and ( |
| 195 |
cur_line and Sequence(cur_line[-1], term).strip() == ''): |
| 196 |
del cur_line[-1] |
| 197 |
if cur_line: |
| 198 |
lines.append(indent + u''.join(cur_line)) |
| 199 |
return lines |
| 200 |
|
| 201 |
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): |
| 202 |
""" |
| 203 |
Sequence-aware :meth:`textwrap.TextWrapper._handle_long_word`. |
| 204 |
|
| 205 |
This simply ensures that word boundaries are not broken mid-sequence, as standard python |
| 206 |
textwrap would incorrectly determine the length of a string containing sequences, and may |
| 207 |
also break consider sequences part of a "word" that may be broken by hyphen (``-``), where |
| 208 |
this implementation corrects both. |
| 209 |
""" |
| 210 |
# Figure out when indent is larger than the specified width, and make |
| 211 |
# sure at least one character is stripped off on every pass |
| 212 |
space_left = 1 if width < 1 else width - cur_len |
| 213 |
# If we're allowed to break long words, then do so: put as much |
| 214 |
# of the next chunk onto the current line as will fit. |
| 215 |
|
| 216 |
if self.break_long_words: |
| 217 |
term = self.term |
| 218 |
chunk = reversed_chunks[-1] |
| 219 |
idx = nxt = 0 |
| 220 |
for text, _ in iter_parse(term, chunk): |
| 221 |
nxt += len(text) |
| 222 |
if Sequence(chunk[:nxt], term).length() > space_left: |
| 223 |
break |
| 224 |
idx = nxt |
| 225 |
cur_line.append(chunk[:idx]) |
| 226 |
reversed_chunks[-1] = chunk[idx:] |
| 227 |
|
| 228 |
# Otherwise, we have to preserve the long word intact. Only add |
| 229 |
# it to the current line if there's nothing already there -- |
| 230 |
# that minimizes how much we violate the width constraint. |
| 231 |
elif not cur_line: |
| 232 |
cur_line.append(reversed_chunks.pop()) |
| 233 |
|
| 234 |
# If we're not allowed to break long words, and there's already |
| 235 |
# text on the current line, do nothing. Next time through the |
| 236 |
# main loop of _wrap_chunks(), we'll wind up here again, but |
| 237 |
# cur_len will be zero, so the next line will be entirely |
| 238 |
# devoted to the long word that we can't handle right now. |
| 239 |
|
| 240 |
|
| 241 |
SequenceTextWrapper.__doc__ = textwrap.TextWrapper.__doc__ |
| 242 |
|
| 243 |
|
| 244 |
class Sequence(six.text_type): |
| 245 |
""" |
| 246 |
A "sequence-aware" version of the base :class:`str` class. |
| 247 |
|
| 248 |
This unicode-derived class understands the effect of escape sequences |
| 249 |
of printable length, allowing a properly implemented :meth:`rjust`, |
| 250 |
:meth:`ljust`, :meth:`center`, and :meth:`length`. |
| 251 |
""" |
| 252 |
|
| 253 |
def __new__(cls, sequence_text, term): |
| 254 |
# pylint: disable = missing-return-doc, missing-return-type-doc |
| 255 |
""" |
| 256 |
Class constructor. |
| 257 |
|
| 258 |
:arg str sequence_text: A string that may contain sequences. |
| 259 |
:arg blessed.Terminal term: :class:`~.Terminal` instance. |
| 260 |
""" |
| 261 |
new = six.text_type.__new__(cls, sequence_text) |
| 262 |
new._term = term |
| 263 |
return new |
| 264 |
|
| 265 |
def ljust(self, width, fillchar=u' '): |
| 266 |
""" |
| 267 |
Return string containing sequences, left-adjusted. |
| 268 |
|
| 269 |
:arg int width: Total width given to left-adjust ``text``. If |
| 270 |
unspecified, the width of the attached terminal is used (default). |
| 271 |
:arg str fillchar: String for padding right-of ``text``. |
| 272 |
:returns: String of ``text``, left-aligned by ``width``. |
| 273 |
:rtype: str |
| 274 |
""" |
| 275 |
rightside = fillchar * int( |
| 276 |
(max(0.0, float(width.__index__() - self.length()))) / float(len(fillchar))) |
| 277 |
return u''.join((self, rightside)) |
| 278 |
|
| 279 |
def rjust(self, width, fillchar=u' '): |
| 280 |
""" |
| 281 |
Return string containing sequences, right-adjusted. |
| 282 |
|
| 283 |
:arg int width: Total width given to right-adjust ``text``. If |
| 284 |
unspecified, the width of the attached terminal is used (default). |
| 285 |
:arg str fillchar: String for padding left-of ``text``. |
| 286 |
:returns: String of ``text``, right-aligned by ``width``. |
| 287 |
:rtype: str |
| 288 |
""" |
| 289 |
leftside = fillchar * int( |
| 290 |
(max(0.0, float(width.__index__() - self.length()))) / float(len(fillchar))) |
| 291 |
return u''.join((leftside, self)) |
| 292 |
|
| 293 |
def center(self, width, fillchar=u' '): |
| 294 |
""" |
| 295 |
Return string containing sequences, centered. |
| 296 |
|
| 297 |
:arg int width: Total width given to center ``text``. If |
| 298 |
unspecified, the width of the attached terminal is used (default). |
| 299 |
:arg str fillchar: String for padding left and right-of ``text``. |
| 300 |
:returns: String of ``text``, centered by ``width``. |
| 301 |
:rtype: str |
| 302 |
""" |
| 303 |
split = max(0.0, float(width.__index__()) - self.length()) / 2 |
| 304 |
leftside = fillchar * int( |
| 305 |
(max(0.0, math.floor(split))) / float(len(fillchar))) |
| 306 |
rightside = fillchar * int( |
| 307 |
(max(0.0, math.ceil(split))) / float(len(fillchar))) |
| 308 |
return u''.join((leftside, self, rightside)) |
| 309 |
|
| 310 |
def truncate(self, width): |
| 311 |
""" |
| 312 |
Truncate a string in a sequence-aware manner. |
| 313 |
|
| 314 |
Any printable characters beyond ``width`` are removed, while all |
| 315 |
sequences remain in place. Horizontal Sequences are first expanded |
| 316 |
by :meth:`padd`. |
| 317 |
|
| 318 |
:arg int width: The printable width to truncate the string to. |
| 319 |
:rtype: str |
| 320 |
:returns: String truncated to at most ``width`` printable characters. |
| 321 |
""" |
| 322 |
output = "" |
| 323 |
current_width = 0 |
| 324 |
target_width = width.__index__() |
| 325 |
parsed_seq = iter_parse(self._term, self.padd()) |
| 326 |
|
| 327 |
# Retain all text until non-cap width reaches desired width |
| 328 |
for text, cap in parsed_seq: |
| 329 |
if not cap: |
| 330 |
# use wcwidth clipped to 0 because it can sometimes return -1 |
| 331 |
current_width += max(wcwidth(text), 0) |
| 332 |
if current_width > target_width: |
| 333 |
break |
| 334 |
output += text |
| 335 |
|
| 336 |
# Return with remaining caps appended |
| 337 |
return output + ''.join(text for text, cap in parsed_seq if cap) |
| 338 |
|
| 339 |
def length(self): |
| 340 |
r""" |
| 341 |
Return the printable length of string containing sequences. |
| 342 |
|
| 343 |
Strings containing ``term.left`` or ``\b`` will cause "overstrike", |
| 344 |
but a length less than 0 is not ever returned. So ``_\b+`` is a |
| 345 |
length of 1 (displays as ``+``), but ``\b`` alone is simply a |
| 346 |
length of 0. |
| 347 |
|
| 348 |
Some characters may consume more than one cell, mainly those CJK |
| 349 |
Unified Ideographs (Chinese, Japanese, Korean) defined by Unicode |
| 350 |
as half or full-width characters. |
| 351 |
|
| 352 |
For example: |
| 353 |
|
| 354 |
>>> from blessed import Terminal |
| 355 |
>>> from blessed.sequences import Sequence |
| 356 |
>>> term = Terminal() |
| 357 |
>>> msg = term.clear + term.red(u'コンニチハ') |
| 358 |
>>> Sequence(msg, term).length() |
| 359 |
10 |
| 360 |
|
| 361 |
.. note:: Although accounted for, strings containing sequences such |
| 362 |
as ``term.clear`` will not give accurate returns, it is not |
| 363 |
considered lengthy (a length of 0). |
| 364 |
""" |
| 365 |
# because control characters may return -1, "clip" their length to 0. |
| 366 |
return sum(max(wcwidth(w_char), 0) for w_char in self.padd(strip=True)) |
| 367 |
|
| 368 |
def strip(self, chars=None): |
| 369 |
""" |
| 370 |
Return string of sequences, leading and trailing whitespace removed. |
| 371 |
|
| 372 |
:arg str chars: Remove characters in chars instead of whitespace. |
| 373 |
:rtype: str |
| 374 |
:returns: string of sequences with leading and trailing whitespace removed. |
| 375 |
""" |
| 376 |
return self.strip_seqs().strip(chars) |
| 377 |
|
| 378 |
def lstrip(self, chars=None): |
| 379 |
""" |
| 380 |
Return string of all sequences and leading whitespace removed. |
| 381 |
|
| 382 |
:arg str chars: Remove characters in chars instead of whitespace. |
| 383 |
:rtype: str |
| 384 |
:returns: string of sequences with leading removed. |
| 385 |
""" |
| 386 |
return self.strip_seqs().lstrip(chars) |
| 387 |
|
| 388 |
def rstrip(self, chars=None): |
| 389 |
""" |
| 390 |
Return string of all sequences and trailing whitespace removed. |
| 391 |
|
| 392 |
:arg str chars: Remove characters in chars instead of whitespace. |
| 393 |
:rtype: str |
| 394 |
:returns: string of sequences with trailing removed. |
| 395 |
""" |
| 396 |
return self.strip_seqs().rstrip(chars) |
| 397 |
|
| 398 |
def strip_seqs(self): |
| 399 |
""" |
| 400 |
Return ``text`` stripped of only its terminal sequences. |
| 401 |
|
| 402 |
:rtype: str |
| 403 |
:returns: Text with terminal sequences removed |
| 404 |
""" |
| 405 |
return self.padd(strip=True) |
| 406 |
|
| 407 |
def padd(self, strip=False): |
| 408 |
""" |
| 409 |
Return non-destructive horizontal movement as destructive spacing. |
| 410 |
|
| 411 |
:arg bool strip: Strip terminal sequences |
| 412 |
:rtype: str |
| 413 |
:returns: Text adjusted for horizontal movement |
| 414 |
""" |
| 415 |
outp = '' |
| 416 |
for text, cap in iter_parse(self._term, self): |
| 417 |
if not cap: |
| 418 |
outp += text |
| 419 |
continue |
| 420 |
|
| 421 |
value = cap.horizontal_distance(text) |
| 422 |
if value > 0: |
| 423 |
outp += ' ' * value |
| 424 |
elif value < 0: |
| 425 |
outp = outp[:value] |
| 426 |
elif not strip: |
| 427 |
outp += text |
| 428 |
return outp |
| 429 |
|
| 430 |
|
| 431 |
def iter_parse(term, text): |
| 432 |
""" |
| 433 |
Generator yields (text, capability) for characters of ``text``. |
| 434 |
|
| 435 |
value for ``capability`` may be ``None``, where ``text`` is |
| 436 |
:class:`str` of length 1. Otherwise, ``text`` is a full |
| 437 |
matching sequence of given capability. |
| 438 |
""" |
| 439 |
for match in term._caps_compiled_any.finditer(text): # pylint: disable=protected-access |
| 440 |
name = match.lastgroup |
| 441 |
value = match.group(name) |
| 442 |
if name == 'MISMATCH': |
| 443 |
yield (value, None) |
| 444 |
else: |
| 445 |
yield value, term.caps[name] |
| 446 |
|
| 447 |
|
| 448 |
def measure_length(text, term): |
| 449 |
""" |
| 450 |
.. deprecated:: 1.12.0. |
| 451 |
|
| 452 |
:rtype: int |
| 453 |
:returns: Length of the first sequence in the string |
| 454 |
""" |
| 455 |
try: |
| 456 |
text, capability = next(iter_parse(term, text)) |
| 457 |
if capability: |
| 458 |
return len(text) |
| 459 |
except StopIteration: |
| 460 |
return 0 |
| 461 |
return 0 |