Python prompt_toolkit.document.Document() Examples
The following are 30
code examples of prompt_toolkit.document.Document().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
prompt_toolkit.document
, or try the search function
.
Example #1
Source File: test_basic.py From click-repl with MIT License | 7 votes |
def test_completion(): @click.group() def root_command(): pass @root_command.group() def first_level_command(): pass @first_level_command.command() def second_level_command_one(): pass @first_level_command.command() def second_level_command_two(): pass c = ClickCompleter(root_command) completions = list(c.get_completions(Document(u"first_level_command "))) assert set(x.text for x in completions) == set( [u"second_level_command_one", u"second_level_command_two"] )
Example #2
Source File: completer.py From ptpython with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _get_expression_completions( self, document: Document, complete_event: CompleteEvent, temp_locals: Dict[str, Any], ) -> Iterable[Completion]: """ Complete the [ or . operator after an object. """ match = self.expression_pattern.search(document.text_before_cursor) if match is not None: object_var = match.groups()[0] result = self._lookup(object_var, temp_locals) if isinstance(result, (list, tuple, dict)): yield Completion("[", 0) elif result: yield Completion(".", 0)
Example #3
Source File: test_command_collection.py From click-repl with MIT License | 6 votes |
def test_completion(): @click.group() def foo_group(): pass @foo_group.command() def foo_cmd(): pass @click.group() def foobar_group(): pass @foobar_group.command() def foobar_cmd(): pass c = ClickCompleter(click.CommandCollection(sources=[foo_group, foobar_group])) completions = list(c.get_completions(Document(u"foo"))) assert set(x.text for x in completions) == set([u"foo_cmd", u"foobar_cmd"])
Example #4
Source File: processors.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__( self, buffer_control: "BufferControl", document: Document, lineno: int, source_to_display: SourceToDisplay, fragments: StyleAndTextTuples, width: int, height: int, ) -> None: self.buffer_control = buffer_control self.document = document self.lineno = lineno self.source_to_display = source_to_display self.fragments = fragments self.width = width self.height = height
Example #5
Source File: commands.py From pymux with BSD 3-Clause "New" or "Revised" License | 6 votes |
def command_prompt(pymux, variables): """ Enter command prompt. """ client_state = pymux.get_client_state() if variables['<command>']: # When a 'command' has been given. client_state.prompt_text = variables['<message>'] or '(%s)' % variables['<command>'].split()[0] client_state.prompt_command = variables['<command>'] client_state.prompt_mode = True client_state.prompt_buffer.reset(Document( format_pymux_string(pymux, variables['<default>'] or ''))) get_app().layout.focus(client_state.prompt_buffer) else: # Show the ':' prompt. client_state.prompt_text = '' client_state.prompt_command = '' get_app().layout.focus(client_state.command_buffer) # Go to insert mode. get_app().vi_state.input_mode = InputMode.INSERT
Example #6
Source File: history_browser.py From ptpython with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_new_document(self, cursor_pos=None): """ Create a `Document` instance that contains the resulting text. """ lines = [] # Original text, before cursor. if self.original_document.text_before_cursor: lines.append(self.original_document.text_before_cursor) # Selected entries from the history. for line_no in sorted(self.selected_lines): lines.append(self.history_lines[line_no]) # Original text, after cursor. if self.original_document.text_after_cursor: lines.append(self.original_document.text_after_cursor) # Create `Document` with cursor at the right position. text = "\n".join(lines) if cursor_pos is not None and cursor_pos > len(text): cursor_pos = len(text) return Document(text, cursor_pos)
Example #7
Source File: pygments.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_sync_start_position( self, document: Document, lineno: int ) -> Tuple[int, int]: """ Scan backwards, and find a possible position to start. """ pattern = self._compiled_pattern lines = document.lines # Scan upwards, until we find a point where we can start the syntax # synchronisation. for i in range(lineno, max(-1, lineno - self.MAX_BACKWARDS), -1): match = pattern.match(lines[i]) if match: return i, match.start() # No synchronisation point found. If we aren't that far from the # beginning, start at the very beginning, otherwise, just try to start # at the current line. if lineno < self.FROM_START_IF_NO_SYNC_POS_FOUND: return 0, 0 else: return lineno, 0
Example #8
Source File: completer.py From ptpython with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _get_attribute_completions( self, document: Document, complete_event: CompleteEvent, temp_locals: Dict[str, Any], ) -> Iterable[Completion]: """ Complete attribute names. """ match = self.attribute_lookup_pattern.search(document.text_before_cursor) if match is not None: object_var, attr_name = match.groups() # Do lookup of `object_var` in the context. result = self._lookup(object_var, temp_locals) for name in dir(result): if name.startswith(attr_name): yield Completion( name, -len(attr_name), )
Example #9
Source File: named_commands.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
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()
Example #10
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
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])
Example #11
Source File: test_completer.py From contrail-api-cli with MIT License | 6 votes |
def test_cursor_position(self, mock_session): mock_document = Document(text='cat bar --foo bar', cursor_position=6) comp = ShellCompleter() Resource('bar', uuid='4c6d3711-61f1-4505-b8df-189d32b52872') Resource('foo', uuid='7413a49b-4f17-4340-b93f-7e03b29b5a9d') completions = comp.get_completions(mock_document, None) self.assertEqual(len(list(completions)), 1) mock_document = Document(text='ls -P foo', cursor_position=6) completions = comp.get_completions(mock_document, None) self.assertEqual(len(list(completions)), 2) mock_document = Document(text='ln foo', cursor_position=3) completions = comp.get_completions(mock_document, None) self.assertEqual(len(list(completions)), 2) mock_document = Document(text='ln foo bar', cursor_position=3) completions = comp.get_completions(mock_document, None) self.assertEqual(len(list(completions)), 0) mock_document = Document(text='ln foo bar', cursor_position=6) completions = comp.get_completions(mock_document, None) self.assertEqual(len(list(completions)), 1)
Example #12
Source File: test_completer.py From contrail-api-cli with MIT License | 6 votes |
def test_fq_name_completion(self, mock_session): mock_document = Document(text='cat bar/default-dom') comp = ShellCompleter() r1 = Resource('bar', fq_name='default-domain:project:resource') r2 = Resource('bar', fq_name='foo:foo:foo') completions = list(comp.get_completions(mock_document, None)) self.assertEqual(len(completions), 1) self.assertTrue(str(r1.path.relative_to(Context().shell.current_path)) in [c.text for c in completions]) r1.delete() r2.delete() completions = comp.get_completions(mock_document, None) self.assertEqual(len(list(completions)), 0)
Example #13
Source File: ptk.py From pyq with Apache License 2.0 | 6 votes |
def get_completions(self, document, complete_event): """Yield completions""" # Detect a file handle m = HSYM_RE.match(document.text_before_cursor) if m: text = m.group(1) doc = Document(text, len(text)) for c in self.path_completer.get_completions(doc, complete_event): yield c else: # Get word/text before cursor. word_before_cursor = document.get_word_before_cursor(False) for words, meta in self.words_info: for a in words: if a.startswith(word_before_cursor): yield Completion(a, -len(word_before_cursor), display_meta=meta)
Example #14
Source File: test_repl.py From crash with Apache License 2.0 | 6 votes |
def test_undo_capitalize(self): buffer = Buffer() text = 'Selec' buffer.set_document(Document(text, len(text))) self.capitalizer.apply_capitalization(buffer) self.assertEqual('Selec', buffer.text) text = buffer.text + 't' buffer.set_document(Document(text, len(text))) self.capitalizer.apply_capitalization(buffer) self.assertEqual('SELECT', buffer.text) text = buffer.text + 'i' buffer.set_document(Document(text, len(text))) self.capitalizer.apply_capitalization(buffer) self.assertEqual('Selecti', buffer.text) text = buffer.text + 'on' buffer.set_document(Document(text, len(text))) self.capitalizer.apply_capitalization(buffer) self.assertEqual('Selection', buffer.text)
Example #15
Source File: test_completion.py From azure-cli-shell with MIT License | 6 votes |
def test_second_completion(self): self.init3() doc = Document(u'crea ') gen = self.completer.get_completions(doc, None) with self.assertRaises(StopIteration): six.next(gen) doc = Document(u'create --fun ') gen = self.completer.get_completions(doc, None) with self.assertRaises(StopIteration): six.next(gen) doc = Document(u'command d ') gen = self.completer.get_completions(doc, None) with self.assertRaises(StopIteration): six.next(gen) doc = Document(u'create --funtimes "life" --hello') gen = self.completer.get_completions(doc, None) self.assertEqual(six.next(gen), Completion( "--helloworld", -7))
Example #16
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #17
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def document(self, value: Document) -> None: self.buffer.set_document(value, bypass_readonly=True)
Example #18
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_completions_async( self, document: Document, complete_event: CompleteEvent ) -> AsyncGenerator[Completion, None]: # Get all completions from the other completers in a blocking way. for completer in self.completers: async for item in completer.get_completions_async(document, complete_event): yield item
Example #19
Source File: processors.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def unpack( self, ) -> Tuple[ "BufferControl", Document, int, SourceToDisplay, StyleAndTextTuples, int, int ]: return ( self.buffer_control, self.document, self.lineno, self.source_to_display, self.fragments, self.width, self.height, )
Example #20
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
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: for c in completer.get_completions(document, complete_event): yield c
Example #21
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_completions_async( self, document: Document, complete_event: CompleteEvent ) -> AsyncGenerator[Completion, None]: completer = self.get_completer() or DummyCompleter() async for completion in completer.get_completions_async( document, complete_event ): yield completion
Example #22
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_completions( self, document: Document, complete_event: CompleteEvent ) -> Iterable[Completion]: completer = self.get_completer() or DummyCompleter() return completer.get_completions(document, complete_event)
Example #23
Source File: controls.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #24
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_completions_async( self, document: Document, complete_event: CompleteEvent ) -> AsyncGenerator[Completion, None]: """ Asynchronous generator of completions. """ async for completion in generator_to_async_generator( lambda: self.completer.get_completions(document, complete_event) ): yield completion
Example #25
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_completions( self, document: Document, complete_event: CompleteEvent ) -> Iterable[Completion]: return self.completer.get_completions(document, complete_event)
Example #26
Source File: base.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #27
Source File: test_document.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def document(): return Document( "line 1\n" + "line 2\n" + "line 3\n" + "line 4\n", len("line 1\n" + "lin") )
Example #28
Source File: nested.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_completions( self, document: Document, complete_event: CompleteEvent ) -> Iterable[Completion]: # Split document. text = document.text_before_cursor.lstrip() stripped_len = len(document.text_before_cursor) - len(text) # If there is a space, check for the first term, and use a # subcompleter. if " " in text: first_term = text.split()[0] completer = self.options.get(first_term) # If we have a sub completer, use this for the completions. if completer is not None: remaining_text = text[len(first_term) :].lstrip() move_cursor = len(text) - len(remaining_text) + stripped_len new_document = Document( remaining_text, cursor_position=document.cursor_position - move_cursor, ) for c in completer.get_completions(new_document, complete_event): yield c # No space in the input: behave exactly like `WordCompleter`. else: completer = WordCompleter( list(self.options.keys()), ignore_case=self.ignore_case ) for c in completer.get_completions(document, complete_event): yield c
Example #29
Source File: test_document.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_cursor_position(document): assert document.cursor_position_row == 1 assert document.cursor_position_col == 3 d = Document("", 0) assert d.cursor_position_row == 0 assert d.cursor_position_col == 0
Example #30
Source File: validation.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def validate(self, document: Document) -> None: # Parse input document. # We use `match`, not `match_prefix`, because for validation, we want # the actual, unambiguous interpretation of the input. m = self.compiled_grammar.match(document.text) if m: for v in m.variables(): validator = self.validators.get(v.varname) if validator: # Unescape text. unwrapped_text = self.compiled_grammar.unescape(v.varname, v.value) # Create a document, for the completions API (text/cursor_position) inner_document = Document(unwrapped_text, len(unwrapped_text)) try: validator.validate(inner_document) except ValidationError as e: raise ValidationError( cursor_position=v.start + e.cursor_position, message=e.message, ) from e else: raise ValidationError( cursor_position=len(document.text), message="Invalid command" )