def style_factory(name): try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('native') class CliStyle(Style): styles = {} styles.update(style.styles) styles.update(default_style_extensions) styles.update({ Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000', Token.Menu.Completions.Completion: 'bg:#008888 #ffffff', Token.Menu.Completions.ProgressButton: 'bg:#003333', Token.Menu.Completions.ProgressBar: 'bg:#00aaaa', Token.Toolbar: 'bg:#222222 #cccccc', Token.Toolbar.Off: 'bg:#222222 #004444', Token.Toolbar.On: 'bg:#222222 #ffffff', Token.Toolbar.Search: 'noinherit bold', Token.Toolbar.Search.Text: 'nobold', Token.Toolbar.System: 'noinherit bold', Token.Toolbar.Arg: 'noinherit bold', Token.Toolbar.Arg.Text: 'nobold' }) return PygmentsStyle(CliStyle)
def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', } if name == 'default': style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def run(self): labels = self.neo4j.get_labels() relationship_types = self.neo4j.get_relationship_types() properties = self.neo4j.get_property_keys() if self.filename: with open(self.filename, "rb") as f: queries = split_queries_on_semicolons(f.read()) for query in queries: print("> " + query) self.handle_query(query) print() return click.secho(" ______ __ __ ______ __ __ ", fg="red") click.secho("/\ ___\ /\ \_\ \ /\ ___\ /\ \ /\ \ ", fg="yellow") click.secho("\ \ \____ \ \____ \ \ \ \____ \ \ \____ \ \ \ ", fg="green") click.secho(" \ \_____\ \/\_____\ \ \_____\ \ \_____\ \ \_\ ", fg="blue") click.secho(" \/_____/ \/_____/ \/_____/ \/_____/ \/_/ ", fg="magenta") print("Cycli version: {}".format(__version__)) print("Neo4j version: {}".format(".".join(map(str, self.neo4j.neo4j_version)))) print("Bug reports: https://github.com/nicolewhite/cycli/issues\n") completer = CypherCompleter(labels, relationship_types, properties) layout = create_prompt_layout( lexer=CypherLexer, get_prompt_tokens=get_tokens, reserve_space_for_menu=8, ) buff = CypherBuffer( accept_action=AcceptAction.RETURN_DOCUMENT, history=FileHistory(filename=os.path.expanduser('~/.cycli_history')), completer=completer, complete_while_typing=True, ) application = Application( style=PygmentsStyle(CypherStyle), buffer=buff, layout=layout, on_exit=AbortAction.RAISE_EXCEPTION, key_bindings_registry=CypherBinder.registry ) cli = CommandLineInterface(application=application, eventloop=create_eventloop()) try: while True: document = cli.run() query = document.text self.handle_query(query) except UserWantsOut: print("Goodbye!") except Exception as e: print(e)
def init_prompt_toolkit_cli(self): """ Initializes the Prompt Tookkit CLI. """ self.init_lexer() kbmanager = KeyBindingManager.for_prompt() style_overrides = { Token.Prompt: '#aaddaa', Token.OutPrompt: '#ddaaaa', Token.Name.Namespace: '#ddaadd', Token.Name.Function: '#aadddd', } style_cls = get_style_by_name('default') style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) app = create_prompt_application( get_prompt_tokens=self.get_prompt_tokens, key_bindings_registry=kbmanager.registry, completer=self._completer, lexer=self._lexer, style=style, ) self._eventloop = create_eventloop() self.pt_cli = CommandLineInterface( app, eventloop=self._eventloop, output=create_output(true_color=False), )
def style_factory(name): try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('native') styles = {} styles.update(style.styles) styles.update(default_style_extensions) styles.update({ Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000', Token.Menu.Completions.Completion: 'bg:#008888 #ffffff', Token.Menu.Completions.ProgressButton: 'bg:#003333', Token.Menu.Completions.ProgressBar: 'bg:#00aaaa', Token.Toolbar: 'bg:#222222 #cccccc', Token.Toolbar.Off: 'bg:#222222 #004444', Token.Toolbar.On: 'bg:#222222 #ffffff', Token.Toolbar.Search: 'noinherit bold', Token.Toolbar.Search.Text: 'nobold', Token.Toolbar.System: 'noinherit bold', Token.Toolbar.Arg: 'noinherit bold', Token.Toolbar.Arg.Text: 'nobold' }) return PygmentsStyle.from_defaults(style_dict=styles)
def _handle_exception(cls, cli, e): output = cli.output # Instead of just calling ``traceback.format_exc``, we take the # traceback and skip the bottom calls of this framework. t, v, tb = sys.exc_info() tblist = traceback.extract_tb(tb) for line_nr, tb_tuple in enumerate(tblist): if tb_tuple[0] == '<stdin>': tblist = tblist[line_nr:] break l = traceback.format_list(tblist) if l: l.insert(0, "Traceback (most recent call last):\n") l.extend(traceback.format_exception_only(t, v)) tb = ''.join(l) # Format exception and write to output. # (We use the default style. Most other styles result # in unreadable colors for the traceback.) tokens = _lex_python_traceback(tb) cli.print_tokens(tokens, style=PygmentsStyle(DefaultStyle)) output.write('%s\n\n' % e) output.flush()
def run(): validate_osenvironment() print_banner() cli_buffer = OSBuffer() ltobj = OSLayout(multiwindow=False) application = Application(style=PygmentsStyle(OSStyle), layout=ltobj.layout, buffers=cli_buffer.buffers, on_exit=AbortAction.RAISE_EXCEPTION, key_bindings_registry=OSKeyBinder.registry) cli = CommandLineInterface(application=application, eventloop=create_eventloop()) while True: try: document = cli.run(reset_current_buffer=True) process_document(document) except KeyboardInterrupt: # A keyboardInterrupt generated possibly due to Ctrl-C print "Keyboard Interrupt Generated" continue except EOFError: print "cntl-D" sys.exit()
def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: style_cls.styles.get( Token.Keyword, '#009900'), Token.PromptNum: style_cls.styles.get( Token.Literal.Number, '#00ff00 bold') } if name is 'default': style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def _create_application(self): """ Create CommandLineInterface instance. """ # Create Vi command buffer. def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. self.leave_command_mode(append_to_history=True) # Execute command. handle_command(self, text) # Create history and search buffers. commands_history = FileHistory( os.path.join(self.config_directory, 'commands_history')) command_buffer = Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=Always(), completer=create_command_completer(self), history=commands_history) search_buffer_history = FileHistory( os.path.join(self.config_directory, 'search_history')) search_buffer = Buffer(history=search_buffer_history, enable_history_search=Always(), accept_action=AcceptAction.IGNORE) # Create app. # Create CLI. application = Application( layout=self.editor_layout.layout, key_bindings_registry=self.key_bindings_manager.registry, get_title=lambda: get_terminal_title(self), buffers={ COMMAND_BUFFER: command_buffer, SEARCH_BUFFER: search_buffer, }, style=DynamicStyle(lambda: PygmentsStyle(self.current_style)), paste_mode=Condition(lambda cli: self.paste_mode), ignore_case=Condition(lambda cli: self.ignore_case), mouse_support=Condition(lambda cli: self.enable_mouse_support), use_alternate_screen=True, on_buffer_changed=Callback(self._current_buffer_changed)) # Handle command line previews. # (e.g. when typing ':colorscheme blue', it should already show the # preview before pressing enter.) def preview(): if self.cli.current_buffer == command_buffer: self.previewer.preview(command_buffer.text) command_buffer.on_text_changed += preview return application
def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: "#009900", Token.PromptNum: "#00ff00 bold", Token.OutPrompt: "#990000", Token.OutPromptNum: "#ff0000 bold", } if name == "default": style_cls = get_style_by_name("default") # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update( { Token.Number: "#007700", Token.Operator: "noinherit", Token.String: "#BB6622", Token.Name.Function: "#2080D0", Token.Name.Class: "bold #2080D0", Token.Name.Namespace: "bold #2080D0", } ) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def style_factory(name='default'): #pragma: no cover try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('default') styles = {} styles.update(style.styles) styles.update(default_style_extensions) styles.update({ Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000', Token.Menu.Completions.Completion: 'bg:#008888 #ffffff', Token.Menu.Completions.ProgressButton: 'bg:#003333', Token.Menu.Completions.ProgressBar: 'bg:#00aaaa', Token.Toolbar: 'bg:#222222 #cccccc', Token.Toolbar.Off: 'bg:#222222 #004444', Token.Toolbar.On: 'bg:#222222 #ffffff', Token.Toolbar.Search: 'noinherit bold', Token.Toolbar.Search.Text: 'nobold', Token.Toolbar.System: 'noinherit bold', Token.Toolbar.Arg: 'noinherit bold', Token.Toolbar.Arg.Text: 'nobold', Token.Pound: 'bg:#a06a2c #222222' }) return PygmentsStyle.from_defaults(style_dict=styles)
def main(): def get_bottom_toolbar_tokens(cli): return [(Token.Toolbar, ' This is a toolbar. ')] text = prompt('Say something: ', get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=PygmentsStyle(TestStyle)) print('You said: %s' % text)
def singleline(self, store_in_history=True, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs): """Reads a single line of input from the shell. The store_in_history kwarg flags whether the input should be stored in PTK's in-memory history. """ env = builtins.__xonsh_env__ mouse_support = env.get('MOUSE_SUPPORT') if store_in_history: history = self.history else: history = None enable_history_search = False auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None completions_display = env.get('COMPLETIONS_DISPLAY') multicolumn = (completions_display == 'multi') self.styler.style_name = env.get('XONSH_COLOR_STYLE') completer = None if completions_display == 'none' else self.pt_completer if not env.get('UPDATE_PROMPT_ON_KEYPRESS'): prompt_tokens_cached = self.prompt_tokens(None) get_prompt_tokens = lambda cli: prompt_tokens_cached rprompt_tokens_cached = self.rprompt_tokens(None) get_rprompt_tokens = lambda cli: rprompt_tokens_cached bottom_toolbar_tokens_cached = self.bottom_toolbar_tokens(None) get_bottom_toolbar_tokens = lambda cli: bottom_toolbar_tokens_cached else: get_prompt_tokens = self.prompt_tokens get_rprompt_tokens = self.rprompt_tokens get_bottom_toolbar_tokens = self.bottom_toolbar_tokens with self.prompter: prompt_args = { 'mouse_support': mouse_support, 'auto_suggest': auto_suggest, 'get_prompt_tokens': get_prompt_tokens, 'get_rprompt_tokens': get_rprompt_tokens, 'get_bottom_toolbar_tokens': get_bottom_toolbar_tokens, 'style': PygmentsStyle(xonsh_style_proxy(self.styler)), 'completer': completer, 'multiline': multiline, 'get_continuation_tokens': self.continuation_tokens, 'history': history, 'enable_history_search': enable_history_search, 'reserve_space_for_menu': 0, 'key_bindings_registry': self.key_bindings_manager.registry, 'display_completions_in_columns': multicolumn, } if builtins.__xonsh_env__.get('COLOR_INPUT'): prompt_args['lexer'] = PygmentsLexer(XonshLexer) line = self.prompter.prompt(**prompt_args) return line
def style_factory(name, cli_style): try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('native') custom_styles = dict([(string_to_tokentype(x), y) for x, y in cli_style.items()]) return PygmentsStyle.from_defaults(style_dict=custom_styles, pygments_style_cls=style)
def print_color(self, string, end='\n', **kwargs): """Prints a color string using prompt-toolkit color management.""" env = builtins.__xonsh_env__ self.styler.style_name = env.get('XONSH_COLOR_STYLE') if isinstance(string, str): tokens = partial_color_tokenize(string + end) else: # assume this is a list of (Token, str) tuples and just print tokens = string proxy_style = PygmentsStyle(xonsh_style_proxy(self.styler)) print_tokens(tokens, style=proxy_style)
def main(): style = PygmentsStyle.from_defaults(style_dict={ Token.Hello: '#ff0066', Token.World: '#44ff44 italic', }) tokens = [ (Token.Hello, 'Hello '), (Token.World, 'World'), (Token, '\n'), ] print_tokens(tokens, style=style)
def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') style_overrides = _style_overrides_linux elif legacy == 'lightbg': style_overrides = _style_overrides_light_bg style_cls = get_style_by_name('pastie') elif legacy == 'neutral': # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name('default') style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', }) elif legacy =='nocolor': style_cls=_NoStyle style_overrides = {} else : raise ValueError('Got unknown colors: ', legacy) else : if isinstance(name_or_cls, string_types): style_cls = get_style_by_name(name_or_cls) else: style_cls = name_or_cls style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', } style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def _make_style_from_name_or_cls(self, name_or_cls): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name_or_cls == 'legacy': legacy = self.colors.lower() if legacy == 'linux': style_cls = get_style_by_name('monokai') style_overrides = _style_overrides_linux elif legacy == 'lightbg': style_overrides = _style_overrides_light_bg style_cls = get_style_by_name('pastie') elif legacy == 'neutral': # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name('default') style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', }) elif legacy == 'nocolor': style_cls = _NoStyle style_overrides = {} else: raise ValueError('Got unknown colors: ', legacy) else: if isinstance(name_or_cls, string_types): style_cls = get_style_by_name(name_or_cls) else: style_cls = name_or_cls style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#990000', Token.OutPromptNum: '#ff0000 bold', } style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def loop(cmd, history_file): key_binding_manager = KeyBindingManager( enable_search=True, enable_abort_and_exit_bindings=True ) layout = create_prompt_layout( message=u'cr> ', multiline=True, lexer=SqlLexer, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()) ] ) buffer = CrashBuffer( history=TruncatedFileHistory(history_file, max_length=MAX_HISTORY_LENGTH), accept_action=AcceptAction.RETURN_DOCUMENT, completer=SQLCompleter(cmd) ) buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete() application = Application( layout=layout, buffer=buffer, style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle), key_bindings_registry=key_binding_manager.registry, editing_mode=_get_editing_mode(), on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ) eventloop = create_eventloop() output = create_output() cli = CommandLineInterface( application=application, eventloop=eventloop, output=output ) def get_num_columns_override(): return output.get_size().columns cmd.get_num_columns = get_num_columns_override while True: try: doc = cli.run(reset_current_buffer=True) if doc: cmd.process(doc.text) except KeyboardInterrupt: cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it") except EOFError: cmd.logger.warn(u'Bye!') return
def _make_style_from_name(self, name): """ Small wrapper that make an IPython compatible style from a style name We need that to add style for prompt ... etc. """ style_overrides = {} if name == "legacy": legacy = self.colors.lower() if legacy == "linux": style_cls = get_style_by_name("monokai") style_overrides = _style_overrides_linux elif legacy == "lightbg": style_overrides = _style_overrides_light_bg style_cls = get_style_by_name("pastie") elif legacy == "neutral": # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_cls = get_style_by_name("default") style_overrides.update( { Token.Number: "#007700", Token.Operator: "noinherit", Token.String: "#BB6622", Token.Name.Function: "#2080D0", Token.Name.Class: "bold #2080D0", Token.Name.Namespace: "bold #2080D0", Token.Prompt: "#009900", Token.PromptNum: "#00ff00 bold", Token.OutPrompt: "#990000", Token.OutPromptNum: "#ff0000 bold", } ) elif legacy == "nocolor": style_cls = _NoStyle style_overrides = {} else: raise ValueError("Got unknown colors: ", legacy) else: style_cls = get_style_by_name(name) style_overrides = { Token.Prompt: "#009900", Token.PromptNum: "#00ff00 bold", Token.OutPrompt: "#990000", Token.OutPromptNum: "#ff0000 bold", } style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) return style
def style_factory(name, cli_style): try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('native') class CLIStyle(Style): styles = {} styles.update(style.styles) styles.update(default_style_extensions) custom_styles = dict([(string_to_tokentype(x), y) for x, y in cli_style.items()]) styles.update(custom_styles) return PygmentsStyle(CLIStyle)
def generate_style(python_style, ui_style): """ Generate Pygments Style class from two dictionaries containing style rules. """ assert isinstance(python_style, dict) assert isinstance(ui_style, dict) class PythonStyle(Style): styles = {} styles.update(default_style_extensions) styles.update(python_style) styles.update(ui_style) return PygmentsStyle(PythonStyle)
def print_color(self, string, end="\n", **kwargs): """Prints a color string using prompt-toolkit color management.""" if isinstance(string, str): tokens = partial_color_tokenize(string + end) else: # assume this is a list of (Token, str) tuples and just print tokens = string if HAS_PYGMENTS: env = builtins.__xonsh_env__ self.styler.style_name = env.get("XONSH_COLOR_STYLE") proxy_style = PygmentsStyle(pyghooks.xonsh_style_proxy( self.styler)) else: proxy_style = style_from_dict(DEFAULT_STYLE_DICT) print_tokens(tokens, style=proxy_style)
def loop(cmd, history_file): key_binding_manager = KeyBindingManager( enable_search=True, enable_abort_and_exit_bindings=True) layout = create_prompt_layout( message=u'cr> ', multiline=True, lexer=SqlLexer, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()) ]) buffer = CrashBuffer(history=TruncatedFileHistory( history_file, max_length=MAX_HISTORY_LENGTH), accept_action=AcceptAction.RETURN_DOCUMENT, completer=SQLCompleter(cmd)) buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete() application = Application( layout=layout, buffer=buffer, style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle), key_bindings_registry=key_binding_manager.registry, editing_mode=_get_editing_mode(), on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ) eventloop = create_eventloop() output = create_output() cli = CommandLineInterface(application=application, eventloop=eventloop, output=output) def get_num_columns_override(): return output.get_size().columns cmd.get_num_columns = get_num_columns_override while True: try: doc = cli.run(reset_current_buffer=True) if doc: cmd.process(doc.text) except KeyboardInterrupt: cmd.logger.warn( "Query not cancelled. Run KILL <jobId> to cancel it") except EOFError: cmd.logger.warn(u'Bye!') return
def style_factory(name, cli_style): try: style = pygments.styles.get_style_by_name(name) except ClassNotFound: style = pygments.styles.get_style_by_name('native') custom_styles = {} for token in cli_style: try: custom_styles[string_to_tokentype(token)] = style.styles[ string_to_tokentype(cli_style[token])] except AttributeError as err: custom_styles[string_to_tokentype(token)] = cli_style[token] return PygmentsStyle.from_defaults(style_dict=custom_styles, pygments_style_cls=style)
def singleline(self, store_in_history=True, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs): """Reads a single line of input from the shell. The store_in_history kwarg flags whether the input should be stored in PTK's in-memory history. """ env = builtins.__xonsh_env__ mouse_support = env.get('MOUSE_SUPPORT') if store_in_history: history = self.history else: history = None enable_history_search = False auto_suggest = auto_suggest if env.get('AUTO_SUGGEST') else None completions_display = env.get('COMPLETIONS_DISPLAY') multicolumn = (completions_display == 'multi') self.styler.style_name = env.get('XONSH_COLOR_STYLE') completer = None if completions_display == 'none' else self.pt_completer prompt_tokens = self.prompt_tokens(None) get_prompt_tokens = lambda cli: prompt_tokens rprompt_tokens = self.rprompt_tokens(None) get_rprompt_tokens = lambda cli: rprompt_tokens with self.prompter: line = self.prompter.prompt( mouse_support=mouse_support, auto_suggest=auto_suggest, get_prompt_tokens=get_prompt_tokens, get_rprompt_tokens=get_rprompt_tokens, style=PygmentsStyle(xonsh_style_proxy(self.styler)), completer=completer, lexer=PygmentsLexer(XonshLexer), multiline=multiline, get_continuation_tokens=self.continuation_tokens, history=history, enable_history_search=enable_history_search, reserve_space_for_menu=0, key_bindings_registry=self.key_bindings_manager.registry, display_completions_in_columns=multicolumn) return line
def run(): cli_buffer = VaultBuffer() vault_layout = VaultLayout(multiwindow=True) application = Application(style=PygmentsStyle(VaultStyle), layout=vault_layout.layout, buffers=cli_buffer.buffers, on_exit=AbortAction.RAISE_EXCEPTION, key_bindings_registry=VaultKeyBinder.registry, use_alternate_screen=False) cli = CommandLineInterface(application=application, eventloop=create_eventloop()) while True: try: document = cli.run(reset_current_buffer=True) process_document(document) except KeyboardInterrupt: print "Keyboard interrupt generated" continue except EOFError: print "ctrl-D" sys.exit()
operators1 = ['add', 'sub', 'div', 'mul'] operators2 = ['sqrt', 'log', 'sin', 'ln'] def create_grammar(): return compile(""" (\s* (?P<operator1>[a-z]+) \s+ (?P<var1>[0-9.]+) \s+ (?P<var2>[0-9.]+) \s*) | (\s* (?P<operator2>[a-z]+) \s+ (?P<var1>[0-9.]+) \s*) """) example_style = PygmentsStyle.from_defaults({ Token.Operator: '#33aa33 bold', Token.Number: '#aa3333 bold', Token.TrailingInput: 'bg:#662222 #ffffff', }) if __name__ == '__main__': g = create_grammar() lexer = GrammarLexer(g, lexers={ 'operator1': SimpleLexer(Token.Operator), 'operator2': SimpleLexer(Token.Operator), 'var1': SimpleLexer(Token.Number), 'var2': SimpleLexer(Token.Number), })
operators1 = ['add', 'sub', 'div', 'mul'] operators2 = ['sqrt', 'log', 'sin', 'ln'] def create_grammar(): return compile(""" (\s* (?P<operator1>[a-z]+) \s+ (?P<var1>[0-9.]+) \s+ (?P<var2>[0-9.]+) \s*) | (\s* (?P<operator2>[a-z]+) \s+ (?P<var1>[0-9.]+) \s*) """) example_style = PygmentsStyle.from_defaults({ Token.Operator: '#33aa33 bold', Token.Number: '#aa3333 bold', Token.TrailingInput: 'bg:#662222 #ffffff', }) if __name__ == '__main__': g = create_grammar() lexer = GrammarLexer(g, lexers={ 'operator1': SimpleLexer(Token.Operator), 'operator2': SimpleLexer(Token.Operator), 'var1': SimpleLexer(Token.Number), 'var2': SimpleLexer(Token.Number), }) completer = GrammarCompleter(g, {
""" Example of a colored prompt. """ from __future__ import unicode_literals from prompt_toolkit import prompt from prompt_toolkit.styles import PygmentsStyle from pygments.token import Token example_style = PygmentsStyle.from_defaults(style_dict={ # User input. Token: '#ff0066', # Prompt. Token.Username: '******', Token.At: '#00aa00', Token.Colon: '#00aa00', Token.Pound: '#00aa00', Token.Host: '#000088 bg:#aaaaff', Token.Path: '#884444 underline', }) def get_prompt_tokens(cli): return [ (Token.Username, 'john'), (Token.At, '@'), (Token.Host, 'localhost'), (Token.Colon, ':'), (Token.Path, '/user/john'), (Token.Pound, '# '),
def loop(cmd, history_file): key_binding_manager = KeyBindingManager( enable_search=True, enable_abort_and_exit_bindings=True, enable_system_bindings=True, enable_open_in_editor=True ) bind_keys(key_binding_manager.registry) layout = create_layout( multiline=True, lexer=SqlLexer, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()) ], get_bottom_toolbar_tokens=lambda cli: get_toolbar_tokens(cmd), get_prompt_tokens=lambda cli: [(Token.Prompt, 'cr> ')] ) application = Application( layout=layout, buffer=create_buffer(cmd, history_file), style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle), key_bindings_registry=key_binding_manager.registry, editing_mode=_get_editing_mode(), on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ) eventloop = create_eventloop() output = create_output() cli = CommandLineInterface( application=application, eventloop=eventloop, output=output ) def get_num_columns_override(): return output.get_size().columns cmd.get_num_columns = get_num_columns_override while True: try: doc = cli.run(reset_current_buffer=True) if doc: cmd.process(doc.text) except ProgrammingError as e: if '401' in e.message: username = cmd.username password = cmd.password cmd.username = input('Username: '******'Bye!') return
#!/usr/bin/env python """ Simple example showing a bottom toolbar. """ from __future__ import unicode_literals from prompt_toolkit import prompt from prompt_toolkit.styles import PygmentsStyle from pygments.token import Token test_style = PygmentsStyle.from_defaults({ Token.Toolbar: '#ffffff bg:#333333', }) def main(): def get_bottom_toolbar_tokens(cli): return [(Token.Toolbar, ' This is a toolbar. ')] text = prompt('Say something: ', get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=test_style) print('You said: %s' % text) if __name__ == '__main__': main()
def __init__(self, looper, basedirpath, nodeReg, cliNodeReg, output=None, debug=False, logFileName=None): self.curClientPort = None logging.root.addHandler(CliHandler(self.out)) self.looper = looper self.basedirpath = basedirpath self.nodeReg = nodeReg self.cliNodeReg = cliNodeReg # Used to store created clients self.clients = {} # clientName -> Client # To store the created requests self.requests = {} # To store the nodes created self.nodes = {} self.externalClientKeys = {} # type: Dict[str,str] self.cliCmds = {'status', 'new'} self.nodeCmds = self.cliCmds | {'keyshare'} self.helpablesCommands = self.cliCmds | self.nodeCmds self.simpleCmds = {'status', 'exit', 'quit', 'license'} self.commands = {'list', 'help'} | self.simpleCmds self.cliActions = {'send', 'show'} self.commands.update(self.cliCmds) self.commands.update(self.nodeCmds) self.node_or_cli = ['node', 'client'] self.nodeNames = list(self.nodeReg.keys()) + ["all"] self.debug = debug self.plugins = {} ''' examples: status new node Alpha new node all new client Joe client Joe send <msg> client Joe show 1 ''' psep = re.escape(os.path.sep) self.utilGrams = [ "(\s* (?P<simple>{}) \s*) |".format(self.relist(self.simpleCmds)), "(\s* (?P<load>load) \s+ (?P<file_name>[.a-zA-z0-9{}]+) \s*) |".format(psep), "(\s* (?P<command>help) (\s+ (?P<helpable>[a-zA-Z0-9]+) )? (\s+ (?P<node_or_cli>{}) )?\s*) |".format(self.relist(self.node_or_cli)), "(\s* (?P<command>list) \s*)" ] self.nodeGrams = [ "(\s* (?P<node_command>{}) \s+ (?P<node_or_cli>nodes?) \s+ (?P<node_name>[a-zA-Z0-9]+)\s*) |".format(self.relist(self.nodeCmds)), "(\s* (?P<load_plugins>load\s+plugins\s+from) \s+ (?P<plugin_dir>[a-zA-Z0-9-:{}]+) \s*)".format(psep), ] self.clientGrams = [ "(\s* (?P<client_command>{}) \s+ (?P<node_or_cli>clients?) \s+ (?P<client_name>[a-zA-Z0-9]+) \s*) |".format(self.relist(self.cliCmds)), "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>send) \s+ (?P<msg>\{\s*.*\}) \s*) |", "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>show) \s+ (?P<req_id>[0-9]+) \s*) |", "(\s* (?P<add_key>add\s+key) \s+ (?P<verkey>[a-fA-F0-9]+) \s+ (?P<for_client>for\s+client) \s+ (?P<identifier>[a-zA-Z0-9]+) \s*)", ] self.lexers = { 'node_command': SimpleLexer(Token.Keyword), 'command': SimpleLexer(Token.Keyword), 'helpable': SimpleLexer(Token.Keyword), 'load_plugins': SimpleLexer(Token.Keyword), 'load': SimpleLexer(Token.Keyword), 'node_or_cli': SimpleLexer(Token.Keyword), 'arg1': SimpleLexer(Token.Name), 'node_name': SimpleLexer(Token.Name), 'more_nodes': SimpleLexer(Token.Name), 'simple': SimpleLexer(Token.Keyword), 'client_command': SimpleLexer(Token.Keyword), 'add_key': SimpleLexer(Token.Keyword), 'verkey': SimpleLexer(Token.Literal), 'for_client': SimpleLexer(Token.Keyword), 'identifier': SimpleLexer(Token.Name), } self.clientWC = WordCompleter([]) self.completers = { 'node_command': WordCompleter(self.nodeCmds), 'client_command': WordCompleter(self.cliCmds), 'client': WordCompleter(['client']), 'command': WordCompleter(self.commands), 'node_or_cli': WordCompleter(self.node_or_cli), 'node_name': WordCompleter(self.nodeNames), 'more_nodes': WordCompleter(self.nodeNames), 'helpable': WordCompleter(self.helpablesCommands), 'load_plugins': WordCompleter(['load plugins from']), 'client_name': self.clientWC, 'cli_action': WordCompleter(self.cliActions), 'simple': WordCompleter(self.simpleCmds), 'add_key': WordCompleter(['add key']), 'for_client': WordCompleter(['for client']), } self.initializeGrammar() self.initializeGrammarLexer() self.initializeGrammarCompleter() self.style = PygmentsStyle.from_defaults({ Token.Operator: '#33aa33 bold', Token.Number: '#aa3333 bold', Token.Name: '#ffff00 bold', Token.Heading: 'bold', Token.TrailingInput: 'bg:#662222 #ffffff', Token.BoldGreen: '#33aa33 bold', Token.BoldOrange: '#ff4f2f bold', Token.BoldBlue: '#095cab bold'}) self.functionMappings = self.createFunctionMappings() self.voidMsg = "<none>" # Create an asyncio `EventLoop` object. This is a wrapper around the # asyncio loop that can be passed into prompt_toolkit. eventloop = create_asyncio_eventloop(looper.loop) pers_hist = FileHistory('.{}-cli-history'.format(self.name)) # Create interface. app = create_prompt_application('{}> '.format(self.name), lexer=self.grammarLexer, completer=self.grammarCompleter, style=self.style, history=pers_hist) if output: out = output else: if is_windows(): if is_conemu_ansi(): out = ConEmuOutput(sys.__stdout__) else: out = Win32Output(sys.__stdout__) else: out = CustomOutput.from_pty(sys.__stdout__, true_color=True) self.cli = CommandLineInterface( application=app, eventloop=eventloop, output=out) # Patch stdout in something that will always print *above* the prompt # when something is written to stdout. sys.stdout = self.cli.stdout_proxy() setupLogging(TRACE_LOG_LEVEL, Console.Wordage.mute, filename=logFileName) self.logger = getlogger("cli") self.print("\n{}-CLI (c) 2016 Evernym, Inc.".format(self.properName)) self.print("Node registry loaded.") self.print("None of these are created or running yet.") self.showNodeRegistry() self.print("Type 'help' for more information.")
def __init__(self): """(PymuxStyle) -> NoneType *Description* """ self.pygments_style = PygmentsStyle.from_defaults(style_dict=ui_style) self._token_to_attrs_dict = None
def init_prompt_toolkit_cli(self): if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty(): # Fall back to plain non-interactive output for tests. # This is very limited, and only accepts a single line. def prompt(): return cast_unicode_py2( input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt return kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode) insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT) # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode)) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return status, indent = self.input_splitter.check_complete(d.text) if (status != 'incomplete') and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + (' ' * (indent or 0))) @kbmanager.registry.add_binding(Keys.ControlC) def _(event): event.current_buffer.reset() @Condition def cursor_in_leading_ws(cli): before = cli.application.buffer.document.current_line_before_cursor return (not before) or before.isspace() # Ctrl+I == Tab @kbmanager.registry.add_binding(Keys.ControlI, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode & cursor_in_leading_ws)) def _(event): event.current_buffer.insert_text(' ' * 4) # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail( self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) app = create_prompt_application( multiline=True, lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer), get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, key_bindings_registry=kbmanager.registry, history=history, completer=IPythonPTCompleter(self.Completer), enable_history_search=True, style=style, mouse_support=self.mouse_support, ) self.pt_cli = CommandLineInterface(app, eventloop=create_eventloop( self.inputhook))
from prompt_toolkit.styles import PygmentsStyle from pygments.token import Token from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.keys import Keys from datetime import datetime import os import subprocess import random import sys manager = KeyBindingManager.for_prompt() toolbar_style = PygmentsStyle.from_defaults({ Token.Toolbar: '#ffffff bg:#333333', Token.SCM: '#FF1A00 bg:#333333', Token.QUIT: '#ffffff bg:#ff0000' }) # GIT COMMANDS GIT_STATUS = ['git', 'status', '--porcelain'] GIT_BRANCH = ['git', 'rev-parse', '--abbrev-ref', 'HEAD'] GIT_MODIFICATIONS = ['git', '--no-pager', 'diff', '--numstat', 'HEAD'] GIT_AUTHORS = ["git", "log", "--format=%aN"] @manager.registry.add_binding(Keys.ControlC) @manager.registry.add_binding(Keys.ControlD) def _(event): def quit_it(): if getattr(event.cli, 'quit', False) is True:
def __init__(self, looper, tmpdir, nodeReg, cliNodeReg, debug=False, logFileName=None): self.curClientPort = None logging.root.addHandler(CliHandler(self.out)) self.looper = looper self.tmpdir = tmpdir self.nodeReg = nodeReg self.cliNodeReg = cliNodeReg # Used to store created clients self.clients = {} # clientId -> Client # To store the created requests self.requests = {} # To store the nodes created self.nodes = {} self.cliCmds = {'status', 'new'} self.nodeCmds = self.cliCmds | {'keyshare'} self.helpablesCommands = self.cliCmds | self.nodeCmds self.simpleCmds = {'status', 'exit', 'quit', 'license'} self.commands = {'list', 'help'} | self.simpleCmds self.cliActions = {'send', 'show'} self.commands.update(self.cliCmds) self.commands.update(self.nodeCmds) self.node_or_cli = ['node', 'client'] self.nodeNames = list(self.nodeReg.keys()) + ["all"] self.debug = debug self.plugins = [] ''' examples: status new node Alpha new node all new client Joe client Joe send <msg> client Joe show 1 ''' def re(seq): return '(' + '|'.join(seq) + ')' grams = [ "(\s* (?P<simple>{}) \s*) |".format(re(self.simpleCmds)), "(\s* (?P<client_command>{}) \s+ (?P<node_or_cli>clients?) \s+ (?P<client_name>[a-zA-Z0-9]+) \s*) |".format(re(self.cliCmds)), "(\s* (?P<node_command>{}) \s+ (?P<node_or_cli>nodes?) \s+ (?P<node_name>[a-zA-Z0-9]+)\s*) |".format(re(self.nodeCmds)), "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>send) \s+ (?P<msg>\{\s*\".*\}) \s*) |", "(\s* (?P<client>client) \s+ (?P<client_name>[a-zA-Z0-9]+) \s+ (?P<cli_action>show) \s+ (?P<req_id>[0-9]+) \s*) |", "(\s* (?P<load_plugins>load\s+plugins\s+from) \s+ (?P<plugin_dir>[a-zA-Z0-9-{}]+) \s*) |".format(os.path.sep), "(\s* (?P<load>load) \s+ (?P<file_name>[.a-zA-z0-9{}]+) \s*) |".format(os.path.sep), "(\s* (?P<command>help) (\s+ (?P<helpable>[a-zA-Z0-9]+) )? (\s+ (?P<node_or_cli>{}) )?\s*) |".format(re(self.node_or_cli)), "(\s* (?P<command>list) \s*)".format(re(self.commands)) ] self.grammar = compile("".join(grams)) lexer = GrammarLexer(self.grammar, lexers={ 'node_command': SimpleLexer(Token.Keyword), 'command': SimpleLexer(Token.Keyword), 'helpable': SimpleLexer(Token.Keyword), 'load_plugins': SimpleLexer(Token.Keyword), 'load': SimpleLexer(Token.Keyword), 'node_or_cli': SimpleLexer(Token.Keyword), 'arg1': SimpleLexer(Token.Name), 'node_name': SimpleLexer(Token.Name), 'more_nodes': SimpleLexer(Token.Name), 'simple': SimpleLexer(Token.Keyword), 'client_command': SimpleLexer(Token.Keyword), }) self.clientWC = WordCompleter([]) completer = GrammarCompleter(self.grammar, { 'node_command': WordCompleter(self.nodeCmds), 'client_command': WordCompleter(self.cliCmds), 'client': WordCompleter(['client']), 'command': WordCompleter(self.commands), 'node_or_cli': WordCompleter(self.node_or_cli), 'node_name': WordCompleter(self.nodeNames), 'more_nodes': WordCompleter(self.nodeNames), 'helpable': WordCompleter(self.helpablesCommands), 'load_plugins': WordCompleter(['load plugins from']), 'client_name': self.clientWC, 'cli_action': WordCompleter(self.cliActions), 'simple': WordCompleter(self.simpleCmds) }) self.style = PygmentsStyle.from_defaults({ Token.Operator: '#33aa33 bold', Token.Number: '#aa3333 bold', Token.Name: '#ffff00 bold', Token.Heading: 'bold', Token.TrailingInput: 'bg:#662222 #ffffff', Token.BoldGreen: '#33aa33 bold', Token.BoldOrange: '#ff4f2f bold', Token.BoldBlue: '#095cab bold'}) self.functionMappings = self.createFunctionMappings() self.voidMsg = "<none>" # Create an asyncio `EventLoop` object. This is a wrapper around the # asyncio loop that can be passed into prompt_toolkit. eventloop = create_asyncio_eventloop(looper.loop) pers_hist = FileHistory('.plenum-cli-history') # Create interface. app = create_prompt_application('plenum> ', lexer=lexer, completer=completer, style=self.style, history=pers_hist) self.cli = CommandLineInterface( application=app, eventloop=eventloop, output=CustomOutput.from_pty(sys.__stdout__, true_color=True)) # Patch stdout in something that will always print *above* the prompt # when something is written to stdout. sys.stdout = self.cli.stdout_proxy() setupLogging(TRACE_LOG_LEVEL, Console.Wordage.mute, filename=logFileName) self.logger = getlogger("cli") self.print("\nplenum-CLI (c) 2016 Evernym, Inc.") self.print("Node registry loaded.") self.print("None of these are created or running yet.") self.showNodeRegistry() self.print("Type 'help' for more information.")
return registry #STYLE _style = { Token: '#ffffff', Token.Toolbar: '#ffffff bg:#111111', Token.Toolbar.On: '#ffffff', Token.Toolbar.Off: '#ffffff', Token.Prompt: '#00ff00', Token.Continuation: '#00ff00', Token.String: '#00ff00' } get_style = lambda _name='native': PygmentsStyle.from_defaults( style_dict=_style, pygments_style_cls=pygments.styles.get_style_by_name(_name)) _o_style = style_from_dict({ Token.OutPrompt: '#9988ff', Token.String: '#ffffff' }) rprint = lambda buff: lambda text:\ print_tokens(zip(itertools.cycle([Token.OutPrompt, Token.String]), ['Out[%d]: ' % buff.return_count, text, '\n\n']), style=_o_style) #cli class RCLI(object):
def init_prompt_toolkit_cli(self): if not sys.stdin.isatty(): # Piped input - e.g. for tests. Fall back to plain non-interactive # output. This is very limited, and only accepts a single line. def prompt(): return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt return kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode) insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT) # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode )) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return status, indent = self.input_splitter.check_complete(d.text) if (status != 'incomplete') and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + (' ' * (indent or 0))) @kbmanager.registry.add_binding(Keys.ControlC) def _(event): event.current_buffer.reset() # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail(self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) app = create_prompt_application(multiline=True, lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer), get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, key_bindings_registry=kbmanager.registry, history=history, completer=IPythonPTCompleter(self.Completer), enable_history_search=True, style=style, mouse_support=self.mouse_support, ) self.pt_cli = CommandLineInterface(app, eventloop=create_eventloop(self.inputhook))
def init_prompt_toolkit_cli(self): if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ): # Simple restricted interface for tests so we can find prompts with # pexpect. Multi-line input not supported. def prompt(): return cast_unicode_py2( input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt self.print_out_prompt = \ lambda: print('Out[%d]: ' % self.execution_count, end='') return kbmanager = KeyBindingManager.for_prompt() insert_mode = ViInsertMode() | EmacsInsertMode() # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode)) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return # Pressing enter flushes any pending display. This also ensures # the displayed execution_count is correct. self.handle_iopub() more, indent = self.check_complete(d.text) if (not more) and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + indent) @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) def _(event): event.current_buffer.reset() @kbmanager.registry.add_binding(Keys.ControlBackslash, filter=HasFocus(DEFAULT_BUFFER)) def _(event): raise EOFError # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail( self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cast_unicode_py2(cell.rstrip()) if cell and (cell != last_cell): history.append(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#ff2200', Token.OutPromptNum: '#ff0000 bold', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) editing_mode = getattr(EditingMode, self.editing_mode.upper()) langinfo = self.kernel_info.get('language_info', {}) lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text')) app = create_prompt_application( multiline=True, editing_mode=editing_mode, lexer=PygmentsLexer(get_pygments_lexer(lexer)), get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, key_bindings_registry=kbmanager.registry, history=history, completer=JupyterPTCompleter(self.Completer), enable_history_search=True, style=style, ) self._eventloop = create_eventloop() self.pt_cli = CommandLineInterface( app, eventloop=self._eventloop, output=create_output(true_color=self.true_color), )
def init_prompt_toolkit_cli(self): if 'JUPYTER_CONSOLE_TEST' in os.environ: # Simple restricted interface for tests so we can find prompts with # pexpect. Multi-line input not supported. def prompt(): return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt self.print_out_prompt = \ lambda: print('Out[%d]: ' % self.execution_count, end='') return kbmanager = KeyBindingManager.for_prompt() insert_mode = ViInsertMode() | EmacsInsertMode() # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode )) def _(event): b = event.current_buffer d = b.document if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return more, indent = self.check_complete(d.text) if (not more) and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + indent) @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) def _(event): event.current_buffer.reset() # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for _, _, cell in self.history_manager.get_tail(self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) style_overrides = { Token.Prompt: '#009900', Token.PromptNum: '#00ff00 bold', Token.OutPrompt: '#ff2200', Token.OutPromptNum: '#ff0000 bold', } if self.highlighting_style: style_cls = get_style_by_name(self.highlighting_style) else: style_cls = get_style_by_name('default') # The default theme needs to be visible on both a dark background # and a light background, because we can't tell what the terminal # looks like. These tweaks to the default theme help with that. style_overrides.update({ Token.Number: '#007700', Token.Operator: 'noinherit', Token.String: '#BB6622', Token.Name.Function: '#2080D0', Token.Name.Class: 'bold #2080D0', Token.Name.Namespace: 'bold #2080D0', }) style_overrides.update(self.highlighting_style_overrides) style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, style_dict=style_overrides) editing_mode = getattr(EditingMode, self.editing_mode.upper()) langinfo = self.kernel_info.get('language_info', {}) lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text')) app = create_prompt_application(multiline=True, editing_mode=editing_mode, lexer=PygmentsLexer(get_pygments_lexer(lexer)), get_prompt_tokens=self.get_prompt_tokens, get_continuation_tokens=self.get_continuation_tokens, key_bindings_registry=kbmanager.registry, history=history, completer=JupyterPTCompleter(self.Completer), enable_history_search=True, style=style, ) self._eventloop = create_eventloop() self.pt_cli = CommandLineInterface(app, eventloop=self._eventloop, output=create_output(true_color=self.true_color), )
def singleline(self, store_in_history=True, auto_suggest=None, enable_history_search=True, multiline=True, **kwargs): """Reads a single line of input from the shell. The store_in_history kwarg flags whether the input should be stored in PTK's in-memory history. """ events.on_pre_prompt.fire() env = builtins.__xonsh_env__ mouse_support = env.get("MOUSE_SUPPORT") if store_in_history: history = self.history else: history = None enable_history_search = False auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None completions_display = env.get("COMPLETIONS_DISPLAY") multicolumn = completions_display == "multi" complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS") if complete_while_typing: # PTK requires history search to be none when completing while typing enable_history_search = False if HAS_PYGMENTS: self.styler.style_name = env.get("XONSH_COLOR_STYLE") completer = None if completions_display == "none" else self.pt_completer if not env.get("UPDATE_PROMPT_ON_KEYPRESS"): prompt_tokens_cached = self.prompt_tokens(None) get_prompt_tokens = lambda cli: prompt_tokens_cached rprompt_tokens_cached = self.rprompt_tokens(None) get_rprompt_tokens = lambda cli: rprompt_tokens_cached bottom_toolbar_tokens_cached = self.bottom_toolbar_tokens(None) get_bottom_toolbar_tokens = lambda cli: bottom_toolbar_tokens_cached else: get_prompt_tokens = self.prompt_tokens get_rprompt_tokens = self.rprompt_tokens get_bottom_toolbar_tokens = self.bottom_toolbar_tokens with self.prompter: prompt_args = { "mouse_support": mouse_support, "auto_suggest": auto_suggest, "get_prompt_tokens": get_prompt_tokens, "get_rprompt_tokens": get_rprompt_tokens, "get_bottom_toolbar_tokens": get_bottom_toolbar_tokens, "completer": completer, "multiline": multiline, "get_continuation_tokens": self.continuation_tokens, "history": history, "enable_history_search": enable_history_search, "reserve_space_for_menu": 0, "key_bindings_registry": self.key_bindings_manager.registry, "display_completions_in_columns": multicolumn, "complete_while_typing": complete_while_typing, } if builtins.__xonsh_env__.get("COLOR_INPUT"): if HAS_PYGMENTS: prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer) prompt_args["style"] = PygmentsStyle( pyghooks.xonsh_style_proxy(self.styler)) else: prompt_args["style"] = style_from_dict(DEFAULT_STYLE_DICT) line = self.prompter.prompt(**prompt_args) events.on_post_prompt.fire() return line
def __init__(self): self.pygments_style = PygmentsStyle.from_defaults(style_dict=ui_style) self._token_to_attrs_dict = None
def create_prompt_application(self, message='', multiline=False, wrap_lines=True, is_password=False, vi_mode=False, complete_while_typing=True, enable_history_search=False, lexer=None, enable_system_bindings=False, enable_open_in_editor=False, validator=None, completer=None, reserve_space_for_menu=8, auto_suggest=None, style=None, history=None, clipboard=None, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, display_completions_in_columns=False, get_title=None, mouse_support=False, extra_input_processors=None, key_bindings_registry=None, on_abort=AbortAction.RAISE_EXCEPTION, on_exit=AbortAction.RAISE_EXCEPTION, accept_action=AcceptAction.RETURN_DOCUMENT, default=''): """Create an :class:`~Application` instance for a prompt. (It is meant to cover 90% of the prompt use cases, where no extreme customization is required. For more complex input, it is required to create a custom :class:`~Application` instance.) message : Text to be shown before the prompt. mulitiline : Allow multiline input. Pressing enter will insert a newline. (This requires Meta+Enter to accept the input.) wrap_lines : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. When True (the default), automatically wrap long lines instead of scrolling horizontally. is_password : Show asterisks instead of the actual typed characters. vi_mode : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. If True, use Vi key bindings. complete_while_typing : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. Enable autocompletion while typing. enable_history_search : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. Enable up-arrow parting string matching. lexer : :class:`~prompt_toolkit.layout.lexers.Lexer` to be used for the syntax highlighting. validator : :class:`~prompt_toolkit.validation.Validator` instance for input validation. completer : :class:`~prompt_toolkit.completion.Completer` instance for input completion. reserve_space_for_menu : Space to be reserved for displaying the menu. (0 means that no space needs to be reserved.) auto_suggest : :class:`~prompt_toolkit.auto_suggest.AutoSuggest` instance for input suggestions. style : Pygments style class for the color scheme. enable_system_bindings : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. Pressing Meta+'!' will show a system prompt. enable_open_in_editor : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. Pressing 'v' in Vi mode or C-X C-E in emacs mode will open an external editor. history : :class:`~prompt_toolkit.history.History` instance. clipboard : :class:`~prompt_toolkit.clipboard.base.Clipboard` instance. (e.g. :class:`~prompt_toolkit.clipboard.in_memory.InMemoryClipboard`) get_bottom_toolbar_tokens : Optional callable which takes a :class:`~prompt_toolkit.interface.CommandLineInterface` and returns a list of tokens for the bottom toolbar. display_completions_in_columns : `bool` or :class:`~prompt_toolkit.filters.CLIFilter`. Display the completions in multiple columns. get_title : Callable that returns the title to be displayed in the terminal. mouse_support : `bool` or :class:`~prompt_toolkit.filters.CLIFilter` to enable mouse support. default : The default text to be shown in the input buffer. (This can be edited by the user.) Notes ----- This method was forked from the mainline prompt-toolkit repo. Copyright (c) 2014, Jonathan Slenders, All rights reserved. WARNING; This method is due for removal once prompt-toolkit >v0.54 is released. """ if key_bindings_registry is None: key_bindings_registry = KeyBindingManager.for_prompt( enable_vi_mode=vi_mode, enable_system_bindings=enable_system_bindings, enable_open_in_editor=enable_open_in_editor).registry # Make sure that complete_while_typing is disabled when enable_history_search # is enabled. (First convert to SimpleFilter, to avoid doing bitwise operations # on bool objects.) complete_while_typing = to_simple_filter(complete_while_typing) enable_history_search = to_simple_filter(enable_history_search) multiline = to_simple_filter(multiline) complete_while_typing = complete_while_typing & ~enable_history_search # Accept Pygments styles as well for backwards compatibility. try: if issubclass(style, pygments.style.Style): style = PygmentsStyle(style) except TypeError: # Happens when style is `None` or an instance of something else. pass # Create application return Application(layout=self.create_prompt_layout( message=message, lexer=lexer, is_password=is_password, reserve_space_for_menu=(reserve_space_for_menu if completer is not None else 0), multiline=Condition(lambda cli: multiline()), get_prompt_tokens=get_prompt_tokens, get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, display_completions_in_columns=display_completions_in_columns, extra_input_processors=extra_input_processors, wrap_lines=wrap_lines), buffer=Buffer( enable_history_search=enable_history_search, complete_while_typing=complete_while_typing, is_multiline=multiline, history=(history or InMemoryHistory()), validator=validator, completer=completer, auto_suggest=auto_suggest, accept_action=accept_action, initial_document=Document(default), ), style=style or DEFAULT_STYLE, clipboard=clipboard, key_bindings_registry=key_bindings_registry, get_title=get_title, mouse_support=mouse_support, on_abort=on_abort, on_exit=on_exit)