An object to split an input line in a manner similar to readline. By having our own implementation, we can expose readline-like completion in a uniform manner to all frontends. This object only needs to be given the line of text to be split and the cursor position on said line, and it
| 513 | |
| 514 | |
| 515 | class CompletionSplitter(object): |
| 516 | """An object to split an input line in a manner similar to readline. |
| 517 | |
| 518 | By having our own implementation, we can expose readline-like completion in |
| 519 | a uniform manner to all frontends. This object only needs to be given the |
| 520 | line of text to be split and the cursor position on said line, and it |
| 521 | returns the 'word' to be completed on at the cursor after splitting the |
| 522 | entire line. |
| 523 | |
| 524 | What characters are used as splitting delimiters can be controlled by |
| 525 | setting the ``delims`` attribute (this is a property that internally |
| 526 | automatically builds the necessary regular expression)""" |
| 527 | |
| 528 | # Private interface |
| 529 | |
| 530 | # A string of delimiter characters. The default value makes sense for |
| 531 | # IPython's most typical usage patterns. |
| 532 | _delims = DELIMS |
| 533 | |
| 534 | # The expression (a normal string) to be compiled into a regular expression |
| 535 | # for actual splitting. We store it as an attribute mostly for ease of |
| 536 | # debugging, since this type of code can be so tricky to debug. |
| 537 | _delim_expr = None |
| 538 | |
| 539 | # The regular expression that does the actual splitting |
| 540 | _delim_re = None |
| 541 | |
| 542 | def __init__(self, delims=None): |
| 543 | delims = CompletionSplitter._delims if delims is None else delims |
| 544 | self.delims = delims |
| 545 | |
| 546 | @property |
| 547 | def delims(self): |
| 548 | """Return the string of delimiter characters.""" |
| 549 | return self._delims |
| 550 | |
| 551 | @delims.setter |
| 552 | def delims(self, delims): |
| 553 | """Set the delimiters for line splitting.""" |
| 554 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
| 555 | self._delim_re = re.compile(expr) |
| 556 | self._delims = delims |
| 557 | self._delim_expr = expr |
| 558 | |
| 559 | def split_line(self, line, cursor_pos=None): |
| 560 | """Split a line of text with a cursor at the given position. |
| 561 | """ |
| 562 | l = line if cursor_pos is None else line[:cursor_pos] |
| 563 | return self._delim_re.split(l)[-1] |
| 564 | |
| 565 | |
| 566 |