def validate(self, document): document = Document(text=self.isp.transform_cell(document.text)) super(IPythonValidator, self).validate(document)
def get_completions(self, text, cursor_positition): with self._completer_lock: return self.completer.get_completions( Document(text=text, cursor_position=cursor_positition), None )
def test_substring_completion(self): self.init4() doc = Document(u'create') gen = self.completer.get_completions(doc, None) self.assertEqual(six.next(gen), Completion("createmore", -6))
def __init__(self, text='', multiline=True, password=False, lexer=None, auto_suggest=None, completer=None, complete_while_typing=True, accept_handler=None, history=None, focusable=True, focus_on_click=False, wrap_lines=True, read_only=False, width=None, height=None, dont_extend_height=False, dont_extend_width=False, line_numbers=False, get_line_prefix=None, scrollbar=False, style='', search_field=None, preview_search=True, prompt='', input_processors=None): assert isinstance(text, six.text_type) assert search_field is None or isinstance(search_field, SearchToolbar) if search_field is None: search_control = None elif isinstance(search_field, SearchToolbar): search_control = search_field.control if input_processors is None: input_processors = [] # Writeable attributes. self.completer = completer self.complete_while_typing = complete_while_typing self.lexer = lexer self.auto_suggest = auto_suggest self.read_only = read_only self.wrap_lines = wrap_lines self.buffer = CustomBuffer( document=Document(text, 0), multiline=multiline, read_only=Condition(lambda: is_true(self.read_only)), completer=DynamicCompleter(lambda: self.completer), complete_while_typing=Condition( lambda: is_true(self.complete_while_typing)), auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest), accept_handler=accept_handler, history=history) self.control = BufferControl( buffer=self.buffer, lexer=DynamicLexer(lambda: self.lexer), input_processors=[ ConditionalProcessor(AppendAutoSuggestion(), has_focus(self.buffer) & ~is_done), ConditionalProcessor(processor=PasswordProcessor(), filter=to_filter(password)), BeforeInput(prompt, style='class:text-area.prompt'), ] + input_processors, search_buffer_control=search_control, preview_search=preview_search, focusable=focusable, focus_on_click=focus_on_click) if multiline: if scrollbar: right_margins = [ScrollbarMargin(display_arrows=True)] else: right_margins = [] if line_numbers: left_margins = [NumberedMargin()] else: left_margins = [] else: left_margins = [] right_margins = [] style = 'class:text-area ' + style self.window = Window( height=height, width=width, dont_extend_height=dont_extend_height, dont_extend_width=dont_extend_width, content=self.control, style=style, wrap_lines=Condition(lambda: is_true(self.wrap_lines)), left_margins=left_margins, right_margins=right_margins, get_line_prefix=get_line_prefix)
def set_doc(): self.pt_cli.application.buffer.document = Document(s)
def text(self, value: str) -> None: self.document = Document(value, 0)
def document(): return Document('line 1\n' + 'line 2\n' + 'line 3\n' + 'line 4\n', len('line 1\n' + 'lin'))
def set_text(self, new_text: str): self.input_field.document = Document(text=new_text, cursor_position=len(new_text))
def test_colon_indent(ctx): document = Document("for i in range(5):") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.buffer.document.current_line == ctx.indent
def test_word_completer_match_middle(): completer = WordCompleter(['abc', 'def', 'abca'], match_middle=True) completions = completer.get_completions(Document('bc'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'abca']
def _print(field, st): s = field.text + st.replace('\r', '') field.buffer.document = Document(text=s, cursor_position=len(s))
def set_status_text(msg: str): """Sets the status field text.""" new_text = "Current Status: " + msg status_field.buffer.document = Document( text=new_text, cursor_position=len(new_text) )
def run_async(): with self._auto_refresh_context(): self.default_buffer.reset(Document(self.default)) result = yield From(self.app.run_async(pre_run=pre_run2)) raise Return(result)
def run_sync(): with self._auto_refresh_context(): self.default_buffer.reset(Document(self.default)) return self.app.run(inputhook=self.inputhook, pre_run=pre_run2)
def _(event: KeyPressEvent): input_field.add_history(input_field.text) input_field.text = '' text = 'hello' output_field.buffer.document = Document(text=text, cursor_position=len(text))
def test_continuation_line(ctx): document = Document("\nsecond line") ctx.buffer.set_document(document) ctx.cr(ctx.buffer, ctx.cli) assert ctx.buffer.document.current_line == ""
def __init__( self, text: str = "", multiline: FilterOrBool = True, password: FilterOrBool = False, lexer: Optional[Lexer] = None, auto_suggest: Optional[AutoSuggest] = None, completer: Optional[Completer] = None, complete_while_typing: FilterOrBool = True, validator: Optional[Validator] = None, accept_handler: Optional[BufferAcceptHandler] = None, history: Optional[History] = None, focusable: FilterOrBool = True, focus_on_click: FilterOrBool = False, wrap_lines: FilterOrBool = True, read_only: FilterOrBool = False, width: AnyDimension = None, height: AnyDimension = None, dont_extend_height: FilterOrBool = False, dont_extend_width: FilterOrBool = False, line_numbers: bool = False, get_line_prefix: Optional[GetLinePrefixCallable] = None, scrollbar: bool = False, style: str = "", search_field: Optional[SearchToolbar] = None, preview_search: FilterOrBool = True, prompt: AnyFormattedText = "", input_processors: Optional[List[Processor]] = None, ) -> None: if search_field is None: search_control = None elif isinstance(search_field, SearchToolbar): search_control = search_field.control if input_processors is None: input_processors = [] # Writeable attributes. self.completer = completer self.complete_while_typing = complete_while_typing self.lexer = lexer self.auto_suggest = auto_suggest self.read_only = read_only self.wrap_lines = wrap_lines self.validator = validator self.buffer = Buffer( document=Document(text, 0), multiline=multiline, read_only=Condition(lambda: is_true(self.read_only)), completer=DynamicCompleter(lambda: self.completer), complete_while_typing=Condition( lambda: is_true(self.complete_while_typing) ), validator=DynamicValidator(lambda: self.validator), auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest), accept_handler=accept_handler, history=history, ) self.control = BufferControl( buffer=self.buffer, lexer=DynamicLexer(lambda: self.lexer), input_processors=[ ConditionalProcessor( AppendAutoSuggestion(), has_focus(self.buffer) & ~is_done ), ConditionalProcessor( processor=PasswordProcessor(), filter=to_filter(password) ), BeforeInput(prompt, style="class:text-area.prompt"), ] + input_processors, search_buffer_control=search_control, preview_search=preview_search, focusable=focusable, focus_on_click=focus_on_click, ) if multiline: if scrollbar: right_margins = [ScrollbarMargin(display_arrows=True)] else: right_margins = [] if line_numbers: left_margins = [NumberedMargin()] else: left_margins = [] else: height = D.exact(1) left_margins = [] right_margins = [] style = "class:text-area " + style self.window = Window( height=height, width=width, dont_extend_height=dont_extend_height, dont_extend_width=dont_extend_width, content=self.control, style=style, wrap_lines=Condition(lambda: is_true(self.wrap_lines)), left_margins=left_margins, right_margins=right_margins, get_line_prefix=get_line_prefix, )
def __init__(self, text='', multiline=True, password=False, lexer=None, completer=None, accept_handler=None, focusable=True, wrap_lines=True, read_only=False, width=None, height=None, dont_extend_height=False, dont_extend_width=False, line_numbers=False, scrollbar=False, style='', search_field=None, preview_search=True, prompt='', input_processors=[]): assert isinstance(text, six.text_type) assert search_field is None or isinstance(search_field, SearchToolbar) if search_field is None: search_control = None elif isinstance(search_field, SearchToolbar): search_control = search_field.control self.buffer = Buffer( document=Document(text, 0), multiline=multiline, read_only=read_only, completer=completer, complete_while_typing=True, accept_handler=(lambda buff: accept_handler(buff)) if accept_handler else None) self.control = BufferControl( buffer=self.buffer, lexer=lexer, input_processors=[ ConditionalProcessor( processor=PasswordProcessor(), filter=to_filter(password) ), BeforeInput(prompt, style='class:text-area.prompt'), ] + input_processors, search_buffer_control=search_control, preview_search=preview_search, focusable=focusable) if multiline: if scrollbar: right_margins = [ScrollbarMargin(display_arrows=True)] else: right_margins = [] if line_numbers: left_margins = [NumberedMargin()] else: left_margins = [] else: wrap_lines = False # Never wrap for single line input. height = D.exact(1) left_margins = [] right_margins = [] style = 'class:text-area ' + style self.window = Window( height=height, width=width, dont_extend_height=dont_extend_height, dont_extend_width=dont_extend_width, content=self.control, style=style, wrap_lines=wrap_lines, left_margins=left_margins, right_margins=right_margins)
def get_completions(completer, complete_event, text): position = len(text) return list( completer.get_completions( Document(text=text, cursor_position=position), complete_event))
def test_select_keyword_completion(completer, complete_event): text = 'SEL' position = len('SEL') result = completer.get_completions( Document(text=text, cursor_position=position), complete_event) assert set(result) == set([Completion(text='SELECT', start_position=-3)])
def text(self, value): self.buffer.set_document(Document(value, 0), bypass_readonly=True)
def get_result(completer, text, position=None): position = len(text) if position is None else position return completer.get_completions( Document(text=text, cursor_position=position), Mock())
def print_buffer(data): new_text = output_field.text + data output_field.buffer.document = Document( text=new_text, cursor_position=len(new_text) )
def get_path_matches(self, _, word_before_cursor): completer = PathCompleter(expanduser=True) document = Document(text=word_before_cursor, cursor_position=len(word_before_cursor)) for c in completer.get_completions(document, None): yield Match(completion=c, priority=(0, ))
def __init__(self, event, create_server=False): def ok_handler(): # Simplistic check to see if user forgot to enter something for url url = len(self.url.text) > len('https://') if not all([self.name.text, url, self.method.text]): return ErrorDialog(event, title='Input Error', text='Name, Url, and Method are required.') result = server_to_db() if result.get('success'): root_container.floats.pop() # Rather than inserting a new button into, e.g., # hsplit.children, we recreate the layout since we have to # pay attention to sort order here event.app.layout = Layout(root_container.create()) # Find the button in the redrawn layout; then focus on it buttons = ButtonManager.update_buttons(event.app) for button in buttons: if self.name.text == button.content.text()[1][1].strip(): event.app.layout.focus(button) break select_item(event) else: # Add/update server returned an error ErrorDialog(event, title='Add/edit server error', text=str(result.get('errors'))) def cancel_handler(): root_container.floats.pop() if ButtonManager.prev_button: event.app.layout.focus(ButtonManager.prev_button) def server_to_db(): if self.rowid: # Updating an existing server return db.update_one( rowid=self.rowid, values={ 'name': self.name.text, 'url': self.url.text, 'method': self.method.text }) else: # Creating a new server return db.add_one( values={ 'name': self.name.text, 'url': self.url.text, 'method': self.method.text }) # Get data about server currently editing if create_server: title = 'New Server' self.rowid = None name = '' url = 'https://' method = '' else: title = 'Edit Server' self.name = ButtonManager.current_button result = db.fetch_one(name=self.name) self.rowid = result.rowid name = result.name url = result.url method = result.method # Dialog configuration ok_button = Button(text='OK', handler=ok_handler) cancel_button = Button(text='Cancel', handler=cancel_handler) methods = [ 'GET', 'POST', 'PUT', 'HEAD', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH' ] method_completer = WordCompleter(methods, ignore_case=True) local_kb = KeyBindings() @local_kb.add('enter') def cancel_completion(event): buff = event.app.current_buffer buff.complete_state = None event.app.layout.focus_next() self.name = TextArea( multiline=False, text=name ) self.name.buffer.document = Document(name, len(name)) self.url = TextArea( multiline=False, text=url ) self.url.buffer.document = Document(url, len(url)) self.method = TextArea( multiline=False, completer=method_completer, text=method) self.method.buffer.document = Document(method, len(method)) self.dialog = Dialog( title=title, body=HSplit([ Label(text='Server name:\n'), self.name, Window(height=1, char=' '), Label(text='Url:\n'), self.url, Window(height=1, char=' '), Label(text='Method:\n'), self.method, Window(height=1, char=' ') ], key_bindings=local_kb ), buttons=[ok_button, cancel_button], width=D(preferred=80), with_background=True ) self.current_button = event.app.layout.current_window root_container.floats.append(Float(self.dialog)) event.app.layout.focus(self.dialog)
def set_prompt(self, prompt_command="", position=0): """ writes the prompt line """ self.description_docs = u'{}'.format(prompt_command) self.cli.current_buffer.reset(initial_document=Document( self.description_docs, cursor_position=position)) self.cli.request_redraw()
def get_completions( self, document: Document, complete_event: CompleteEvent) -> t.Iterable[Completion]: # TODO: Problem with completing positionals. Solve argument resolution to know in which positional. try: # Split document. text = document.text_before_cursor.lstrip() stripped_len = len(document.text_before_cursor) - len(text) if text.endswith('-h') or text.endswith('--help'): return # 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 isinstance(completer, Completer): 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 # we reached the bottom subcommand. Parse to see if we have to autocomplete an argument or its value else: options = {} params = {} dest_args = {} if not completer: return for arg in completer: if isinstance(arg, dict): arg = [arg] elif isinstance(arg, list): pass else: # to pass command function in dict command definition continue for a in arg: if a.get('argument').startswith('-'): options.update({a.get('argument'): a}) else: params.update({a.get('argument'): a}) if 'dest' in a: dest_args.update({a.get('dest'): a}) else: dest_args.update( {a.get('argument').lstrip('-'): a}) try: words = shlex.split(text) except: return if len(words ) > 0 and words[-1] in options and text.endswith( words[-1]): completer = DshellWordCompleter( words=list(options.keys())) for c in completer.get_completions( document, complete_event): yield c for p in params: if 'choices' in params[p]: completer = DshellWordCompleter( params[p].get("choices")) elif 'completer' in params[p]: completer = params[p].get('completer') else: parser = create_parser( completer, GuessArgumentParser(allow_abbrev=False)) finder = "F:I.N:D.E:R" if document.char_before_cursor == ' ': text = document.text + finder current_word = finder else: text = document.text current_word = document.get_word_before_cursor( WORD=True) namespace = parser.parse_args(shlex.split(text)[1:]) values = dict(namespace._get_kwargs()) # find key related to current_word for k, v in values.items(): if is_iterable_not_string(v): if current_word in v: break else: if v == current_word: break else: k = None v = None # special case for DictAction for dest, arg_def in dest_args.items(): if 'action' in arg_def and arg_def[ 'action'] == DictAction and values[dest]: for k, v in values[dest].items(): # target if k == current_word: resp = ntwrk.get( 'api_1_0.orchestrationresource', view_data={ 'orchestration_id': values['orchestration_id'] }) if resp.ok: needed_target = resp.msg['target'] completer = DshellWordCompleter([ target for target in needed_target if target not in values[dest].keys() ]) for c in completer.get_completions( document, complete_event): yield c return elif current_word in v: completer = arg_def.get( 'completer', None) for c in completer.get_completions( document, complete_event): if c.text not in v: yield c if len(v) == 0 or len( v) == 1 and v[0] == finder: return k = None v = None # get source value if k: nargs = dest_args[k].get('nargs') if nargs and not isinstance(nargs, int): if k not in params and document.char_before_cursor == ' ': if '--' not in words: # next argument may be a positional parameter or an optional argument # if nargs '+' means that at least 1 item must be provided if not (nargs == '+' and v and len(v) - 1 == 0) and k not in params: completer = DshellWordCompleter( words=list(options.keys())) for c in completer.get_completions( document, complete_event): yield c if nargs == '*' or (nargs == '+' and v and len(v) - 1 > 0): yield Completion('--') else: for p in params: if 'choices' in params[p]: completer = DshellWordCompleter( params[p].get("choices")) elif 'completer' in params[p]: completer = params[p].get( 'completer') for c in completer.get_completions( document, complete_event): yield c break elif k in params and document.char_before_cursor == ' ': completer = DshellWordCompleter( words=list(options.keys())) for c in completer.get_completions( document, complete_event): yield c # cursor is in params (not option) it may set an optional parameter elif k in params and '--' not in words: completer = DshellWordCompleter( words=list(options.keys())) for c in completer.get_completions( document, complete_event): yield c if k in dest_args: if 'choices' in dest_args[k]: completer = DshellWordCompleter( dest_args[k].get("choices")) for c in completer.get_completions( document, complete_event): if (v and c.text not in v) or v is None: yield c completer = dest_args[k].get('completer', None) else: completer = None if completer: if isinstance(completer, ResourceCompleter): kwargs = dict(var_filters=values) else: kwargs = {} for c in completer.get_completions( document, complete_event, **kwargs): if (v and c.text not in v) or v is None: yield c else: completer = DshellWordCompleter( words=list(options.keys())) for c in completer.get_completions( document, complete_event): yield c for p in params: if getattr(namespace, p) is None: if 'choices' in params[p]: completer = DshellWordCompleter( params[p].get("choices")) elif 'completer' in params[p]: completer = params[p].get('completer') for c in completer.get_completions( document, complete_event): yield c # No space in the input: behave exactly like `WordCompleter`. else: completer = DshellWordCompleter(list(self.options.keys()), ignore_case=self.ignore_case) for c in completer.get_completions(document, complete_event): yield c except Exception as e: dprint(e)
def create_copy_document(self): """ Create a Document instance and token list that can be used in copy mode. """ data_buffer = self.screen.data_buffer text = [] token_lists = [] first_row = min(data_buffer.keys()) last_row = max(data_buffer.keys()) def token_has_no_background(token): try: # Token looks like ('C', color, bgcolor, bold, underline, ...) return token[2] is None except IndexError: return True for lineno in range(first_row, last_row + 1): token_list = [] row = data_buffer[lineno] max_column = max(row.keys()) if row else 0 # Remove trailing whitespace. (If the background is transparent.) row_data = [row[x] for x in range(0, max_column + 1)] while (row_data and row_data[-1].char.isspace() and token_has_no_background(row_data[-1].token)): row_data.pop() # Walk through row. char_iter = iter(range(len(row_data))) for x in char_iter: c = row[x] text.append(c.char) token_list.append((c.token, c.char)) # Skip next cell when this is a double width character. if c.width == 2: try: next(char_iter) except StopIteration: pass token_lists.append(token_list) text.append('\n') def get_tokens_for_line(lineno): try: return token_lists[lineno] except IndexError: return [] # Calculate cursor position. d = Document(text=''.join(text)) return Document(text=d.text, cursor_position=d.translate_row_col_to_index( row=self.screen.pt_screen.cursor_position.y, col=self.screen.pt_screen.cursor_position.x)), get_tokens_for_line
def get_completions(self, document, completion_event): """ Retrieve all possible completions. Overrides prompt toolkit Completer's class get_completions. Retrieves and then yields any relevant completions provided by initialized subcompleters, based on context given by the document. :param document: a prompt toolkit Document object, upon which the completions are done. It contains the input text and current cursor position. :type Document :rtype None """ text = document.text_before_cursor words = text.split() word = document.get_word_before_cursor(WORD=True) # complete custom BAC commands if len(words) == 0 or words[0] != 'aws': for c in self._nested_completer.get_completions( document, completion_event): yield c return last = words[-1] penultimate = words[-2] if len(words) > 2 else None is_ws = (text[-1] == ' ') # prevent the command from being overwritten by the suggestion if len(words) == 1 and not is_ws: return # complete cached resources (e.g.: --bucket my-bucket) if last in CACHED_OPTIONS: self._cache_completer.completer.words = ( self._cache.get_cached_resource(last)) for c in self._cache_completer.get_completions( Document(), completion_event): if word and not c.text.startswith(word): c.text = ' %s' % c.text yield Completion(c.text, c.start_position, c.display, c.display_meta) return if penultimate and penultimate in CACHED_OPTIONS and word: if not self._cache_completer.completer.words: self._cache_completer.completer.words = ( self._cache.get_cached_resource(penultimate)) for c in self._cache_completer.get_completions( Document(word), completion_event): yield c return if self._query_context: quote, start = self._query_context if (document.cursor_position <= start): if document.cursor_position < start: self._query_context = None self._query_completer.reset() for c in self._query_completer.get_completions( Document(text[start:]), completion_event): yield c elif (not quote and (is_ws or last.startswith(('\'', '\"')))): self._query_context = None self._query_completer.reset() elif quote and quote in text[start:]: pass else: for c in self._query_completer.get_completions( Document(text[start:]), completion_event): yield c return elif last == '--query' and is_ws: positionals = extract_positional_args(words) if len(positionals) < 3: return service, operation = positionals[1:3] self._query_completer.set_shape_dict(service, operation) for c in self._query_completer.get_completions( Document(text_type('')), completion_event): yield c return elif penultimate and penultimate == '--query' and not is_ws: if last.startswith(('\'', '\"')): start = document.cursor_position self._query_context = last[0], start else: start = document.cursor_position - len(last) self._query_context = None, start for c in self._query_completer.get_completions( Document(text[start:]), completion_event): yield c return # autocomplete aws-cli commands for c in self._aws_completer.get_completions(Document(text), completion_event): yield c return
def test_non_empty_text_validator_with_valid_input(user_input): validator = io_utils.not_empty_validator("error message") document = Document(user_input) # If there is input there shouldn't be an exception assert validator.validate(document) is None