def __init__(self, completer, ctx, shell): """Takes instance of xonsh.completer.Completer, the xonsh execution context, and the shell instance itself. """ self.completer = completer self.ctx = ctx self.shell = shell self.hist_suggester = AutoSuggestFromHistory()
def input_loop(self): print("Enter !help for help.") print( "Sending a command is done with Meta+Enter (on Linux Meta = Alt).") while True: li = '' try: bottom = [ f'Connected to {self.cur.get_host()}:{self.cur.get_port()}', f'Caching is {"on" if self.use_cache else "off"}.', f'Log level is {self.log_level}', f'Extended display is {"on" if self.extended_display else "off"}.' ] li = self.session.prompt( self.db + '> ', default=self.default_line, lexer=PygmentsLexer(SqlLexer), auto_suggest=AutoSuggestFromHistory(), bottom_toolbar=' - '.join(bottom), multiline=True, prompt_continuation=self._prompt_continuation, # mouse_support=True ) except KeyboardInterrupt: # CTRL-C continue except EOFError: # CTRL-D break finally: # Whatever happens, reset default prefilled command. self.default_line = '' try: self.exec(li.strip()) except Exception as e: logging.error(e) raise print('Bye.')
def askFinalAction(self) -> "Optional[str]": history = FileHistory(join(histDir, "action")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( list(self._finalActions.keys()), ignore_case=False, match_middle=True, sentence=True, ) while True: action = prompt( "> Select action (ENTER to convert): ", history=history, auto_suggest=auto_suggest, completer=completer, ) if not action: return None if action not in self._finalActions: log.error(f"invalid action: {action}") continue return action
def __init__(self, args): use_asyncio_event_loop() self.args = args self.current_context = self self.teamservers = TeamServers(args['<URL>']) self.completer = STCompleter(self) self.prompt_session = PromptSession( HTML(("[<ansiyellow>" f"{len(self.teamservers.connections)}" "</ansiyellow>] ST ≫ ")), 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)
def main(): enter_main_time = time.time() # invoke in non-standalone mode to gather args ctx = gather_args.main(standalone_mode=False) if not ctx: # called help return # redis client client = Client(ctx.params["h"], ctx.params["p"], ctx.params["n"], config.decode) if not sys.stdin.isatty(): for line in sys.stdin.readlines(): logger.debug(f"[Command stdin] {line}") answer = client.send_command(line, None) write_result(answer) return if ctx.params["cmd"]: # no interactive mode answer = client.send_command(" ".join(ctx.params["cmd"]), None) write_result(answer) logger.warn("[OVER] command executed, exit...") return # Create history file if not exists. if not os.path.exists(HISTORY_FILE): logger.info(f"History file {HISTORY_FILE} not exists, create now...") f = open(HISTORY_FILE, "w+") f.close() style = STYLE # prompt session session = PromptSession( history=FileHistory(HISTORY_FILE), style=style, auto_suggest=AutoSuggestFromHistory(), complete_while_typing=True, ) compile_grammar_bg(session) repl(client, session)
def cmdloop(self, intro=None): """Enters a loop that reads and execute input from user.""" if intro: print(intro) auto_suggest = AutoSuggestFromHistory() self.push = self._push while not builtins.__xonsh__.exit: try: line = self.singleline(auto_suggest=auto_suggest) if not line: self.emptyline() else: raw_line = line line = self.precmd(line) self.default(line, raw_line) except (KeyboardInterrupt, SystemExit): self.reset_buffer() except EOFError: if builtins.__xonsh__.env.get("IGNOREEOF"): print('Use "exit" to leave the shell.', file=sys.stderr) else: break
def __init__(self): self.name = 'main' self.prompt_session = PromptSession( 'ST ≫ ', bottom_toolbar=bottom_toolbar, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, # rprompt=get_rprompt, # style=rprompt_style ) self.contexts = [ Listeners(self.prompt_session), Sessions(self.prompt_session), Modules(self.prompt_session), Stagers(self.prompt_session) ] self.prompt_session.completer = WordCompleter([ctx.name for ctx in self.contexts] + ['exit'], ignore_case=True) self.prompt_session.contexts = self.contexts self.current_context = self
def run(self): self.session = PromptSession(auto_suggest=AutoSuggestFromHistory()) while True: command = self.session.prompt(HTML("<seagreen><b>DLNest>></b></seagreen>")) commandWordList = command.strip().split(' ') if commandWordList[0] == 'run': self.runTrain(commandWordList) elif commandWordList[0] == 'new': self.newProject(commandWordList) elif commandWordList[0] == 'load': self.runAnalyze(commandWordList) elif commandWordList[0] == 'runExp': if len(commandWordList) < 2: continue self.runExp(commandWordList[1]) elif commandWordList[0] == 'release': self.release() elif commandWordList[0] == 'del': self.kill(commandWordList[1]) elif commandWordList[0] == 'suspend': self.suspend(commandWordList[1]) elif commandWordList[0] == 'reload': self.reload(commandWordList[1]) elif commandWordList[0] == 'showDL': self.showDL() elif commandWordList[0] == 'showAN': self.showAN() elif commandWordList[0] == 'show': self.taskInfo() elif commandWordList[0] == 'exit': exit(0) elif commandWordList[0] == 'changeCards': self.changeCards(commandWordList) elif commandWordList[0] == 'showCards': self.showCards() elif commandWordList[0] == "changeDelay": self.changeTimeDelay(commandWordList[1]) else: print("Use \'run\' to start a new training process, use \'new\' to create a project.")
def do_upload_file(user, command, randomuri): # TODO lots of common code source = "" destination = "" if command == "upload-file": style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source except KeyboardInterrupt: return while not os.path.isfile(source): print("File does not exist: %s" % source) source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source destination = session.prompt("Location to upload to: ") else: args = argp(command) source = args.source destination = args.destination try: destination = destination.replace("\\", "\\\\") print("") print("Uploading %s to %s" % (source, destination)) uploadcommand = f"upload-file {source} {destination}" new_task(uploadcommand, user, randomuri) except Exception as e: print("Error with source file: %s" % e) traceback.print_exc()
def initPrompt(its_password, auth, stage): cmd_validator = False cmd_style = pStyle.from_dict({ # User input (default text). '': '#ffffff', # Prompt. 'username': '******', 'at': 'ansigreen', 'colon': '#ffffff', 'pound': '#ffffff', 'host': '#21F521', # bg:#444400 'path': 'ansicyan underline', 'bottom-toolbar': 'ansiblue bg:#ffffff' }) if auth: cmd_msg = [('class:at', ''), ('class:host', ""), ('class:colon', ''), ('class:path', ''), ('class:pound', '')] if stage == 1: cmd_msg.append( ('class:username', "2FA (Two-factor authentication KEY: ")) cmd_validator = passwordValidator() elif stage == 2: cmd_msg.append(('class:username', "PIN Code: ")) else: cmd_msg = [('class:username', "auth"), ('class:at', '@'), ('class:host', 'aaa114-project'), ('class:colon', ':'), ('class:path', '~/'), ('class:pound', '# ')] data = str( auth_prompt.prompt(cmd_msg, style=cmd_style, bottom_toolbar=bottom_toolbar, refresh_interval=0.5, validator=cmd_validator, is_password=its_password, auto_suggest=AutoSuggestFromHistory())) if stage == 1: return data.lower() return data
def start(self): # 开始函数: 命令获取和unicorn实例创建 """ main start function, here we handle the command get loop and unicorn istance creation :return: """ # 创建实例 if not self.emu_instance: self.initialize() # 清空屏幕 utils.clear_terminal() print(utils.get_banner()) print('\n\n\t' + utils.white_bold('Contribute ') + 'https://github.com/iGio90/uDdbg\n') print('\t' + 'Type ' + utils.white_bold_underline('help') + ' to begin.\n') print() while True: # prompt方法 text = prompt(FormattedText([('ansired bold', MENU_APPENDIX + ' ') ]), history=self.history, auto_suggest=AutoSuggestFromHistory()) # only grant the use of empty command to replicate the last command while in cli. No executors if len(text) == 0 and self.last_command is not None: # 解析命令 self.functions_instance.parse_command(self.last_command) continue self.last_command = text # send command to the parser # 解析命令 self.functions_instance.parse_command(text)
def cmdloop(self, intro=None): """Enters a loop that reads and execute input from user.""" if intro: print(intro) _auto_suggest = AutoSuggestFromHistory() while not builtins.__xonsh_exit__: try: token_func, style_cls = self._get_prompt_tokens_and_style() mouse_support = builtins.__xonsh_env__.get('MOUSE_SUPPORT') if builtins.__xonsh_env__.get('AUTO_SUGGEST'): auto_suggest = _auto_suggest else: auto_suggest = None completions_display = builtins.__xonsh_env__.get('COMPLETIONS_DISPLAY') multicolumn = (completions_display == 'multi') completer = None if completions_display == 'none' else self.pt_completer line = prompt( mouse_support=mouse_support, auto_suggest=auto_suggest, get_prompt_tokens=token_func, style=style_cls, completer=completer, lexer=PygmentsLexer(XonshLexer), history=self.history, key_bindings_registry=self.key_bindings_manager.registry, display_completions_in_columns=multicolumn) if not line: self.emptyline() else: line = self.precmd(line) self.default(line) except KeyboardInterrupt: self.reset_buffer() except EOFError: if builtins.__xonsh_env__.get("IGNOREEOF"): print('Use "exit" to leave the shell.') else: break
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
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')) input_spec = None output_spec = None output_codec = None print("\nWelcome to the asn1tools shell!\n") while True: try: line = prompt(u'$ ', completer=completer, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, history=history, on_abort=AbortAction.RETRY) 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))
def shell_main(client): user_home = os.path.expanduser('~') history = FileHistory(os.path.join(user_home, '.bunga-history.txt')) commands = load_commands(client) while True: try: line = prompt_toolkit.prompt(ANSI('\x1b[36m(bunga)\x1b[0m '), completer=FuzzyWordCompleter(commands), complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, complete_style=CompleteStyle.READLINE_LIKE, history=history) except EOFError: break if line: if is_comment(line): continue if line == 'exit': break command, pipe_commands = parse_command(line) try: if command == 'dmesg': output = execute_dmesg(client) else: output = execute_command(client, command) print_output(output, pipe_commands) except ExecuteCommandError as e: print(e.output.decode('utf-8', 'replace'), end='') print_error(e.error) except NotConnectedError: print_error('Not connected.')
def build_cli(self): # TODO: Optimize index suggestion to serve indices options only at the needed position, such as 'from' # set completer indices_list = self.es_executor.indices_list sql_completer = WordCompleter(self.keywords_list + self.functions_list + indices_list, ignore_case=True) # set history if self.history_file == "default": self.history_file = config_location() + "history" history = FileHistory(os.path.expanduser(self.history_file)) # https://stackoverflow.com/a/13726418 denote multiple unused arguments of callback in Python def get_continuation(width, *_): continuation = self.multiline_continuation_char * (width - 1) + " " return [("class:continuation", continuation)] prompt_app = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=sql_completer, complete_while_typing=True, history=history, style=style_factory(self.syntax_style, self.cli_style), prompt_continuation=get_continuation, multiline=es_is_multiline(self), auto_suggest=AutoSuggestFromHistory(), input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(), ) ], tempfile_suffix=".sql", ) return prompt_app
def askFile(self, kind: str, histName: str, varName: str, reading: bool): from shlex import split as shlex_split history = FileHistory(join(histDir, histName)) auto_suggest = AutoSuggestFromHistory() completer_keys = list(self._fsActions.keys()) # Note: isdir and isfile funcs follow sym links, so no worry about links for _path in os.listdir(os.getcwd()): if isdir(_path): continue completer_keys.append(_path) completer = WordCompleter( completer_keys, ignore_case=False, match_middle=False, sentence=True, ) default = getattr(self, varName) while True: filename = prompt( f"> {kind}: ", history=history, auto_suggest=auto_suggest, completer=completer, default=default, ) if not filename: continue parts = shlex_split(filename) if parts[0] in self._fsActions: actionFunc = self._fsActions[parts[0]] try: actionFunc(parts[1:]) except Exception as e: log.exception("") continue setattr(self, varName, filename) return filename raise ValueError(f"{kind} is not given")
def askOutputFormat(self) -> str: history = FileHistory(join(histDir, "format-output")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( writeFormatDescList + Glossary.writeFormats, ignore_case=True, match_middle=True, sentence=True, ) while True: value = prompt( "> Output format: ", history=history, auto_suggest=auto_suggest, completer=completer, default=self._outputFormat, ) if not value: continue plugin = self.pluginByNameOrDesc(value) if plugin: return plugin.name raise ValueError("output format is not given")
def run_interactive_mode(ctx: click.Context, state: State) -> None: """Run interactive mode.""" click.echo("Start interactive mode.") click.echo("You can use {help} command to explain usage.".format( help=click.style(":help", fg="cyan"))) click.echo() style = Style.from_dict({"profile": "gray"}) message = [("class:cli_name", state.cli_name)] if state.profile != "default": message.append(("class:separator", " ")) message.append(("class:profile", state.profile)) message.append(("class:pound", "> ")) repl( ctx, prompt_kwargs={ "message": message, "style": style, "history": FileHistory(str(get_app_dir() / ".repl-history")), "auto_suggest": AutoSuggestFromHistory(), }, )
def _create_buffer(self): """ Create the `Buffer` for the Python input. """ python_buffer = Buffer( name=DEFAULT_BUFFER, complete_while_typing=Condition( lambda: self.complete_while_typing), enable_history_search=Condition( lambda: self.enable_history_search), tempfile_suffix='.py', history=self.history, completer=ThreadedCompleter(self._completer), validator=ConditionalValidator( self._validator, Condition(lambda: self.enable_input_validation)), auto_suggest=ConditionalAutoSuggest( ThreadedAutoSuggest(AutoSuggestFromHistory()), Condition(lambda: self.enable_auto_suggest)), accept_handler=self._accept_handler, on_text_changed=self._on_input_timeout) return python_buffer
def _control(self): time.sleep(1) completer = WordCompleter(words=self._all_methods, ignore_case=True) while self.exit: self.prompt = "{} ".format(str(self.uri) + ">>") cad = prompt(self.prompt, history=FileHistory('history.txt'), completer=completer, auto_suggest=AutoSuggestFromHistory(), mouse_support=True, complete_in_thread=True) if 'robot' in cad or self.name in cad: print("command ", cad, " not executed for precaution") else: args = cad.lower().split(" ") command = args[0] if command.split(".")[0] in self.__dict__: args.append(command) command = "run" if command in self.methods: eval("self." + command + "(*args)") else: print("command {} not found".format(command))
def __init__( self, transfer: Transfer, cmds: Dict[Text, Callable[[List[Text]], Tuple[bytes, Text, Text]]] = None, ) -> None: """Constructor. :transfer: Es la clase con el protocolo. """ self.t = transfer self.cmd = cmds # Crear el indicador. self.p = PromptSession( self.prompt, # Indicador. history=InMemoryHistory(), # Historial en memoria. auto_suggest=AutoSuggestFromHistory(), # Sugerencias basadas en ) # el historial. # Indicador para guardar archivos. self.pf = PromptSession('Ruta donde desea guardar el archivo: ')
def __init__(self): history = InMemoryHistory() os_commandhelper = OSCommandHelper() resource = Resource() os_completer = OSCompleter(os_commandhelper, resource) self.main_buffer = Buffer( accept_action=AcceptAction.RETURN_DOCUMENT, history=history, auto_suggest=AutoSuggestFromHistory(), completer=os_completer, complete_while_typing=True) self.help_buffer = Buffer( is_multiline=True) self.help_buffer.text = "HELP" os_completer.help_buffer = self.help_buffer self.buffers = { DEFAULT_BUFFER: self.main_buffer, 'HELP': self.help_buffer }
def run(self): print(self.getGreetString()) self.loadFilesIntoCompleter() style = Style.from_dict({ 'b': '#00ff00', }) while True: try: text = prompt(HTML('<b>%s</b>' % (self.getPromptString())), style=style, history=self.history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.prompt_completer, complete_while_typing=True, key_bindings=kb) self.executeCommand(text) self.history.append_string(text) except Exception as e: print('Exception') except KeyboardInterrupt: # print('Keyboard interrupted') pass
def query(ws): suggest = ['SELECT', 'WHERE', 'FILTER', '?'] SPARQLCompleter = WordCompleter(suggest, ignore_case=True) #print(SPARQLCompleter.words) net = cmdHandler.loadGraph(".ws/" + ws) entity = net.get_entity().values() fr = net.get_FromNode() for v in entity: SPARQLCompleter.words.append(v) for v in fr: SPARQLCompleter.words.append("/" + v.lower()) shell = True while (shell): query = prompt( 'SPARQL>', history=FileHistory('history/SQLhistory.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SPARQLCompleter, ) if ("exit" not in query): cmdHandler.quering(ws, query) else: shell = False
def create_application(self, full_layout=True): """ makes the application object and the buffers """ layout_manager = LayoutManager(self) if full_layout: layout = layout_manager.create_layout(ExampleLexer, ToolbarLexer) else: layout = layout_manager.create_tutorial_layout() 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(), 'progress': Buffer(is_multiline=False) } 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.style, buffer=writing_buffer, on_input_timeout=self.on_input_timeout, key_bindings_registry=InteractiveKeyBindings(self).registry, layout=layout, buffers=buffers, )
def start(self): completer = WordCompleter(self.commands) # history = InMemoryHistory() history = FileHistory('.client_history') handlers = { 'put': self.handle_put, 'get': self.handle_get, 'connect': self.handle_connect, 'disconnect': self.handle_disconnect, 'exit': self.handle_exit, 'set': self.handle_set, 'batchput': self.handle_batchput, 'batchget': self.handle_batchget } while True: text = prompt('>> ', history=history, completer=completer, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) # parse command cmd = None try: cmd = self.parseInput(text) except ValidationError as e: print(e) self.printUsage() continue # handle command try: if cmd: handlers[cmd[0]](cmd) except Exception as e: print(e)
def main(database): print("\nWelcome to Sqshell, an SQL REPL!\n") con = sqlite3.connect(database) session = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=sql_completer, history=FileHistory(".sqshell_history"), auto_suggest=AutoSuggestFromHistory(), complete_in_thread=True, key_bindings=bindings, multiline=multiline_bool, mouse_support=True, bottom_toolbar=bottom_toolbar, style=style, ) while True: try: message = [ ("class:language", "SQL"), ("class:arrow", " \u279C "), ] text = session.prompt(message, style=style) except KeyboardInterrupt: continue except EOFError: break with con: try: messages = con.execute(text) except Exception as e: print(repr(e)) else: [print(m) for m in messages] print("Goodbye...!")
def cmdloop(self, intro=None): """Better command loop supported by prompt_toolkit override default cmdloop method """ if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro) + '\n') #self.do_look(None) stop = None while not stop: self.pre_loop() if self.cmdqueue: line = self.cmdqueue.pop(0) else: kwargs = dict(history=self.history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.get_completer(), display_completions_in_columns=True, on_abort=AbortAction.RETRY) if self.get_prompt_tokens: kwargs['get_prompt_tokens'] = self.get_prompt_tokens kwargs['style'] = self.prompt_style prompt_str = u'' else: prompt_str = self.prompt try: line = prompt(prompt_str, **kwargs) except EOFError: line = 'EOF' line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop()
def setup_prompt(self): """ This needs to happen after __init__ when the database is fully initialized. """ history = DatabaseHistory() completer = CommandCompleter(self.commands) lexer = PygmentsLexer(CommandLexer.build(self.commands)) style = style_from_pygments_cls(get_style_by_name("monokai")) auto_suggest = AutoSuggestFromHistory() self.prompt = PromptSession( [ ("fg:ansiyellow bold", "(local) "), ("fg:ansimagenta bold", "pwncat"), ("", "$ "), ], completer=completer, lexer=lexer, style=style, auto_suggest=auto_suggest, complete_while_typing=False, history=history, ) self.toolbar = PromptSession( [ ("fg:ansiyellow bold", "(local) "), ("fg:ansimagenta bold", "pwncat"), ("", "$ "), ], completer=completer, lexer=lexer, style=style, auto_suggest=auto_suggest, complete_while_typing=False, prompt_in_toolbar=True, history=history, )
def repl_callback(ctx, param, value): if not value or ctx.resilient_parsing: return prompt_kwargs = { 'completer': KickoffCompleter(ctx.command, compl_blacklist), # simple text can be provided here if colors are not desired 'message': [('class:appname', self._prompt_caption), ('class:suffix', self._prompt_suffix)], 'style': Style.from_dict({ 'appname': 'ansicyan bold', 'suffix': 'ansigray' }), 'enable_system_prompt': True, 'enable_open_in_editor': True, # CTRL+X CTRL+E 'complete_while_typing': True, 'auto_suggest': AutoSuggestFromHistory(), # this works by default, if enabled explicitely complete_while_typing becomes disabled #'enable_history_search': True, # CTRL+R } if self._config.enable_history: prompt_kwargs['history'] = FileHistory( Path('~').expanduser() / f'.{self._prog_name}_history') click_repl.repl(ctx, prompt_kwargs=prompt_kwargs, allow_system_commands=True, allow_internal_commands=False) ctx.exit()
class PromptToolkitCompleter(Completer): """Simple prompt_toolkit Completer object. It just redirects requests to normal Xonsh completer. """ def __init__(self, completer, ctx, shell): """Takes instance of xonsh.completer.Completer, the xonsh execution context, and the shell instance itself. """ self.completer = completer self.ctx = ctx self.shell = shell self.hist_suggester = AutoSuggestFromHistory() def get_completions(self, document, complete_event): """Returns a generator for list of completions.""" env = builtins.__xonsh_env__ should_complete = ( complete_event.completion_requested or env.get('UPDATE_COMPLETIONS_ON_KEYPRESS') ) # Only generate completions when the user hits tab. if not should_complete or self.completer is None: return # generate actual completions line = document.current_line.lstrip() line_ex = builtins.aliases.expand_alias(line) endidx = document.cursor_position_col begidx = (line[:endidx].rfind(' ') + 1 if line[:endidx].rfind(' ') >= 0 else 0) prefix = line[begidx:endidx] expand_offset = len(line_ex) - len(line) # get normal completions completions, l = self.completer.complete(prefix, line_ex, begidx + expand_offset, endidx + expand_offset, self.ctx) # completions from auto suggest sug_comp = None if env.get('AUTO_SUGGEST'): sug_comp = self.suggestion_completion(document, line) if sug_comp is None: pass elif len(completions) == 0: completions = (sug_comp,) else: completions = set(completions) completions.discard(sug_comp) completions = (sug_comp,) + tuple(sorted(completions)) # reserve space, if needed. if len(completions) <= 1: pass elif len(os.path.commonprefix(completions)) <= len(prefix): self.reserve_space() # Find common prefix (strip quoting) c_prefix = os.path.commonprefix([a.strip('\'"') for a in completions]) # Find last split symbol, do not trim the last part while c_prefix: if c_prefix[-1] in r'/\.:@,': break c_prefix = c_prefix[:-1] # yield completions if sug_comp is None: pre = min(document.cursor_position_col - begidx, len(c_prefix)) else: pre = len(c_prefix) for comp in completions: # do not display quote disp = comp[pre:].strip('\'"') yield Completion(comp, -l, display=disp) def suggestion_completion(self, document, line): """Provides a completion based on the current auto-suggestion.""" cli = self.shell.prompter.cli sug = self.hist_suggester.get_suggestion(cli, cli.current_buffer, document) if sug is None: return None comp, _, _ = sug.text.partition(' ') _, _, prev = line.rpartition(' ') return prev + comp def reserve_space(self): cli = builtins.__xonsh_shell__.shell.prompter.cli window = cli.application.layout.children[0].content.children[1] if window and window.render_info: h = window.render_info.content_height r = builtins.__xonsh_env__.get('COMPLETIONS_MENU_ROWS') size = h + r def comp_height(cli): # If there is an autocompletion menu to be shown, make sure that o # layout has at least a minimal height in order to display it. if not cli.is_done: return LayoutDimension(min=size) else: return LayoutDimension() window._height = comp_height