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()
def __init__(self, **kwargs): super().__init__(**kwargs) if ON_WINDOWS: winutils.enable_virtual_terminal_processing() self._first_prompt = True self.history = ThreadedHistory(PromptToolkitHistory()) self.prompter = PromptSession(history=self.history) self.prompt_formatter = PTKPromptFormatter(self.prompter) self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self) self.key_bindings = load_xonsh_bindings() # Store original `_history_matches` in case we need to restore it self._history_matches_orig = self.prompter.default_buffer._history_matches # This assumes that PromptToolkitShell is a singleton events.on_ptk_create.fire( prompter=self.prompter, history=self.history, completer=self.pt_completer, bindings=self.key_bindings, ) # Goes at the end, since _MergedKeyBindings objects do not have # an add() function, which is necessary for on_ptk_create events self.key_bindings = merge_key_bindings( [self.key_bindings, load_emacs_shift_selection_bindings()])
def __init__(self, **kwargs): ptk_args = kwargs.pop("ptk_args", {}) super().__init__(**kwargs) if ON_WINDOWS: winutils.enable_virtual_terminal_processing() self._first_prompt = True self.history = ThreadedHistory(PromptToolkitHistory()) ptk_args.setdefault("history", self.history) if not XSH.env.get("XONSH_COPY_ON_DELETE", False): disable_copy_on_deletion() if HAVE_SYS_CLIPBOARD: ptk_args.setdefault("clipboard", PyperclipClipboard()) self.prompter: PromptSession = PromptSession(**ptk_args) self.prompt_formatter = PTKPromptFormatter(self) self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self) ptk_bindings = self.prompter.app.key_bindings self.key_bindings = load_xonsh_bindings(ptk_bindings) self._overrides_deprecation_warning_shown = False # Store original `_history_matches` in case we need to restore it self._history_matches_orig = self.prompter.default_buffer._history_matches # This assumes that PromptToolkitShell is a singleton events.on_ptk_create.fire( prompter=self.prompter, history=self.history, completer=self.pt_completer, bindings=self.key_bindings, ) # Goes at the end, since _MergedKeyBindings objects do not have # an add() function, which is necessary for on_ptk_create events self.key_bindings = merge_key_bindings( [self.key_bindings, load_emacs_shift_selection_bindings()] )
def __init__(self, PtPromptSession=PromptSession, history=None, pt_print=print_formatted_text, oop_engine=False): self.config = settings.Settings.load() if history is None: self.history = ThreadedHistory( FileHistory(os.path.expanduser(self.config.history_path))) else: self.history = history self.PtPromptSession = PtPromptSession self.pt_print = pt_print self.oop_engine = oop_engine
def main(): print( 'Asynchronous loading of history. Notice that the up-arrow will work ' 'for as far as the completions are loaded.\n' 'Even when the input is accepted, loading will continue in the ' 'background and when the next prompt is displayed.\n') our_history = ThreadedHistory(SlowHistory()) # The history needs to be passed to the `PromptSession`. It can't be passed # to the `prompt` call because only one history can be used during a # session. session = PromptSession(history=our_history) while True: text = session.prompt('Say something: ') print('You said: %s' % text)
def __init__(self, config, engine, PtPromptSession, pt_print=print_formatted_text): self.config = config self.engine = engine self.pt_print = pt_print bindings = self.setup_key_bindings() lexer = PygmentsLexer(PtgHaskellLexer) history = ThreadedHistory( FileHistory(os.path.expanduser(config.history_path))) pg_style = style_from_pygments_cls(get_style_by_name(config.style)) bottom_toolbar_style = Style.from_dict({ 'bottom-toolbar': config.type_bar_style, 'bottom-toolbar.text': config.type_bar_text_style }) style = merge_styles([pg_style, bottom_toolbar_style]) self._psession = PtPromptSession( ":", lexer=lexer, vi_mode=config.vi_mode, multiline=True, # enable_open_in_editor=True, # Handle this manually key_bindings=bindings, history=history, tempfile_suffix=".hs", style=style, complete_while_typing=False, completer=completer.make_completer(engine, config), enable_suspend=True, prompt_continuation=default_continuation, bottom_toolbar=self.bottom_toolbar if config.type_bar_enabled else None) self._psession.message = self.in_prompt_message if config.vi_mode: vimcursor.setup_vim_cursor() self._cur_lineno = 1 #len(self._psession.history.get_strings())+1 self.threadpool = ThreadPool(processes=1) self.bottom_text = None self.last_cursor_word = None
def __init__(self, **kwargs): super().__init__(**kwargs) if ON_WINDOWS: winutils.enable_virtual_terminal_processing() self._first_prompt = True self.history = ThreadedHistory(PromptToolkitHistory()) self.prompter = PromptSession(history=self.history) self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self) self.key_bindings = KeyBindings() load_xonsh_bindings(self.key_bindings) # This assumes that PromptToolkit2Shell is a singleton events.on_ptk_create.fire( prompter=self.prompter, history=self.history, completer=self.pt_completer, bindings=self.key_bindings, )
def __init__(self, PtPromptSession=PromptSession, history=None, pt_print=print_detect_ansi, oop_engine=False): if isinstance(threading.current_thread(), threading._MainThread): signal.signal(signal.SIGINT, int_handler) self.config = settings.Settings.load() if self.config.settings_path: print("Using settings file %s" % self.config.settings_path) if history is None: self.history = ThreadedHistory( FileHistory(os.path.expanduser(self.config.history_path))) else: self.history = history self.PtPromptSession = PtPromptSession self.pt_print = pt_print self.oop_engine = oop_engine
def test_threaded_in_memory_history(): # Threaded in memory history is not useful. But testing it anyway, just to # see whether everything plays nicely together. history = ThreadedHistory(InMemoryHistory()) history.append_string("hello") history.append_string("world") # Newest should yield first. assert _call_history_load(history) == ["world", "hello"] # Test another call. assert _call_history_load(history) == ["world", "hello"] history.append_string("test3") assert _call_history_load(history) == ["test3", "world", "hello"] # Passing history as a parameter. history2 = ThreadedHistory(InMemoryHistory(["abc", "def"])) assert _call_history_load(history2) == ["def", "abc"]
def test_threaded_file_history(tmpdir): histfile = tmpdir.join("history") history = ThreadedHistory(FileHistory(histfile)) history.append_string("hello") history.append_string("world") # Newest should yield first. assert _call_history_load(history) == ["world", "hello"] # Test another call. assert _call_history_load(history) == ["world", "hello"] history.append_string("test3") assert _call_history_load(history) == ["test3", "world", "hello"] # Create another history instance pointing to the same file. history2 = ThreadedHistory(FileHistory(histfile)) assert _call_history_load(history2) == ["test3", "world", "hello"]
def __init__(self, **kwargs): super().__init__(**kwargs) if ON_WINDOWS: winutils.enable_virtual_terminal_processing() self._first_prompt = True self.history = ThreadedHistory(PromptToolkitHistory()) self.prompter = PromptSession(history=self.history) self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self) self.key_bindings = merge_key_bindings( [load_xonsh_bindings(), load_emacs_shift_selection_bindings()]) # Store original `_history_matches` in case we need to restore it self._history_matches_orig = self.prompter.default_buffer._history_matches # This assumes that PromptToolkitShell is a singleton events.on_ptk_create.fire( prompter=self.prompter, history=self.history, completer=self.pt_completer, bindings=self.key_bindings, )
def __init__( self, get_globals=None, get_locals=None, history_filename=None, vi_mode=False, input=None, output=None, color_depth=None, # For internal use. extra_key_bindings=None, _completer=None, _validator=None, _lexer=None, _extra_buffer_processors=None, _extra_layout_body=None, _extra_toolbars=None, _input_buffer_height=None): self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self._completer = _completer or PythonCompleter( self.get_globals, self.get_locals) self._validator = _validator or PythonValidator( self.get_compiler_flags) self._lexer = _lexer or PygmentsLexer(PythonLexer) if history_filename: self.history = ThreadedHistory(FileHistory(history_filename)) else: self.history = InMemoryHistory() self._input_buffer_height = _input_buffer_height self._extra_layout_body = _extra_layout_body or [] self._extra_toolbars = _extra_toolbars or [] self._extra_buffer_processors = _extra_buffer_processors or [] self.extra_key_bindings = extra_key_bindings or KeyBindings() # Settings. self.show_signature = False self.show_docstring = False self.show_meta_enter_message = True self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN self.completion_menu_scroll_offset = 1 self.show_line_numbers = False self.show_status_bar = True self.wrap_lines = True self.complete_while_typing = True self.paste_mode = False # When True, don't insert whitespace after newline. self.confirm_exit = True # Ask for confirmation when Control-D is pressed. self.accept_input_on_enter = 2 # Accept when pressing Enter 'n' times. # 'None' means that meta-enter is always required. self.enable_open_in_editor = True self.enable_system_bindings = True self.enable_input_validation = True self.enable_auto_suggest = False self.enable_mouse_support = False self.enable_history_search = False # When True, like readline, going # back in history will filter the # history on the records starting # with the current input. self.enable_syntax_highlighting = True self.highlight_matching_parenthesis = False self.show_sidebar = False # Currently show the sidebar. self.show_sidebar_help = True # When the sidebar is visible, also show the help text. self.show_exit_confirmation = False # Currently show 'Do you really want to exit?' self.terminal_title = None # The title to be displayed in the terminal. (None or string.) self.exit_message = 'Do you really want to exit?' self.insert_blank_line_after_output = True # (For the REPL.) # The buffers. self.default_buffer = self._create_buffer() self.search_buffer = Buffer() self.docstring_buffer = Buffer(read_only=True) # Tokens to be shown at the prompt. self.prompt_style = 'classic' # The currently active style. self.all_prompt_styles = { # Styles selectable from the menu. 'ipython': IPythonPrompt(self), 'classic': ClassicPrompt(), } self.get_input_prompt = lambda: \ self.all_prompt_styles[self.prompt_style].in_prompt() self.get_output_prompt = lambda: \ self.all_prompt_styles[self.prompt_style].out_prompt() #: Load styles. self.code_styles = get_all_code_styles() self.ui_styles = get_all_ui_styles() self._current_code_style_name = 'default' self._current_ui_style_name = 'default' if is_windows(): self._current_code_style_name = 'win32' self._current_style = self._generate_style() # Options to be configurable from the sidebar. self.options = self._create_options() self.selected_option_index = 0 #: Incremeting integer counting the current statement. self.current_statement_index = 1 # Code signatures. (This is set asynchronously after a timeout.) self.signatures = [] # Boolean indicating whether we have a signatures thread running. # (Never run more than one at the same time.) self._get_signatures_thread_running = False self.output = output or create_output() self.input = input or create_input(sys.stdin) self.app = self._create_application(color_depth) if vi_mode: self.app.editing_mode = EditingMode.VI
def __init__( self, get_globals: Optional[_GetNamespace] = None, get_locals: Optional[_GetNamespace] = None, history_filename: Optional[str] = None, vi_mode: bool = False, color_depth: Optional[ColorDepth] = None, # Input/output. input: Optional[Input] = None, output: Optional[Output] = None, # For internal use. extra_key_bindings: Optional[KeyBindings] = None, _completer: Optional[Completer] = None, _validator: Optional[Validator] = None, _lexer: Optional[Lexer] = None, _extra_buffer_processors=None, _extra_layout_body=None, _extra_toolbars=None, _input_buffer_height=None, ) -> None: self.get_globals: _GetNamespace = get_globals or (lambda: {}) self.get_locals: _GetNamespace = get_locals or self.get_globals self._completer = _completer or FuzzyCompleter( PythonCompleter( self.get_globals, self.get_locals, lambda: self.enable_dictionary_completion, ), enable_fuzzy=Condition(lambda: self.enable_fuzzy_completion), ) self._validator = _validator or PythonValidator( self.get_compiler_flags) self._lexer = _lexer or PygmentsLexer(PythonLexer) self.history: History if history_filename: self.history = ThreadedHistory(FileHistory(history_filename)) else: self.history = InMemoryHistory() self._input_buffer_height = _input_buffer_height self._extra_layout_body = _extra_layout_body or [] self._extra_toolbars = _extra_toolbars or [] self._extra_buffer_processors = _extra_buffer_processors or [] self.extra_key_bindings = extra_key_bindings or KeyBindings() # Settings. self.title: AnyFormattedText = "" self.show_signature: bool = False self.show_docstring: bool = False self.show_meta_enter_message: bool = True self.completion_visualisation: CompletionVisualisation = CompletionVisualisation.MULTI_COLUMN self.completion_menu_scroll_offset: int = 1 self.show_line_numbers: bool = False self.show_status_bar: bool = True self.wrap_lines: bool = True self.complete_while_typing: bool = True self.paste_mode: bool = False # When True, don't insert whitespace after newline. self.confirm_exit: bool = True # Ask for confirmation when Control-D is pressed. self.accept_input_on_enter: int = 2 # Accept when pressing Enter 'n' times. # 'None' means that meta-enter is always required. self.enable_open_in_editor: bool = True self.enable_system_bindings: bool = True self.enable_input_validation: bool = True self.enable_auto_suggest: bool = False self.enable_mouse_support: bool = False self.enable_history_search: bool = False # When True, like readline, going # back in history will filter the # history on the records starting # with the current input. self.enable_syntax_highlighting: bool = True self.enable_fuzzy_completion: bool = False self.enable_dictionary_completion: bool = False self.swap_light_and_dark: bool = False self.highlight_matching_parenthesis: bool = False self.show_sidebar: bool = False # Currently show the sidebar. # When the sidebar is visible, also show the help text. self.show_sidebar_help: bool = True # Currently show 'Do you really want to exit?' self.show_exit_confirmation: bool = False # The title to be displayed in the terminal. (None or string.) self.terminal_title: Optional[str] = None self.exit_message: str = "Do you really want to exit?" self.insert_blank_line_after_output: bool = True # (For the REPL.) # The buffers. self.default_buffer = self._create_buffer() self.search_buffer: Buffer = Buffer() self.docstring_buffer: Buffer = Buffer(read_only=True) # Tokens to be shown at the prompt. self.prompt_style: str = "classic" # The currently active style. # Styles selectable from the menu. self.all_prompt_styles: Dict[str, PromptStyle] = { "ipython": IPythonPrompt(self), "classic": ClassicPrompt(), } self.get_input_prompt = lambda: self.all_prompt_styles[ self.prompt_style].in_prompt() self.get_output_prompt = lambda: self.all_prompt_styles[ self.prompt_style].out_prompt() #: Load styles. self.code_styles: Dict[str, BaseStyle] = get_all_code_styles() self.ui_styles = get_all_ui_styles() self._current_code_style_name: str = "default" self._current_ui_style_name: str = "default" if is_windows(): self._current_code_style_name = "win32" self._current_style = self._generate_style() self.color_depth: ColorDepth = color_depth or ColorDepth.default() self.max_brightness: float = 1.0 self.min_brightness: float = 0.0 # Options to be configurable from the sidebar. self.options = self._create_options() self.selected_option_index: int = 0 #: Incremeting integer counting the current statement. self.current_statement_index: int = 1 # Code signatures. (This is set asynchronously after a timeout.) self.signatures: List[Any] = [] # Boolean indicating whether we have a signatures thread running. # (Never run more than one at the same time.) self._get_signatures_thread_running: bool = False self.style_transformation = merge_style_transformations([ ConditionalStyleTransformation( SwapLightAndDarkStyleTransformation(), filter=Condition(lambda: self.swap_light_and_dark), ), AdjustBrightnessStyleTransformation(lambda: self.min_brightness, lambda: self.max_brightness), ]) self.ptpython_layout = PtPythonLayout( self, lexer=DynamicLexer(lambda: self._lexer if self. enable_syntax_highlighting else SimpleLexer()), input_buffer_height=self._input_buffer_height, extra_buffer_processors=self._extra_buffer_processors, extra_body=self._extra_layout_body, extra_toolbars=self._extra_toolbars, ) self.app = self._create_application(input, output) if vi_mode: self.app.editing_mode = EditingMode.VI
def __init__(self, my_app: "sqlApp"): self.my_app = my_app help_text = """ Press Enter in the input box to page through the table. Alternatively, enter a filtering SQL statement and then press Enter to page through the results. """ self.formatter = TabularOutputFormatter() self.completer = PreviewCompleter( my_app=self.my_app, completer=MssqlCompleter( smart_completion=True, get_conn=lambda: self.my_app.selected_object.conn)) history_file = config_location() + 'preview_history' ensure_dir_exists(history_file) hist = PreviewHistory(my_app=self.my_app, filename=expanduser(history_file)) self.input_buffer = PreviewBuffer( name="previewbuffer", tempfile_suffix=".sql", history=ThreadedHistory(hist), auto_suggest=ThreadedAutoSuggest( PreviewSuggestFromHistory(my_app)), completer=ThreadedCompleter(self.completer), # history = hist, # auto_suggest = PreviewSuggestFromHistory(my_app), # completer = self.completer, complete_while_typing=Condition( lambda: self.my_app.selected_object is not None and self.my_app .selected_object.conn.connected()), multiline=False) input_control = BufferControl( buffer=self.input_buffer, include_default_input_processors=False, input_processors=[AppendAutoSuggestion()], preview_search=False) self.input_window = Window(input_control) search_buffer = Buffer(name="previewsearchbuffer") self.search_field = SearchToolbar(search_buffer) self.output_field = TextArea( style="class:preview-output-field", text=help_text, height=D(preferred=50), search_field=self.search_field, wrap_lines=False, focusable=True, read_only=True, preview_search=True, input_processors=[ ConditionalProcessor( processor=HighlightIncrementalSearchProcessor(), filter=has_focus("previewsearchbuffer") | has_focus(self.search_field.control), ), HighlightSelectionProcessor(), ]) def refresh_results(window_height) -> bool: """ This method gets called when the app restarts after exiting for execution of preview query. It populates the output buffer with results from the fetch/query. """ sql_conn = self.my_app.selected_object.conn if sql_conn.execution_status == executionStatus.FAIL: # Let's display the error message to the user output = sql_conn.execution_err else: crsr = sql_conn.cursor if crsr.description: cols = [col.name for col in crsr.description] else: cols = [] if len(cols): res = sql_conn.fetch_from_cache(size=window_height - 4, wait=True) output = self.formatter.format_output(res, cols, format_name="psql") output = "\n".join(output) else: output = "No rows returned\n" # Add text to output buffer. self.output_field.buffer.set_document( Document(text=output, cursor_position=0), True) return True def accept(buff: Buffer) -> bool: """ This method gets called when the user presses enter/return in the filter box. It is interpreted as either 'execute query' or 'fetch next page of results' if filter query hasn't changed. """ obj = self.my_app.selected_object sql_conn = obj.conn identifier = object_to_identifier(obj) query = sql_conn.preview_query( name=identifier, obj_type=obj.otype, filter_query=buff.text, limit=self.my_app.preview_limit_rows) if query is None: return True func = partial(refresh_results, window_height=self.output_field.window.render_info. window_height) if sql_conn.query != query: # Exit the app to execute the query self.my_app.application.exit(result=["preview", query]) self.my_app.application.pre_run_callables.append(func) else: # No need to exit let's just go and fetch func() return True # Keep filter text def cancel_handler() -> None: sql_conn = self.my_app.selected_object.conn sql_conn.close_cursor() self.input_buffer.text = "" self.output_field.buffer.set_document( Document(text=help_text, cursor_position=0), True) self.my_app.show_preview = False self.my_app.show_sidebar = True self.my_app.application.layout.focus(self.input_buffer) self.my_app.application.layout.focus("sidebarbuffer") return None self.input_buffer.accept_handler = accept self.cancel_button = Button(text="Done", handler=cancel_handler)
f"The command finished in {Decimal(str(execution_time)).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)}ms." ) def quote_check(args: str) -> bool: return " ".join(args).replace("\\\"", "").count("\"") % 2 != 0 or \ " ".join(args).count("'") % 2 != 0 or \ " ".join(args).count("`") % 2 != 0 pre_casts = pychromecast.get_chromecasts() casts = [] cmd_completer: ActionCompleter = ActionCompleter() cmd_auto_suggest: ThreadedAutoSuggest = ThreadedAutoSuggest( AutoSuggestFromHistory()) cmd_history: ThreadedHistory = ThreadedHistory(InMemoryHistory()) cmd_lexer: PygmentsLexer = PygmentsLexer(CommandLexer) now_cast = None now_id = 0 prefix = "> " @cmd_completer.action("echo", capture_all=True, display_meta="Prints characters to the console") @cmd_completer.param(None) def _echo_action(*args) -> None: if " ".join(args) == "": print() return
def GenerateHistory(name, need_persistent=False): if need_persistent: return PersistentHistory(name) else: return ThreadedHistory(NonPersistentHistory())
def __init__(self, my_app: "sqlApp") -> None: self.my_app = my_app self.search_field = SearchToolbar() history_file = config_location() + 'history' ensure_dir_exists(history_file) hist = ThreadedHistory(FileHistory(expanduser(history_file))) self.input_buffer = Buffer( name="defaultbuffer", tempfile_suffix=".py", multiline=MultilineFilter(self.my_app), history=hist, completer=DynamicCompleter( lambda: ThreadedCompleter(self.my_app.completer)), # lambda: self.my_app.completer), auto_suggest=ThreadedAutoSuggest(AutoSuggestFromHistory()), complete_while_typing=Condition( lambda: self.my_app.active_conn is not None)) main_win_control = BufferControl( buffer=self.input_buffer, lexer=PygmentsLexer(SqlLexer), search_buffer_control=self.search_field.control, include_default_input_processors=False, input_processors=[AppendAutoSuggestion()], preview_search=True) self.main_win = Window( main_win_control, height=( lambda: (None if get_app().is_done else (Dimension(min=self.my_app.min_num_menu_lines) if not self.my_app.show_preview else Dimension( min=self.my_app.min_num_menu_lines, preferred=180)))), get_line_prefix=partial(sql_line_prefix, my_app=self.my_app), scroll_offsets=ScrollOffsets(bottom=1, left=4, right=4)) self.lprompt = login_prompt(self.my_app) self.preview = preview_element(self.my_app) self.disconnect_dialog = disconnect_dialog(self.my_app) container = HSplit([ VSplit([ FloatContainer( content=HSplit([ self.main_win, self.search_field, ]), floats=[ Float( bottom=1, left=1, right=0, content=sql_sidebar_help(self.my_app), ), Float(content=self.lprompt), Float(content=self.preview, ), Float(content=self.disconnect_dialog, ), Float(left=2, bottom=1, content=exit_confirmation(self.my_app)), Float(xcursor=True, ycursor=True, transparent=True, content=CompletionsMenu(scroll_offset=1, max_height=16, extra_filter=has_focus( self.input_buffer))) ]), ConditionalContainer( content=sql_sidebar(self.my_app), filter=ShowSidebar(self.my_app) & ~is_done, ) ]), VSplit([ status_bar(self.my_app), show_sidebar_button_info(self.my_app) ]) ]) def accept(buff): app = get_app() app.exit(result=["non-preview", buff.text]) app.pre_run_callables.append(buff.reset) return True self.input_buffer.accept_handler = accept self.layout = Layout(container, focused_element=self.main_win)