Python prompt_toolkit.auto_suggest.AutoSuggestFromHistory() Examples
The following are 23
code examples of prompt_toolkit.auto_suggest.AutoSuggestFromHistory().
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.auto_suggest
, or try the search function
.
Example #1
Source File: prompt.py From aq with MIT License | 6 votes |
def __init__(self, parser, engine, options=None): self.parser = parser self.engine = engine self.options = options if options is not None else {} util.ensure_data_dir_exists() application = create_prompt_application( message='> ', lexer=PygmentsLexer(SqlLexer), history=FileHistory(os.path.expanduser('~/.aq/history')), completer=AqCompleter(schemas=engine.available_schemas, tables=engine.available_tables), auto_suggest=AutoSuggestFromHistory(), validator=QueryValidator(parser), on_abort=AbortAction.RETRY, ) loop = create_eventloop() self.cli = CommandLineInterface(application=application, eventloop=loop) self.patch_context = self.cli.patch_stdout_context()
Example #2
Source File: main.py From kafka-shell with Apache License 2.0 | 6 votes |
def main(): settings = Settings() bindings = get_bindings(settings) executor = Executor(settings) toolbar = Toolbar(settings) completer = KafkaCompleter(settings) if settings.enable_auto_complete else None suggester = AutoSuggestFromHistory() if settings.enable_auto_suggest else None history = ThreadedHistory(FileHistory(get_user_history_path())) if settings.enable_history else InMemoryHistory() session = PromptSession(completer=completer, style=style, bottom_toolbar=toolbar.handler, key_bindings=bindings, history=history, include_default_pygments_style=False) while True: try: command = session.prompt([("class:operator", "> ")], auto_suggest=suggester) except KeyboardInterrupt: continue except EOFError: break else: executor.execute(command) settings.save_settings()
Example #3
Source File: wmdb.py From WitnessMe with GNU General Public License v3.0 | 6 votes |
def __init__(self, db_path): self.db_path = db_path self.completer = WMCompleter(self) self.signatures = Signatures() self.prompt_session = PromptSession( HTML("WMDB ≫ "), #bottom_toolbar=functools.partial(bottom_toolbar, ts=self.teamservers), completer=self.completer, complete_in_thread=True, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), #rprompt=get_rprompt(False), #style=example_style, search_ignore_case=True )
Example #4
Source File: prompt.py From HomePWN with GNU General Public License v3.0 | 6 votes |
def prompt(commands, module=None): """Launch the prompt with the given commands Args: commands ([str]): List of commands to autocomplete module (str, optional): Name of the module. Defaults to None. Returns: prompt session: Session of the promt """ default_prompt = "homePwn" color_default_prompt = ColorSelected().theme.primary warn = ColorSelected().theme.warn confirm = ColorSelected().theme.confirm html = HTML(f"<bold><{color_default_prompt}>{default_prompt} >></{color_default_prompt}></bold>") if module: html = HTML(f"<bold><{color_default_prompt}>{default_prompt}</{color_default_prompt}> (<{warn}>{module}</{warn}>) <{confirm}>>></{confirm}></bold> ") data = session.prompt( html, completer= CustomCompleter(commands), complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) return data
Example #5
Source File: main.py From Slack-Gitsin with GNU General Public License v3.0 | 6 votes |
def main(): """ Start the Slack Client """ os.system("clear; figlet 'Slack Gitsin' | lolcat") history = FileHistory(os.path.expanduser("~/.slackHistory")) while True: text = prompt("slack> ", history=history, auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, style=DocumentStyle, completer=Completer(fuzzy_match=False, text_utils=TextUtils()), complete_while_typing=Always(), get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, key_bindings_registry=manager.registry, accept_action=AcceptAction.RETURN_DOCUMENT ) slack = Slack(text) slack.run_command()
Example #6
Source File: layout.py From hummingbot with Apache License 2.0 | 5 votes |
def create_input_field(lexer=None, completer: Completer = None): return TextArea( height=10, prompt='>>> ', style='class:input-field', multiline=False, focus_on_click=True, lexer=lexer, auto_suggest=AutoSuggestFromHistory(), completer=completer, complete_while_typing=True, )
Example #7
Source File: auto-suggestion.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def main(): # Create some history first. (Easy for testing.) history = InMemoryHistory() history.append_string("import os") history.append_string('print("hello")') history.append_string('print("world")') history.append_string("import path") # Print help. print("This CLI has fish-style auto-suggestion enable.") print('Type for instance "pri", then you\'ll see a suggestion.') print("Press the right arrow to insert the suggestion.") print("Press Control-C to retry. Control-D to exit.") print() session = PromptSession( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, ) while True: try: text = session.prompt("Say something: ") except KeyboardInterrupt: pass # Ctrl-C pressed. Try again. else: break print("You said: %s" % text)
Example #8
Source File: app.py From aws-shell with Apache License 2.0 | 5 votes |
def create_buffer(self, completer, history): return Buffer( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT)
Example #9
Source File: app.py From azure-cli-shell with MIT License | 5 votes |
def create_application(self, full_layout=True): """ makes the application object and the buffers """ if full_layout: layout = create_layout(self.lexer, ExampleLexer, ToolbarLexer) else: layout = create_tutorial_layout(self.lexer) buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'description': Buffer(is_multiline=True, read_only=True), 'parameter' : Buffer(is_multiline=True, read_only=True), 'examples' : Buffer(is_multiline=True, read_only=True), 'bottom_toolbar' : Buffer(is_multiline=True), 'example_line' : Buffer(is_multiline=True), 'default_values' : Buffer(), 'symbols' : Buffer() } writing_buffer = Buffer( history=self.history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always() ) return Application( mouse_support=False, style=self.styles, buffer=writing_buffer, on_input_timeout=self.on_input_timeout, key_bindings_registry=registry, layout=layout, buffers=buffers, )
Example #10
Source File: prompt.py From fuzzowski with GNU General Public License v2.0 | 5 votes |
def __init__(self) -> None: self.commands = self.get_commands() self.cmd_handler = CommandHandler(self.commands) self.completer = CommandCompleter(self.commands) self.style = self.get_style() self._break = False self.prompt_session = PromptSession(completer=self.completer, style=self.style, bottom_toolbar=self.bottom_toolbar, auto_suggest=AutoSuggestFromHistory()) super(CommandPrompt, self).__init__() # --------------------------------------------------------------- #
Example #11
Source File: __init__.py From asn1tools with MIT License | 5 votes |
def _do_shell(_args): commands = ['compile', 'convert', 'help', 'exit'] completer = WordCompleter(commands, WORD=True) user_home = os.path.expanduser('~') history = FileHistory(os.path.join(user_home, '.asn1tools-history.txt')) session = PromptSession(completer=completer, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, history=history) input_spec = None output_spec = None output_codec = None print("\nWelcome to the asn1tools shell!\n") while True: try: line = session.prompt(u'$ ') except EOFError: return line = line.strip() if line: if line.startswith('compile'): input_spec, output_spec, output_codec = _handle_command_compile(line) elif line.startswith('convert'): _handle_command_convert(line, input_spec, output_spec, output_codec) elif line == 'help': _handle_command_help() elif line == 'exit': return else: print('{}: command not found'.format(line))
Example #12
Source File: maininterface.py From polymorph with GNU General Public License v2.0 | 5 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['capture', 'spoof', 'clear', 'import']) history = FileHistory(self._polym_path + '/.minterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold><red>PH</red> > </bold>"), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in ["capture", "c"]: self._capture(command) elif command[0] in ["spoof", "s"]: self._spoof(command) elif command[0] in ["import", "i"]: self._import(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #13
Source File: tlistinterface.py From polymorph with GNU General Public License v2.0 | 5 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'dissect', 'template', 'wireshark', 'clear', 'back']) history = FileHistory(self._polym_path + '/.tlinterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:<red>cap</red> > </bold>"), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["show", "s"]: self._show(command) elif command[0] == "dissect": self._dissect(command) elif command[0] in ["template", "t"]: self._template(command) elif command[0] in ["wireshark", "w"]: self._wireshark(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #14
Source File: layerinterface.py From polymorph with GNU General Public License v2.0 | 5 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'name', 'field', 'fields', 'dump', 'recalculate', 'clear', 'back']) history = FileHistory(self._polym_path + '/.linterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:cap/t%d/<red>%s</red> > </bold>" % (self._tindex, self._l.name)), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue # Argument parsing command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["s", "show"]: self._show(command) elif command[0] == "name": self._name(command) elif command[0] in ["field", "f"]: self._field(command) elif command[0] in ["fields", "fs"]: self._fields(command) elif command[0] in ["dump", "d"]: self._dump(command) elif command[0] in ["recalculate", "r"]: self._recalculate(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #15
Source File: shell.py From we-get with MIT License | 5 votes |
def shell(self, items, pargs): self.pargs = pargs self.items = items stdout.write( '\n') # When the fetching messege ends need to add \n after \r. self.prompt_show_items() history = InMemoryHistory() session = PromptSession() if PROMPT_TOOLKIT_V2 else None while True: kwargs = dict( history=history, auto_suggest=AutoSuggestFromHistory(), completer=WGCompleter(list(self.items.keys())), style=we_get_prompt_style ) try: p = prompt(u'we-get > ', **kwargs) except TypeError as e: log.debug('{}:{}'.format(type(e), e)) kwargs.pop('history') if PROMPT_TOOLKIT_V2: p = session.prompt(u'we-get > ', **kwargs) else: p = prompt(u'we-get > ', **kwargs) if self.prompt_no_command(p): continue elif self.prompt_is_single_command(p): command = p args = None else: _ = p.split() command = _[0] _.pop(0) args = ' '.join(_) if not self.prompt_verify_command(command, args): continue elif not self.prompt_parse_command(command, args): break
Example #16
Source File: prompt.py From Pytify with MIT License | 5 votes |
def custom_prompt(currentSong): session = PromptSession( message=get_prompt, history=history(), auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, bottom_toolbar=get_bottom_toolbar(currentSong), completer=completer(), complete_while_typing=True, complete_in_thread=True, style=style ) return session.prompt()
Example #17
Source File: console.py From python-sploitkit with GNU Affero General Public License v3.0 | 4 votes |
def start(self): """ Start looping with console's session prompt. """ reexec = None self._reset_logname() self.logger.debug("Starting {}[{}]".format(self.__class__.__name__, id(self))) # execute attached module's pre-load function if relevant self._run_if_defined("preload") # now start the console loop while True: self._reset_logname() try: _ = reexec if reexec is not None else \ self._session.prompt( auto_suggest=AutoSuggestFromHistory(), #bottom_toolbar="This is\na multiline toolbar", # important note: this disables terminal scrolling #mouse_support=True, ) reexec = None Console._recorder.save(_) if not self.run(_): break # console run aborted except ConsoleDuplicate as e: # stop raising duplicate when reaching a console with a # different level, then reset associated commands not to rerun # the erroneous one from the context of the just-exited console if self == e.higher: reexec = e.cmd self.reset() continue self._close() # reraise up to the higher (level) console raise e except EOFError: Console._recorder.save("exit") break except (KeyboardInterrupt, ValueError): continue # execute attached module's post-load function if relevant self._run_if_defined("postload") # gracefully close and chain this console instance self._close() return self
Example #18
Source File: rtxmlrpc.py From pyrocore with GNU General Public License v2.0 | 4 votes |
def do_repl(self): """REPL for rTorrent XMLRPC commands.""" from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter self.options.quiet = False proxy = self.open() ps1 = proxy.session.name() + u'> ' words = ['help', 'stats', 'exit'] words += [x + '=' for x in proxy.system.listMethods()] history_file = os.path.join(config.config_dir, '.rtxmlrpc_history') while True: try: try: cmd = prompt(ps1, completer=WordCompleter(words), auto_suggest=AutoSuggestFromHistory(), history=FileHistory(history_file)) except KeyboardInterrupt: cmd = '' if not cmd: print("Enter '?' or 'help' for usage information, 'Ctrl-D' to exit.") if cmd in {'?', 'help'}: self.repl_usage() continue elif cmd in {'', 'stats'}: print(repr(proxy).split(None, 1)[1]) continue elif cmd in {'exit'}: raise EOFError() try: method, raw_args = cmd.split('=', 1) except ValueError: print("ERROR: '=' not found") continue raw_args = raw_args.split(',') args = self.cooked(raw_args) self.execute(proxy, method, args) except EOFError: print('Bye from {!r}'.format(proxy)) break
Example #19
Source File: main.py From pymux with BSD 3-Clause "New" or "Revised" License | 4 votes |
def __init__(self, pymux, input, output, color_depth, connection): self.pymux = pymux self.input = input self.output = output self.color_depth = color_depth self.connection = connection #: True when the prefix key (Ctrl-B) has been pressed. self.has_prefix = False #: Error/info message. self.message = None # When a "confirm-before" command is running, # Show this text in the command bar. When confirmed, execute # confirm_command. self.confirm_text = None self.confirm_command = None # When a "command-prompt" command is running. self.prompt_text = None self.prompt_command = None # Popup. self.display_popup = False # Input buffers. self.command_buffer = Buffer( name=COMMAND, accept_handler=self._handle_command, auto_suggest=AutoSuggestFromHistory(), multiline=False, complete_while_typing=False, completer=create_command_completer(pymux)) self.prompt_buffer = Buffer( name=PROMPT, accept_handler=self._handle_prompt_command, multiline=False, auto_suggest=AutoSuggestFromHistory()) # Layout. self.layout_manager = LayoutManager(self.pymux, self) self.app = self._create_app() # Clear write positions right before rendering. (They are populated # during rendering). def before_render(_): self.layout_manager.reset_write_positions() self.app.before_render += before_render
Example #20
Source File: kubeshell.py From kube-shell with Apache License 2.0 | 4 votes |
def run_cli(self): def get_title(): return "kube-shell" logger.info("running kube-shell event loop") if not os.path.exists(os.path.expanduser(kubeconfig_filepath)): click.secho('Kube-shell uses {0} for server side completion. Could not find {0}. ' 'Server side completion functionality may not work.'.format(kubeconfig_filepath), fg='red', blink=True, bold=True) while True: global inline_help try: Kubeshell.clustername, Kubeshell.user, Kubeshell.namespace = KubeConfig.parse_kubeconfig() except: logger.error("unable to parse {} %s".format(kubeconfig_filepath), exc_info=1) completer.set_namespace(self.namespace) try: user_input = prompt('kube-shell> ', history=self.history, auto_suggest=AutoSuggestFromHistory(), style=StyleFactory("vim").style, lexer=KubectlLexer, get_title=get_title, enable_history_search=False, get_bottom_toolbar_tokens=self.toolbar.handler, vi_mode=True, key_bindings_registry=registry, completer=completer) except (EOFError, KeyboardInterrupt): sys.exit() if user_input == "clear": click.clear() elif user_input == "exit": sys.exit() # if execute shell command then strip "!" if user_input.startswith("!"): user_input = user_input[1:] if user_input: if '-o' in user_input and 'json' in user_input: user_input += ' | pygmentize -l json' p = subprocess.Popen(user_input, shell=True) p.communicate()
Example #21
Source File: main.py From athenacli with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _build_prompt_app(self, history): key_bindings = cli_bindings(self) def get_message(): prompt = self.get_prompt(self.prompt) if len(prompt) > self.MAX_LEN_PROMPT: prompt = self.get_prompt('\\r:\\d> ') return [('class:prompt', prompt)] def get_continuation(width, line_number, is_soft_wrap): continuation = ' ' * (width -1) + ' ' return [('class:continuation', continuation)] def show_suggestion_tip(): return self.iterations < 2 get_toolbar_tokens = create_toolbar_tokens_func( self, show_suggestion_tip) with self._completer_lock: if self.key_bindings == 'vi': editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS self.prompt_app = PromptSession( lexer=PygmentsLexer(Lexer), reserve_space_for_menu=self.get_reserved_space(), message=get_message, prompt_continuation=get_continuation, bottom_toolbar=get_toolbar_tokens, complete_style=CompleteStyle.COLUMN, input_processors=[ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() )], tempfile_suffix='.sql', completer=DynamicCompleter(lambda: self.completer), history=history, auto_suggest=AutoSuggestFromHistory(), complete_while_typing=True, multiline=cli_is_multiline(self), style=style_factory(self.syntax_style, self.cli_style), include_default_pygments_style=False, key_bindings=key_bindings, enable_open_in_editor=True, enable_system_prompt=True, editing_mode=editing_mode, search_ignore_case=True )
Example #22
Source File: fieldinterface.py From polymorph with GNU General Public License v2.0 | 4 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['value', 'type', 'show', 'name', 'slice', 'custom', 'size', 'dump', 'clear', 'back']) history = FileHistory(self._polym_path + '/.finterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:cap/t%d/%s/<red>%s</red> > </bold>" % (self._tindex, self._lname, self._f.name)), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ['t', 'type']: self._type(command) elif command[0] in ['v', 'value']: self._value(command) elif command[0] in ['s', 'show']: self._show(command) elif command[0] == 'name': self._name(command) elif command[0] == "slice": print(self._f.slice, '\n') elif command[0] == "custom": self._custom(command) elif command[0] == "size": print(self._f.size, '\n') elif command[0] in ['d', 'dump']: Interface.color_dump(self._f.raw, self._f.slice.start, self._f.slice.stop) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #23
Source File: templateinterface.py From polymorph with GNU General Public License v2.0 | 4 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'name', 'layer', 'dump', 'layers', 'preconditions', 'postconditions', 'executions', 'intercept', 'timestamp', 'version', 'save', 'description', 'spoof', 'clear', 'back']) # Initialization of the command history history = FileHistory(join(self._polym_path, '.tinterface_history')) session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:cap/<red>t%d</red> > </bold>" % self._index), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] == "name": self._name(command) elif command[0] in ["dump", "d"]: self._dump(command) elif command[0] in ["layer", "l"]: self._layer(command) elif command[0] in ['precs', 'preconditions']: self._conditions(command, 'preconditions') elif command[0] in ['posts', 'postconditions']: self._conditions(command, 'postconditions') elif command[0] in ['execs', 'executions']: self._conditions(command, 'executions') elif command[0] in ["show", "s"]: self._show(command) elif command[0] in ["intercept", "i"]: self._intercept(command) elif command[0] in ["layers", "ls"]: self._layers(command) elif command[0] == "timestamp": print(self._t.timestamp, '\n') elif command[0] == "version": self._version(command) elif command[0] in ['desc', 'description']: self._description(command) elif command[0] == "save": self._save(command) elif command[0] in ["spoof"]: self._spoof(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()