Ejemplo n.º 1
0
def create_lexer():
    g = create_ipython_grammar()

    return GrammarLexer(g,
                        lexers={
                            'percent': SimpleLexer('class:pygments.operator'),
                            'magic': SimpleLexer('class:pygments.keyword'),
                            'filename': SimpleLexer('class:pygments.name'),
                            'python': PygmentsLexer(PythonLexer),
                            'system': PygmentsLexer(BashLexer),
                        })
Ejemplo n.º 2
0
def create_lexer():
    g = create_ipython_grammar()

    return GrammarLexer(g,
                        lexers={
                            'percent': SimpleLexer(Token.Operator),
                            'magic': SimpleLexer(Token.Keyword),
                            'filename': SimpleLexer(Token.Name),
                            'python': PygmentsLexer(PythonLexer),
                            'system': PygmentsLexer(BashLexer),
                        })
Ejemplo n.º 3
0
class IPythonPTLexer(Lexer):
    """
    Wrapper around PythonLexer and BashLexer.
    """
    def __init__(self):
        self.python_lexer = PygmentsLexer(Python3Lexer if PY3 else PythonLexer)
        self.shell_lexer = PygmentsLexer(BashLexer)

    def lex_document(self, cli, document):
        if document.text.startswith('!'):
            return self.shell_lexer.lex_document(cli, document)
        else:
            return self.python_lexer.lex_document(cli, document)
Ejemplo n.º 4
0
class IPythonPTLexer(Lexer):
    """
    Wrapper around PythonLexer and BashLexer.
    """
    def __init__(self):
        self.python_lexer = PygmentsLexer(Python3Lexer if PY3 else PythonLexer)
        self.shell_lexer = PygmentsLexer(BashLexer)

    def lex_document(self, cli, document):
        if document.text.startswith('!'):
            return self.shell_lexer.lex_document(cli, document)
        else:
            return self.python_lexer.lex_document(cli, document)
def get_lexers(lex, examLex, toolLex):
    """ gets all the lexer wrappers """
    lexer = None
    if issubclass(lex, PromptLex):
        lexer = lex
    elif issubclass(lex, PygLex):
        lexer = PygmentsLexer(lex)

    if examLex:
        if issubclass(examLex, PygLex):
            examLex = PygmentsLexer(examLex)
    if toolLex:
        if issubclass(toolLex, PygLex):
            toolLex = PygmentsLexer(toolLex)
    return lexer, examLex, toolLex
Ejemplo n.º 6
0
class PdbLexer(Lexer):
    def __init__(self):
        self.python_lexer = PygmentsLexer(PythonLexer)

    def lex_document(self, cli, document):
        parts = document.text.split(None, 1)
        first_word = parts[0] if parts else ''

        # When the first word is a PDB command:
        if first_word in shortcuts.keys() or first_word in commands_with_help.keys():
            # PDB:
            if cli.is_done:
                tokens = [
                    (Token.PdbCommand, ' %s ' % first_word),
                    (Token, ' '),
                    (Token, parts[1] if len(parts) > 1 else ''),
                ]
            else:
                tokens = [(Token.Text, document.text)]

            token_lines = list(split_lines(tokens))
            def get_line(lineno):
                return token_lines[lineno]
            return get_line

        # Otherwise, highlight as Python code.
        else:
            return self.python_lexer.lex_document(cli, document)
Ejemplo n.º 7
0
 def __init__(self, prompt=None, histfile=None, eventloop=None):
     cmd.Cmd.__init__(self)
     self.title = u"mailnex"
     self.completer = Completer(self)
     # ttyBusy tracks times when printing is a Bad Idea
     self.ttyBusy = False
     # lexerEnabled is a marker for the lexer to check before doing
     # interpretations. Currently, this just turns it off when the prompt
     # isn't for the command line but for composing messages.
     self.lexerEnabled = True
     if histfile:
         self.history = prompt_toolkit.history.FileHistory(histfile)
     else:
         self.history = prompt_toolkit.history.InMemoryHistory()
     if prompt is None:
         prompt = "> "
     self.prompt = prompt
     def gpt(cli):
         return [
                 (Token, self.prompt),
                 ]
     self.ptkevloop = ptk_pyuv_wrapper(eventloop)
     registry = KeyBindingManager.for_prompt().registry
     @registry.add_binding(Keys.ControlZ)
     def _(event):
         """Support backrounding ourselves."""
         # I'm surprised this isn't part of the default maps.
         #
         # Ideally, we shouldn't actually have to handle this ourselves; the
         # terminal should handle it for us. However, we are putting the
         # terminal into raw mode, so it won't. The next best thing would be
         # to try to get the actual background character the terminal would
         # use and use that. It is controlZ by default on every Unix system
         # I've used, but it is adjustable, with the 'stty' utility for
         # example.
         # TODO: Figure out how to use an appropriate key here, or allow it
         # to be customized.
         event.cli.suspend_to_background()
     self.cli = prompt_toolkit.interface.CommandLineInterface(
             application = prompt_toolkit.shortcuts.create_prompt_application(
                 u"",
                 #multiline = True,
                 get_prompt_tokens = gpt,
                 style = prompt_style,
                 lexer = PygmentsLexer(PromptLexerFactory(self)),
                 completer = self.completer,
                 history = self.history,
                 auto_suggest = prompt_toolkit.auto_suggest.AutoSuggestFromHistory(),
                 get_title = self.get_title,
                 get_bottom_toolbar_tokens=self.toolbar,
                 key_bindings_registry=registry,
                 ),
             eventloop = self.ptkevloop,
             output = prompt_toolkit.shortcuts.create_output(true_color = False),
     )
     # ui_lines is the number of lines occupied by the UI.
     # For example, 1 line for command prompt, 7 lines for completion menu,
     # 1 line for toolbar.
     self.ui_lines = 9
     self.status = {'unread': None}
Ejemplo n.º 8
0
Archivo: shell.py Proyecto: minrk/xonsh
 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.
     """
     token_func, style_cls = self._get_prompt_tokens_and_style()
     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')
     completer = None if completions_display == 'none' else self.pt_completer
     with self.prompter:
         line = self.prompter.prompt(
                 mouse_support=mouse_support,
                 auto_suggest=auto_suggest,
                 get_prompt_tokens=token_func,
                 style=style_cls,
                 completer=completer,
                 lexer=PygmentsLexer(XonshLexer),
                 multiline=multiline, 
                 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
Ejemplo n.º 9
0
    def _build_cli(self):
        

        get_prompt_tokens = lambda cli: \
                            [(Token.Prompt, '\nIn [%d]: ' % cli.current_buffer.return_count)]
        get_continuation_tokens = lambda cli, width: \
                            [(Token.Continuation, '.' * (width - 1) + ' ')]

        buffer = GoBuffer(
            always_multiline=True,
            accept_action=AcceptAction.RETURN_DOCUMENT
        )
        layout = create_prompt_layout(
            lexer=PygmentsLexer(GoLexer),
            get_prompt_tokens=get_prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            multiline=True
        )
        application = Application(
            layout=layout,
            buffer=buffer,
            style=get_style(),
            key_bindings_registry=key_bindings_registry(),
            ignore_case=True
        )
        render_title = lambda text: zip(itertools.repeat(Token), ['\nQuickGo\n', 'Author: Robus Gauli | [email protected]\n',text,'\n\n'])
        print_tokens(render_title('Version: Experimental 0.0.0'))
        cli = CommandLineInterface(application=application, eventloop=self.event_loop)
        return cli



        
Ejemplo n.º 10
0
def run():
    if not sys.stdin.isatty():
        pager = Pager.from_pipe()
        pager.run()
    else:
        parser = argparse.ArgumentParser(description='Browse through a text file.')
        parser.add_argument('filename', metavar='filename', nargs='+',
                            help='The file to be displayed.')
        parser.add_argument('--vi', help='Prefer Vi key bindings.', action='store_true')
        parser.add_argument('--emacs', help='Prefer Emacs key bindings.', action='store_true')

        args = parser.parse_args()

        # Determine input mode.
        vi_mode = 'vi' in os.environ.get('EDITOR', '').lower()
        if args.vi: vi_mode = True
        if args.emacs: vi_mode = False

        pager = Pager(vi_mode=vi_mode)

        # Open files.
        for filename in args.filename:
            # When a filename is given, take a lexer from that filename.
            lexer = PygmentsLexer.from_filename(filename, sync_from_start=False)

            pager.add_source(FileSource(filename, lexer=lexer))

        # Run UI.
        pager.run()
Ejemplo n.º 11
0
    def _build_cli(self):
        layout = create_prompt_layout(
            message='{0}> '.format(self.args['username']),
            lexer=PygmentsLexer(SqlLexer),
        )

        buf = Buffer(completer=self.completer,
                     history=self.history,
                     complete_while_typing=Always(),
                     accept_action=AcceptAction.RETURN_DOCUMENT)

        key_binding_manager = KeyBindingManager(
            enable_abort_and_exit_bindings=True, )

        application = Application(
            layout=layout,
            buffer=buf,
            key_bindings_registry=key_binding_manager.registry,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True)

        cli = CommandLineInterface(application=application,
                                   eventloop=self.eventloop)

        return cli
Ejemplo n.º 12
0
    def _build_cli(self, history):
        def set_vi_mode(value):
            self.vi_mode = value

        key_binding_manager = mssqlcli_bindings(
            get_vi_mode_enabled=lambda: self.vi_mode,
            set_vi_mode_enabled=set_vi_mode)

        def prompt_tokens(_):
            prompt = self.get_prompt()
            return [(Token.Prompt, prompt)]

        def get_continuation_tokens(cli, width):
            continuation = self.multiline_continuation_char * (width - 1) + ' '
            return [(Token.Continuation, continuation)]

        get_toolbar_tokens = create_toolbar_tokens_func(
            lambda: self.vi_mode, None, None, None)

        layout = create_prompt_layout(
            lexer=PygmentsLexer(PostgresLexer),
            reserve_space_for_menu=self.min_num_menu_lines,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=self.wider_completion_menu,
            multiline=True,
            extra_input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
            ])

        with self._completer_lock:
            buf = MssqlBuffer(auto_suggest=AutoSuggestFromHistory(),
                              always_multiline=self.multi_line,
                              multiline_mode=self.multiline_mode,
                              completer=self.completer,
                              history=history,
                              complete_while_typing=Always(),
                              accept_action=AcceptAction.RETURN_DOCUMENT)

            editing_mode = EditingMode.VI if self.vi_mode else EditingMode.EMACS

            application = Application(
                style=style_factory(self.syntax_style, self.cli_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                ignore_case=True,
                editing_mode=editing_mode)

            cli = CommandLineInterface(application=application,
                                       eventloop=self.eventloop)

            return cli
Ejemplo n.º 13
0
class PdbLexer(Lexer):
    def __init__(self):
        self.python_lexer = PygmentsLexer(PythonLexer)

    def lex_document(self, cli, document):
        parts = document.text.split(None, 1)
        first_word = parts[0] if parts else ''

        # When the first word is a PDB command:
        if first_word in shortcuts.keys(
        ) or first_word in commands_with_help.keys():
            # PDB:
            if cli.is_done:
                tokens = [
                    (Token.PdbCommand, ' %s ' % first_word),
                    (Token, ' '),
                    (Token, parts[1] if len(parts) > 1 else ''),
                ]
            else:
                tokens = [(Token.Text, document.text)]

            token_lines = list(split_lines(tokens))

            def get_line(lineno):
                return token_lines[lineno]

            return get_line

        # Otherwise, highlight as Python code.
        else:
            return self.python_lexer.lex_document(cli, document)
Ejemplo n.º 14
0
def cli(url, http_options):
    click.echo('Version: %s' % __version__)

    # Override less options
    os.environ['LESS'] = '-RXF'

    url = fix_incomplete_url(url)
    context = Context(url)

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    style = style_from_pygments(get_style_by_name('monokai'))

    # Execute default http options.
    execute(' '.join(http_options), context)

    while True:
        try:
            text = prompt('%s> ' % context.url,
                          completer=completer,
                          lexer=lexer,
                          style=style,
                          history=history)
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context)
            if context.should_exit:
                break

    click.echo("Goodbye!")
Ejemplo n.º 15
0
 def display_help(self):
     """
     Display help text.
     """
     if not self.displaying_help:
         source = StringSource(HELP, lexer=PygmentsLexer(RstLexer))
         self.add_source(source)
         self.displaying_help = True
Ejemplo n.º 16
0
def get_lexers(main_lex, exam_lex, tool_lex):
    """ gets all the lexer wrappers """
    if not main_lex:
        return None, None, None
    lexer = None
    if issubclass(main_lex, PromptLex):
        lexer = main_lex
    elif issubclass(main_lex, PygLex):
        lexer = PygmentsLexer(main_lex)

    if exam_lex:
        if issubclass(exam_lex, PygLex):
            exam_lex = PygmentsLexer(exam_lex)
    if tool_lex:
        if issubclass(tool_lex, PygLex):
            tool_lex = PygmentsLexer(tool_lex)
    return lexer, exam_lex, tool_lex
Ejemplo n.º 17
0
def cli(url, http_options):
    click.echo('Version: %s' % __version__)

    copied, config_path = config.initialize()
    if copied:
        click.echo('Config file not found. Initialized a new one: %s' %
                   config_path)

    cfg = config.load()

    # Override pager/less options
    os.environ['PAGER'] = cfg['pager']
    os.environ['LESS'] = '-RXF'

    url = fix_incomplete_url(url)
    context = Context(url)

    output_style = cfg.get('output_style')
    if output_style:
        context.options['--style'] = output_style

    # For prompt-toolkit
    history = InMemoryHistory()
    lexer = PygmentsLexer(HttpPromptLexer)
    completer = HttpPromptCompleter(context)
    try:
        style = get_style_by_name(cfg['command_style'])
    except ClassNotFound:
        style = style_from_pygments(Solarized256Style)
    else:
        style = style_from_pygments(style)

    listener = ExecutionListener(cfg)

    # Execute HTTPie options from CLI or load from last context
    if len(sys.argv) > 1:
        http_options = [smart_quote(a) for a in http_options]
        execute(' '.join(http_options), context, listener=listener)
    else:
        load_context(context)

    while True:
        try:
            text = prompt('%s> ' % context.url,
                          completer=completer,
                          lexer=lexer,
                          style=style,
                          history=history,
                          auto_suggest=AutoSuggestFromHistory(),
                          on_abort=AbortAction.RETRY)
        except EOFError:
            break  # Control-D pressed
        else:
            execute(text, context, listener=listener)
            if context.should_exit:
                break

    click.echo("Goodbye!")
Ejemplo n.º 18
0
    def __init__(self):
        l = pygments_lexers
        self.python_lexer = PygmentsLexer(l.Python3Lexer if PY3 else l.PythonLexer)
        self.shell_lexer = PygmentsLexer(l.BashLexer)

        self.magic_lexers = {
            'HTML': PygmentsLexer(l.HtmlLexer),
            'html': PygmentsLexer(l.HtmlLexer),
            'javascript': PygmentsLexer(l.JavascriptLexer),
            'js': PygmentsLexer(l.JavascriptLexer),
            'perl': PygmentsLexer(l.PerlLexer),
            'ruby': PygmentsLexer(l.RubyLexer),
            'latex': PygmentsLexer(l.TexLexer),
        }
Ejemplo n.º 19
0
 def prompt(self):
     try:
         return prompt(get_prompt_tokens=getPromptTokens,
                       history=self.history,
                       auto_suggest=shellSuggester(),
                       completer=shellCompleter(),
                       lexer=PygmentsLexer(shellLexer))
     except EOFError:
         return "CTRL+D"
Ejemplo n.º 20
0
    def _build_cli(self):
        eventloop = create_eventloop()

        if self._options.persistent_history:
            history = FileHistory(
                os.path.join(
                    os.path.expanduser("~"), ".{}_history".format(self._ctx.binary_name)
                )
            )
        else:
            history = InMemoryHistory()

        layout = create_prompt_layout(
            lexer=PygmentsLexer(NubiaLexer),
            reserve_space_for_menu=5,
            get_prompt_tokens=self.get_prompt_tokens,
            get_rprompt_tokens=self._status_bar.get_rprompt_tokens,
            get_bottom_toolbar_tokens=self._status_bar.get_tokens,
            display_completions_in_columns=False,
            multiline=True,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
        )

        buf = Buffer(
            completer=self._completer,
            history=history,
            auto_suggest=self._suggestor,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT,
        )

        # If EDITOR does not exist, take EMACS
        # if it does, try fit the EMACS/VI pattern using upper
        editor = getattr(
            EditingMode,
            os.environ.get("EDITOR", EditingMode.EMACS).upper(),
            EditingMode.EMACS,
        )

        application = Application(
            style=shell_style,
            buffer=buf,
            editing_mode=editor,
            key_bindings_registry=self._registry,
            layout=layout,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True,
        )

        cli = CommandLineInterface(application=application, eventloop=eventloop)
        return cli
Ejemplo n.º 21
0
    def lex_document(self, cli, document):
        """
        Call the lexer and return a get_tokens_for_line function.
        """
        location = self.editor_buffer.location

        if location:
            return PygmentsLexer.from_filename(location, sync_from_start=False).lex_document(cli, document)

        return SimpleLexer().lex_document(cli, document)
Ejemplo n.º 22
0
def main():
    """
    """
    history = InMemoryHistory()
    while True:
        text = prompt('> ',
                      lexer=PygmentsLexer(HtmlLexer),
                      completer=EsToolkitCompleter(),
                      history=history)
        print('You said: %s' % text)
Ejemplo n.º 23
0
    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
Ejemplo n.º 24
0
def prompt_bash(msg: str, allow_empty: bool) -> str:
    """
    Prompts for bash shell code.

    :param msg: shown message
    :param allow_empty: allow an empty string?
    :return: user input
    """
    from pygments.lexers.shell import BashLexer
    validator = None if allow_empty else NonEmptyValidator()
    return prompt(msg, lexer=PygmentsLexer(BashLexer), completer=SystemCompleter())
Ejemplo n.º 25
0
def create_command_lexer():
    """
    Lexer for highlighting of the command line.
    """
    return GrammarLexer(COMMAND_GRAMMAR,
                        lexers={
                            'command': SimpleLexer(Token.CommandLine.Command),
                            'location':
                            SimpleLexer(Token.CommandLine.Location),
                            'shell_command': PygmentsLexer(BashLexer),
                        })
Ejemplo n.º 26
0
def shell():
    c = Chitin()

    cmd_history = FileHistory(os.path.expanduser('~') + '/.chitin.history')
    print(WELCOME)
    message = VERSION

    def get_bottom_toolbar_tokens(cli):
        return [(Token.Toolbar, ' ' + message)]

    style = style_from_dict({
        Token.Toolbar: '#ffffff bg:#333333',
    })
    completer = SystemCompleter()
    del completer.completers["executable"]

    # Check whether files in and around the current directory have been changed...
    for failed in util.check_integrity_set(set(".")):
        print("[WARN] '%s' has been modified outside of lab book." % failed)
    try:
        while True:
            cmd_str = ""
            while len(cmd_str.strip()) == 0:
                cmd_str = prompt(
                    u'===> ',
                    history=cmd_history,
                    auto_suggest=AutoSuggestFromHistory(),
                    completer=completer,
                    lexer=PygmentsLexer(BashLexer),
                    get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
                    style=style,
                    on_abort=AbortAction.RETRY,
                )

            fields = cmd_str.split(" ")
            command_set = [" ".join(fields)]

            skip, special_command_set = c.attempt_special(cmd_str)
            if skip:
                continue
            if len(special_command_set) > 0:
                command_set = special_command_set

            #####################################
            handled = c.super_handle(command_set)
            if handled:
                if "message" in handled:
                    message = handled["message"]
                else:
                    message = VERSION
            #####################################

    except EOFError:
        print("Bye!")
Ejemplo n.º 27
0
def loop(
    project, dataset, history_file, completion, multiline, verbose, true_color
):
    import ibis

    history = FileHistory(history_file)
    lexer = PygmentsLexer(PostgresLexer)
    con = ibis.bigquery.connect(project, dataset)

    while True:
        def get_prompt_tokens(cli):
            return [
                (Token.Project, con.data_project),
                (Token.ProjectDatasetDot, '.'),
                (Token.Dataset, con.dataset_id),
                (Token.RightAngle, ' > '),
            ]
        try:
            query = prompt(
                get_prompt_tokens=get_prompt_tokens,
                style=style,
                lexer=lexer,
                history=history,
                multiline=multiline,
                true_color=true_color,
            )
            if not query:
                continue

            if verbose:
                print(query)

            lower_query = query.lower()
            if lower_query.startswith(('show', 'describe')):
                meta(con, lower_query)
                continue
        except KeyboardInterrupt:
            pass
        except EOFError:
            return 0
        else:
            try:
                cursor = con.raw_sql(query)
                result = cursor.query.to_dataframe()
            except KeyboardInterrupt:
                pass
            except BadRequest as e:
                error, = e.errors
                if error['reason'] == 'invalidQuery':
                    print(e.message)
                else:
                    raise
            else:
                print(result)
Ejemplo n.º 28
0
    def open_file(self, filename):
        """
        Open this file.
        """
        lexer = PygmentsLexer.from_filename(filename, sync_from_start=False)

        try:
            source = FileSource(filename, lexer=lexer)
        except IOError as e:
            self.message = '{}'.format(e)
        else:
            self.add_source(source)
Ejemplo n.º 29
0
    def __init__(self, uri=None, **settings):
        self.output_file = settings.pop("file", None)
        verbose = settings.pop("verbose", False)
        connection_data = get_connection_data(uri, **settings)
        try:
            self.graph = Graph(uri, **settings)
        except ServiceUnavailable as error:
            raise ConsoleError("Could not connect to {} -- {}".format(
                connection_data["uri"], error))
        try:
            makedirs(HISTORY_FILE_DIR)
        except OSError:
            pass
        self.history = FileHistory(path_join(HISTORY_FILE_DIR, HISTORY_FILE))
        self.prompt_args = {
            "history":
            self.history,
            "lexer":
            PygmentsLexer(CypherLexer),
            "style":
            style_from_pygments(
                VimStyle, {
                    Token.Prompt:
                    "#ansi{}".format(self.prompt_colour.replace(
                        "cyan", "teal")),
                    Token.TxCounter:
                    "#ansi{} bold".format(
                        self.tx_colour.replace("cyan", "teal")),
                })
        }
        self.lexer = CypherLexer()
        self.result_writer = Table.write
        if verbose:
            from neo4j.util import watch
            self.watcher = watch("neo4j.%s" % connection_data["scheme"])

        self.commands = {
            "//": self.set_multi_line,
            "/e": self.edit,
            "/?": self.help,
            "/h": self.help,
            "/help": self.help,
            "/x": self.exit,
            "/exit": self.exit,
            "/play": self.play,
            "/csv": self.set_csv_result_writer,
            "/table": self.set_tabular_result_writer,
            "/tsv": self.set_tsv_result_writer,
            "/config": self.config,
            "/kernel": self.kernel,
        }
        self.tx = None
        self.tx_counter = 0
Ejemplo n.º 30
0
    def _build_cli(self, history):
        def set_vi_mode(value):
            self.vi_mode = value

        key_binding_manager = pgcli_bindings(
            get_vi_mode_enabled=lambda: self.vi_mode,
            set_vi_mode_enabled=set_vi_mode)

        def prompt_tokens(_):
            return [(Token.Prompt, '%s> ' % self.pgexecute.dbname)]

        def get_continuation_tokens(cli, width):
            return [(Token.Continuation, '.' * (width - 1) + ' ')]

        get_toolbar_tokens = create_toolbar_tokens_func(
            lambda: self.vi_mode, self.completion_refresher.is_refreshing)

        layout = create_prompt_layout(
            lexer=PygmentsLexer(PostgresLexer),
            reserve_space_for_menu=4,
            get_prompt_tokens=prompt_tokens,
            get_continuation_tokens=get_continuation_tokens,
            get_bottom_toolbar_tokens=get_toolbar_tokens,
            display_completions_in_columns=self.wider_completion_menu,
            multiline=True,
            extra_input_processors=[
                # Highlight matching brackets while editing.
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
            ])

        with self._completer_lock:
            buf = PGBuffer(always_multiline=self.multi_line,
                           completer=self.completer,
                           history=history,
                           complete_while_typing=Always(),
                           accept_action=AcceptAction.RETURN_DOCUMENT)

            application = Application(
                style=style_factory(self.syntax_style, self.cli_style),
                layout=layout,
                buffer=buf,
                key_bindings_registry=key_binding_manager.registry,
                on_exit=AbortAction.RAISE_EXCEPTION,
                on_abort=AbortAction.RETRY,
                ignore_case=True)

            cli = CommandLineInterface(application=application)

            return cli
Ejemplo n.º 31
0
def prompt_python(msg: str, get_globals: t.Callable[[str], t.Any], get_locals: t.Callable[[str], t.Any]) -> str:
    """
    Prompt for python code.

    :param get_globals: function that returns the global variables
    :param get_locals: function that returns the local variables
    :return: user input
    """
    from ptpython.completer import PythonCompleter
    from pygments.lexers.python import Python3Lexer
    python_completer = PythonCompleter(get_globals, get_locals)
    return prompt(msg, multiline=True, mouse_support=True, lexer=PygmentsLexer(Python3Lexer),
                         completer=python_completer)
Ejemplo n.º 32
0
def prompt_for_command(args, connection, history):
    try:
        cmd = prompt('> ', lexer=PygmentsLexer(SqlLexer), history=history)
        if cmd.startswith(_command_prefix):
            process_command(cmd, connection, args)
        else:
            result = connection.execute(cmd)
            print_result(result)
    except KeyboardInterrupt:
        return
    except EOFError:
        sys.exit(0)
    except Exception as e:
        print(e)
        return
Ejemplo n.º 33
0
    def _build_cli(self):
        eventloop = create_eventloop()

        history = FileHistory(
            os.path.join(
                os.path.expanduser("~"),
                ".{}_history".format(self._ctx.binary_name),
            ))

        layout = create_prompt_layout(
            lexer=PygmentsLexer(NubiaLexer),
            reserve_space_for_menu=5,
            get_prompt_tokens=self.get_prompt_tokens,
            get_rprompt_tokens=self._status_bar.get_rprompt_tokens,
            get_bottom_toolbar_tokens=self._status_bar.get_tokens,
            display_completions_in_columns=False,
            multiline=True,
            extra_input_processors=[
                ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars="[](){}"),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(),
                )
            ],
        )

        buf = Buffer(
            completer=self._completer,
            history=history,
            auto_suggest=self._suggestor,
            complete_while_typing=Always(),
            accept_action=AcceptAction.RETURN_DOCUMENT,
        )

        application = Application(
            style=shell_style,
            buffer=buf,
            key_bindings_registry=self._registry,
            layout=layout,
            on_exit=AbortAction.RAISE_EXCEPTION,
            on_abort=AbortAction.RETRY,
            ignore_case=True,
        )

        cli = CommandLineInterface(application=application,
                                   eventloop=eventloop)
        return cli
Ejemplo n.º 34
0
class PdbLexer(Lexer):
    def __init__(self):
        self.python_lexer = PygmentsLexer(PythonLexer)

    def get_tokens(self, cli, text):
        parts = text.split(None, 1)
        first_word = parts[0] if parts else ''

        # When the first word is a PDB command:
        if first_word in shortcuts.keys() or first_word in commands_with_help.keys():
            # PDB:
            if cli.is_done:
                return [
                    (Token.PdbCommand, ' %s ' % first_word),
                    (Token, ' '),
                    (Token, parts[1] if len(parts) > 1 else ''),
                ]
            else:
                return [(Token.Text, text)]

        # Otherwise, highlight as Python code.
        else:
            return self.python_lexer.get_tokens(cli, text)
Ejemplo n.º 35
0
 def __init__(self):
     self.python_lexer = PygmentsLexer(PythonLexer)
Ejemplo n.º 36
0
 def __init__(self):
     self.python_lexer = PygmentsLexer(Python3Lexer if PY3 else PythonLexer)
     self.shell_lexer = PygmentsLexer(BashLexer)