Esempio n. 1
0
def get_bpython_history_path() -> Optional[Path]:
    try:
        config = Struct()
        loadini(config, Path(get_config_home()).expanduser() / "config")
        return Path(config.hist_file).expanduser()
    except TypeError:
        return None
Esempio n. 2
0
    def __init__(self):
        logging.debug("starting init")
        interp = code.InteractiveInterpreter()
        config = Struct()
        loadini(config, default_config_path())
        config.autocomplete_mode = SIMPLE # only one implemented currently
        logging.debug("starting parent init")
        super(Repl, self).__init__(interp, config)

        self._current_line = ''
        self.current_formatted_line = fmtstr('')
        self.display_lines = [] # lines separated whenever logical line
                                # length goes over what the terminal width
                                # was at the time of original output
        self.history = [] # this is every line that's been executed;
                                # it gets smaller on rewind
        self.display_buffer = []
        self.formatter = BPythonFormatter(config.color_scheme)
        self.scroll_offset = 0
        self.cursor_offset_in_line = 0
        self.done = True

        self.paste_mode = False

        self.width = None
        self.height = None
        self.start_background_tasks()
Esempio n. 3
0
def string_to_fmtstr(x):
    from pygments import format
    from bpython.formatter import BPythonFormatter
    from bpython._py3compat import PythonLexer
    from bpython.config import Struct, loadini, default_config_path
    config = Struct()
    loadini(config, default_config_path())
    return parse(format(PythonLexer().get_tokens(x), BPythonFormatter(config.color_scheme)))
Esempio n. 4
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, TEST_CONFIG)
    for key, value in conf.items():
        if not hasattr(config_struct, key):
            raise ValueError(f"{key!r} is not a valid config attribute")
        setattr(config_struct, key, value)
    return config_struct
Esempio n. 5
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    for key, value in conf.items():
        if not hasattr(config_struct, key):
            raise ValueError("%r is not a valid config attribute" % (key, ))
        setattr(config_struct, key, value)
    return config_struct
Esempio n. 6
0
def string_to_fmtstr(x):
    from pygments import format
    from bpython.formatter import BPythonFormatter
    from bpython._py3compat import PythonLexer
    from bpython.config import Struct, loadini, default_config_path
    config = Struct()
    loadini(config, default_config_path())
    return parse(format(PythonLexer().get_tokens(x), BPythonFormatter(config.color_scheme)))
Esempio n. 7
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    for key, value in conf.items():
        if not hasattr(config_struct, key):
            raise ValueError("%r is not a valid config attribute", (key,))
        setattr(config_struct, key, value)
    return config_struct
Esempio n. 8
0
def main(args=None, locals_=None, banner=None):
    translations.init()
    config = Struct()
    loadini(config, default_config_path())
    module_gatherer = ModuleGatherer()
    while module_gatherer.find_coroutine():
        pass
    with SimpleRepl(config) as r:
        r.width = 50
        r.height = 10
        while True:
            r.print_output()
            r.get_input()
Esempio n. 9
0
    def load_temp_config(self, content, struct=None):
        """Write config to a temporary file and load it."""

        if struct is None:
            struct = config.Struct()

        with tempfile.NamedTemporaryFile() as f:
            f.write(content.encode('utf8'))
            f.flush()

            config.loadini(struct, f.name)

        return struct
Esempio n. 10
0
    def load_temp_config(self, content, struct=None):
        """Write config to a temporary file and load it."""

        if struct is None:
            struct = config.Struct()

        with tempfile.NamedTemporaryFile() as f:
            f.write(content.encode("utf8"))
            f.flush()

            config.loadini(struct, f.name)

        return struct
Esempio n. 11
0
def test():
    from pygments import format
    from bpython.formatter import BPythonFormatter
    from bpython._py3compat import PythonLexer
    from bpython.config import Struct, loadini, default_config_path
    config = Struct()
    loadini(config, default_config_path())

    all_tokens = list(PythonLexer().get_tokens('print 1 + 2'))
    formatted_line = format(all_tokens, BPythonFormatter(config.color_scheme))
    print((repr(formatted_line)))
    fs = parse(formatted_line)
    print((repr(fs)))
    print(fs)

    string_to_fmtstr('asdf')
Esempio n. 12
0
def test():
    from pygments import format
    from bpython.formatter import BPythonFormatter
    from bpython._py3compat import PythonLexer
    from bpython.config import Struct, loadini, default_config_path
    config = Struct()
    loadini(config, default_config_path())

    all_tokens = list(PythonLexer().get_tokens('print(1 + 2)'))
    formatted_line = format(all_tokens, BPythonFormatter(config.color_scheme))
    print((repr(formatted_line)))
    fs = parse(formatted_line)
    print((repr(fs)))
    print(fs)

    string_to_fmtstr('asdf')
Esempio n. 13
0
    def __init__(self):
        logging.debug("starting init")
        interp = code.InteractiveInterpreter()

        config = Struct()
        loadini(config, default_config_path())
        config.autocomplete_mode = SIMPLE # only one implemented currently

        #TODO determine if this is supposed to use this, or if it should be
        # frontend specific.
        if config.cli_suggestion_width <= 0 or config.cli_suggestion_width > 1:
            config.cli_suggestion_width = 1

        self.status_bar = StatusBar(_('welcome to bpython'))
        self.rl_char_sequences = get_updated_char_sequences(key_dispatch, config)
        logging.debug("starting parent init")
        super(Repl, self).__init__(interp, config)
        self.formatter = BPythonFormatter(config.color_scheme)
        self.interact = self.status_bar # overwriting what bpython.Repl put there
                                        # interact is called to interact with the status bar,
                                        # so we're just using the same object
        self._current_line = '' # line currently being edited, without '>>> '
        self.current_formatted_line = fmtstr('') # needs to be updated before each draw
                                                 # by calling set_formatted_line
        self.display_lines = [] # lines separated whenever logical line
                                # length goes over what the terminal width
                                # was at the time of original output
        self.history = [] # this is every line that's been executed;
                                # it gets smaller on rewind
        self.display_buffer = [] # formatted version of lines in the buffer
                                 # kept around so we can unhighlight parens
                                 # using self.reprint_line as called by
                                 # bpython.Repl
        self.scroll_offset = 0
        self.cursor_offset_in_line = 0 # from the left, 0 means first char
        self.done = True

        self.paste_mode = False

        self.width = None
        self.height = None
        self.start_background_tasks()
Esempio n. 14
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    if 'autocomplete_mode' in conf:
        config_struct.autocomplete_mode = conf['autocomplete_mode']
    return config_struct
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    if 'autocomplete_mode' in conf:
        config_struct.autocomplete_mode = conf['autocomplete_mode']
    return config_struct
Esempio n. 16
0
def parse(args, extras=None, ignore_stdin=False):
    """Receive an argument list - if None, use sys.argv - parse all args and
    take appropriate action. Also receive optional extra options: this should
    be a tuple of (title, description, options)
        title:          The title for the option group
        description:    A full description of the option group
        options:        A list of optparse.Option objects to be added to the
                        group

    e.g.:

    parse(['-i', '-m', 'foo.py'],
          ('Front end-specific options',
          'A full description of what these options are for',
          [optparse.Option('-f', action='store_true', dest='f', help='Explode'),
           optparse.Option('-l', action='store_true', dest='l', help='Love')]))


    Return a tuple of (config, options, exec_args) wherein "config" is the
    config object either parsed from a default/specified config file or default
    config options, "options" is the parsed options from
    OptionParser.parse_args, and "exec_args" are the args (if any) to be parsed
    to the executed file (if any).
    """
    if args is None:
        args = sys.argv[1:]

    parser = RaisingOptionParser(
        usage=_('Usage: %prog [options] [file [args]]\n'
                'NOTE: If bpython sees an argument it does '
                'not know, execution falls back to the '
                'regular Python interpreter.'))
    # This is not sufficient if bpython gains its own -m support
    # (instead of falling back to Python itself for that).
    # That's probably fixable though, for example by having that
    # option swallow all remaining arguments in a callback.
    parser.disable_interspersed_args()
    parser.add_option('--config', default=default_config_path(),
                      help=_('Use CONFIG instead of default config file.'))
    parser.add_option('--interactive', '-i', action='store_true',
                      help=_('Drop to bpython shell after running file '
                             'instead of exiting.'))
    parser.add_option('--quiet', '-q', action='store_true',
                      help=_("Don't flush the output to stdout."))
    parser.add_option('--version', '-V', action='store_true',
                      help=_('Print version and exit.'))

    if extras is not None:
        extras_group = OptionGroup(parser, extras[0], extras[1])
        for option in extras[2]:
            extras_group.add_option(option)
        parser.add_option_group(extras_group)

    try:
        options, args = parser.parse_args(args)
    except OptionParserFailed:
        # Just let Python handle this
        os.execv(sys.executable, [sys.executable] + args)

    if options.version:
        print('bpython version', __version__, end=' ')
        print('on top of Python', sys.version.split()[0])
        print('(C) 2008-2012 Bob Farrell, Andreas Stuehrk et al. '
              'See AUTHORS for detail.')
        raise SystemExit

    if not ignore_stdin and not (sys.stdin.isatty() and sys.stdout.isatty()):
        interpreter = code.InteractiveInterpreter()
        interpreter.runsource(sys.stdin.read())
        raise SystemExit

    config = Struct()
    loadini(config, options.config)

    return config, options, args
Esempio n. 17
0
def setup_config():
    config_struct = config.Struct()
    config.loadini(config_struct, TEST_CONFIG)
    config_struct.cli_suggestion_width = 1
    return config_struct
Esempio n. 18
0
def parse(args, extras=None, ignore_stdin=False):
    """Receive an argument list - if None, use sys.argv - parse all args and
    take appropriate action. Also receive optional extra options: this should
    be a tuple of (title, description, options)
        title:          The title for the option group
        description:    A full description of the option group
        options:        A list of optparse.Option objects to be added to the
                        group

    e.g.:

    parse(
        ['-i', '-m', 'foo.py'],
        ('Front end-specific options',
        'A full description of what these options are for',
        [optparse.Option('-f', action='store_true', dest='f', help='Explode'),
        optparse.Option('-l', action='store_true', dest='l', help='Love')]))


    Return a tuple of (config, options, exec_args) wherein "config" is the
    config object either parsed from a default/specified config file or default
    config options, "options" is the parsed options from
    OptionParser.parse_args, and "exec_args" are the args (if any) to be parsed
    to the executed file (if any).
    """
    if args is None:
        args = sys.argv[1:]

    parser = RaisingOptionParser(
        usage=_('Usage: %prog [options] [file [args]]\n'
                'NOTE: If bpython sees an argument it does '
                'not know, execution falls back to the '
                'regular Python interpreter.'))
    # This is not sufficient if bpython gains its own -m support
    # (instead of falling back to Python itself for that).
    # That's probably fixable though, for example by having that
    # option swallow all remaining arguments in a callback.
    parser.disable_interspersed_args()
    parser.add_option('--config',
                      default=default_config_path(),
                      help=_('Use CONFIG instead of default config file.'))
    parser.add_option('--interactive',
                      '-i',
                      action='store_true',
                      help=_('Drop to bpython shell after running file '
                             'instead of exiting.'))
    parser.add_option('--quiet',
                      '-q',
                      action='store_true',
                      help=_("Don't flush the output to stdout."))
    parser.add_option('--version',
                      '-V',
                      action='store_true',
                      help=_('Print version and exit.'))

    if extras is not None:
        extras_group = OptionGroup(parser, extras[0], extras[1])
        for option in extras[2]:
            extras_group.add_option(option)
        parser.add_option_group(extras_group)

    try:
        options, args = parser.parse_args(args)
    except OptionParserFailed:
        # Just let Python handle this
        os.execv(sys.executable, [sys.executable] + args)

    if options.version:
        print('bpython version', __version__, end=" ")
        print('on top of Python', sys.version.split()[0])
        print('(C) 2008-2015 Bob Farrell, Andreas Stuehrk et al. '
              'See AUTHORS for detail.')
        raise SystemExit

    if not ignore_stdin and not (sys.stdin.isatty() and sys.stdout.isatty()):
        interpreter = code.InteractiveInterpreter()
        interpreter.runsource(sys.stdin.read())
        raise SystemExit

    config = Struct()
    loadini(config, options.config)

    return config, options, args
Esempio n. 19
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, TEST_CONFIG)
    if 'autocomplete_mode' in conf:
        config_struct.autocomplete_mode = conf['autocomplete_mode']
    return config_struct
Esempio n. 20
0
def setup_config():
    config_struct = config.Struct()
    config.loadini(config_struct, TEST_CONFIG)
    config_struct.cli_suggestion_width = 1
    return config_struct
Esempio n. 21
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, TEST_CONFIG)
    if conf is not None and "autocomplete_mode" in conf:
        config_struct.autocomplete_mode = conf["autocomplete_mode"]
    return config_struct
Esempio n. 22
0
 def __init__(self):
     config_struct = config.Struct()
     config.loadini(config_struct, os.devnull)
     repl.Repl.__init__(self, repl.Interpreter(), config_struct)
     self.input_line = ""
Esempio n. 23
0
def string_to_fmtstr(x):
    config = Struct()
    loadini(config, default_config_path())
    return parse(format(PythonLexer().get_tokens(x), BPythonFormatter(config.color_scheme)))
Esempio n. 24
0
def setup_config():
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    return config_struct
Esempio n. 25
0
def setup_config():
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    return config_struct
Esempio n. 26
0
def setup_config():
    config_struct = config.Struct()
    config.loadini(config_struct, os.devnull)
    config_struct.cli_suggestion_width = 1
    return config_struct
Esempio n. 27
0
 def __init__(self):
     config_struct = config.Struct()
     config.loadini(config_struct, os.devnull)
     repl.Repl.__init__(self, repl.Interpreter(), config_struct)
     self.input_line = ""
Esempio n. 28
0
def setup_config(conf):
    config_struct = config.Struct()
    config.loadini(config_struct, TEST_CONFIG)
    if conf is not None and 'autocomplete_mode' in conf:
        config_struct.autocomplete_mode = conf['autocomplete_mode']
    return config_struct
Esempio n. 29
0
    def __init__(self, locals_=None, config=None, request_refresh=lambda: None, banner=None, interp=None):
        """
        locals_ is a mapping of locals to pass into the interpreter
        config is a bpython config.Struct with config attributes
        request_refresh is a function that will be called when the Repl
            wants to refresh the display, but wants control returned to it afterwards
        banner is a string to display briefly in the status bar
        interp is an interpreter to use
        """

        logging.debug("starting init")

        if config is None:
            config = Struct()
            loadini(config, default_config_path())

        self.weak_rewind = bool(locals_ or interp) # If creating a new interpreter on undo
                                                   # would be unsafe because initial
                                                   # state was passed in
        if interp is None:
            interp = code.InteractiveInterpreter(locals=locals_)
        if banner is None:
            banner = _('welcome to bpython')
        config.autocomplete_mode = SIMPLE # only one implemented currently
        if config.cli_suggestion_width <= 0 or config.cli_suggestion_width > 1:
            config.cli_suggestion_width = 1

        self.reevaluating = False
        self.fake_refresh_requested = False
        def smarter_request_refresh():
            if self.reevaluating or self.paste_mode:
                self.fake_refresh_requested = True
            else:
                request_refresh()
        self.request_refresh = smarter_request_refresh

        self.status_bar = StatusBar(banner if config.curtsies_fill_terminal else '', _(
            " <%s> Rewind  <%s> Save  <%s> Pastebin <%s> Editor"
            ) % (config.undo_key, config.save_key, config.pastebin_key, config.external_editor_key),
            refresh_request=self.request_refresh
            )
        self.rl_char_sequences = get_updated_char_sequences(key_dispatch, config)
        logging.debug("starting parent init")
        super(Repl, self).__init__(interp, config)
        self.formatter = BPythonFormatter(config.color_scheme)
        self.interact = self.status_bar # overwriting what bpython.Repl put there
                                        # interact is called to interact with the status bar,
                                        # so we're just using the same object
        self._current_line = '' # line currently being edited, without '>>> '
        self.current_stdouterr_line = '' # current line of output - stdout and stdin go here
        self.display_lines = [] # lines separated whenever logical line
                                # length goes over what the terminal width
                                # was at the time of original output
        self.history = [] # this is every line that's been executed;
                          # it gets smaller on rewind
        self.display_buffer = [] # formatted version of lines in the buffer
                                 # kept around so we can unhighlight parens
                                 # using self.reprint_line as called by
                                 # bpython.Repl
        self.scroll_offset = 0 # how many times display has been scrolled down
                               # because there wasn't room to display everything
        self.cursor_offset_in_line = 0 # from the left, 0 means first char

        self.coderunner = CodeRunner(self.interp, self.request_refresh)
        self.stdout = FakeOutput(self.coderunner, self.send_to_stdout)
        self.stderr = FakeOutput(self.coderunner, self.send_to_stderr)
        self.stdin = FakeStdin(self.coderunner, self)

        self.request_paint_to_clear_screen = False # next paint should clear screen
        self.last_events = [None] * 50
        self.presentation_mode = False
        self.paste_mode = False

        self.width = None  # will both be set by a window resize event
        self.height = None