def __init__(self, interp, config): """Initialise the repl. interp is a Python code.InteractiveInterpreter instance config is a populated bpython.config.Struct. """ self.config = config self.cut_buffer = '' self.buffer = [] self.interp = interp self.interp.syntaxerror_callback = self.clear_current_line self.match = False self.rl_history = History(duplicates=config.hist_duplicates, hist_size=config.hist_length) self.s_hist = [] self.history = [] self.evaluating = False self.matches_iter = MatchesIterator() self.funcprops = None self.arg_pos = None self.current_func = None self.highlighted_paren = None self._C = {} self.prev_block_finished = 0 self.interact = Interaction(self.config) # previous pastebin content to prevent duplicate pastes, filled on call # to repl.pastebin self.prev_pastebin_content = '' self.prev_pastebin_url = '' self.prev_removal_url = '' # Necessary to fix mercurial.ui.ui expecting sys.stderr to have this # attribute self.closed = False self.clipboard = get_clipboard() pythonhist = os.path.expanduser(self.config.hist_file) if os.path.exists(pythonhist): try: self.rl_history.load(pythonhist, getpreferredencoding() or "ascii") except EnvironmentError: pass self.completers = autocomplete.get_default_completer( config.autocomplete_mode) if self.config.pastebin_helper: self.paster = PasteHelper(self.config.pastebin_helper) else: self.paster = PastePinnwand(self.config.pastebin_url, self.config.pastebin_expiry, self.config.pastebin_show_url, self.config.pastebin_removal_url)
def test_save(self): history = History() history.entries = [] for line in ["#1", "#2", "#3", "#4"]: history.append_to(history.entries, line) # save only last 2 lines history.save(self.filename, self.encoding, lines=2) # empty the list of entries and load again from the file history.entries = [""] history.load(self.filename, self.encoding) self.assertEqual(history.entries, ["#3", "#4"])
def test_save(self): history = History() history.entries = [] for line in ['#1', '#2', '#3', '#4']: history.append_to(history.entries, line) # save only last 2 lines history.save(self.filename, self.encoding, lines=2) # empty the list of entries and load again from the file history.entries = [''] history.load(self.filename, self.encoding) self.assertEqual(history.entries, ['#3', '#4'])
def test_append_reload_and_write(self): history = History() history.append_reload_and_write("#3", self.filename, self.encoding) self.assertEqual(history.entries, ["#1", "#2", "#3"]) history.append_reload_and_write("#4", self.filename, self.encoding) self.assertEqual(history.entries, ["#1", "#2", "#3", "#4"])
def test_append_reload_and_write(self): history = History() history.append_reload_and_write('#3', self.filename, self.encoding) self.assertEqual(history.entries, ['#1', '#2', '#3']) history.append_reload_and_write('#4', self.filename, self.encoding) self.assertEqual(history.entries, ['#1', '#2', '#3', '#4'])
def __init__(self, interp, config): """Initialise the repl. interp is a Python code.InteractiveInterpreter instance config is a populated bpython.config.Struct. """ self.config = config self.buffer = [] self.interp = interp self.interp.syntaxerror_callback = self.clear_current_line self.match = False self.s = "" self.cpos = 0 self.s_hist = [] self.rl_history = History(allow_duplicates=self.config.hist_duplicates) self.stdin_history = History() self.stdout_history = History() self.evaluating = False self.completer = BPythonCompleter(self.interp.locals, config) self.parser = ReplParser(self) self.matches = [] self.matches_iter = MatchesIterator() self.argspec = None self.list_win_visible = False self._C = {} self.interact = Interaction(self.config) self.ps1 = '>>> ' self.ps2 = '... ' # Necessary to fix mercurial.ui.ui expecting sys.stderr to have this # attribute self.closed = False pythonhist = os.path.expanduser(self.config.hist_file) if os.path.exists(pythonhist): self.rl_history.load(pythonhist, getpreferredencoding() or "ascii")
def setUp(self): self.history = History('#%d' % x for x in range(1000))
class TestHistory(unittest.TestCase): def setUp(self): self.history = History('#%d' % x for x in range(1000)) def test_is_at_start(self): self.history.first() self.assertNotEqual(self.history.index, 0) self.assertTrue(self.history.is_at_end) self.history.forward() self.assertFalse(self.history.is_at_end) def test_is_at_end(self): self.history.last() self.assertEqual(self.history.index, 0) self.assertTrue(self.history.is_at_start) self.assertFalse(self.history.is_at_end) def test_first(self): self.history.first() self.assertFalse(self.history.is_at_start) self.assertTrue(self.history.is_at_end) def test_last(self): self.history.last() self.assertTrue(self.history.is_at_start) self.assertFalse(self.history.is_at_end) def test_back(self): self.assertEqual(self.history.back(), '#999') self.assertNotEqual(self.history.back(), '#999') self.assertEqual(self.history.back(), '#997') for x in range(997): self.history.back() self.assertEqual(self.history.back(), '#0') def test_forward(self): self.history.first() self.assertEqual(self.history.forward(), '#1') self.assertNotEqual(self.history.forward(), '#1') self.assertEqual(self.history.forward(), '#3') # 1000 == entries 4 == len(range(1, 3) ===> '#1000' (so +1) for x in range(1000 - 4 - 1): self.history.forward() self.assertEqual(self.history.forward(), '#999') def test_append(self): self.history.append('print "foo\n"\n') self.history.append('\n') self.assertEqual(self.history.back(), 'print "foo\n"') def test_enter(self): self.history.enter('#lastnumber!') self.assertEqual(self.history.back(), '#lastnumber!') self.assertEqual(self.history.forward(), '#lastnumber!') def test_enter_2(self): self.history.enter('#50') self.assertEqual(self.history.back(), '#509') self.assertEqual(self.history.back(), '#508') self.assertEqual(self.history.forward(), '#509') def test_reset(self): self.history.enter('#lastnumber!') self.history.reset() self.assertEqual(self.history.back(), '#999') self.assertEqual(self.history.forward(), '')
def setUp(self): self.history = History("#%d" % x for x in range(1000))
class TestHistory(unittest.TestCase): def setUp(self): self.history = History("#%d" % x for x in range(1000)) def test_is_at_start(self): self.history.first() self.assertNotEqual(self.history.index, 0) self.assertTrue(self.history.is_at_end) self.history.forward() self.assertFalse(self.history.is_at_end) def test_is_at_end(self): self.history.last() self.assertEqual(self.history.index, 0) self.assertTrue(self.history.is_at_start) self.assertFalse(self.history.is_at_end) def test_first(self): self.history.first() self.assertFalse(self.history.is_at_start) self.assertTrue(self.history.is_at_end) def test_last(self): self.history.last() self.assertTrue(self.history.is_at_start) self.assertFalse(self.history.is_at_end) def test_back(self): self.assertEqual(self.history.back(), "#999") self.assertNotEqual(self.history.back(), "#999") self.assertEqual(self.history.back(), "#997") for x in range(997): self.history.back() self.assertEqual(self.history.back(), "#0") def test_forward(self): self.history.first() self.assertEqual(self.history.forward(), "#1") self.assertNotEqual(self.history.forward(), "#1") self.assertEqual(self.history.forward(), "#3") # 1000 == entries 4 == len(range(1, 3) ===> '#1000' (so +1) for x in range(1000 - 4 - 1): self.history.forward() self.assertEqual(self.history.forward(), "#999") def test_append(self): self.history.append('print "foo\n"\n') self.history.append("\n") self.assertEqual(self.history.back(), 'print "foo\n"') def test_enter(self): self.history.enter("#lastnumber!") self.assertEqual(self.history.back(), "#lastnumber!") self.assertEqual(self.history.forward(), "#lastnumber!") def test_enter_2(self): self.history.enter("#50") self.assertEqual(self.history.back(), "#509") self.assertEqual(self.history.back(), "#508") self.assertEqual(self.history.forward(), "#509") def test_reset(self): self.history.enter("#lastnumber!") self.history.reset() self.assertEqual(self.history.back(), "#999") self.assertEqual(self.history.forward(), "")
def test_load(self): history = History() history.load(self.filename, self.encoding) self.assertEqual(history.entries, ['#1', '#2'])
class Repl(object): """Implements the necessary guff for a Python-repl-alike interface The execution of the code entered and all that stuff was taken from the Python code module, I had to copy it instead of inheriting it, I can't remember why. The rest of the stuff is basically what makes it fancy. It reads what you type, passes it to a lexer and highlighter which returns a formatted string. This then gets passed to echo() which parses that string and prints to the curses screen in appropriate colours and/or bold attribute. The Repl class also keeps two stacks of lines that the user has typed in: One to be used for the undo feature. I am not happy with the way this works. The only way I have been able to think of is to keep the code that's been typed in in memory and re-evaluate it in its entirety for each "undo" operation. Obviously this means some operations could be extremely slow. I'm not even by any means certain that this truly represents a genuine "undo" implementation, but it does seem to be generally pretty effective. If anyone has any suggestions for how this could be improved, I'd be happy to hear them and implement it/accept a patch. I researched a bit into the idea of keeping the entire Python state in memory, but this really seems very difficult (I believe it may actually be impossible to work) and has its own problems too. The other stack is for keeping a history for pressing the up/down keys to go back and forth between lines. XXX Subclasses should implement echo, current_line, cw """ def __init__(self, interp, config): """Initialise the repl. interp is a Python code.InteractiveInterpreter instance config is a populated bpython.config.Struct. """ self.config = config self.cut_buffer = '' self.buffer = [] self.interp = interp self.interp.syntaxerror_callback = self.clear_current_line self.match = False self.rl_history = History(duplicates=config.hist_duplicates, hist_size=config.hist_length) self.s_hist = [] self.history = [] self.evaluating = False self.matches_iter = MatchesIterator() self.argspec = None self.current_func = None self.highlighted_paren = None self._C = {} self.prev_block_finished = 0 self.interact = Interaction(self.config) # previous pastebin content to prevent duplicate pastes, filled on call # to repl.pastebin self.prev_pastebin_content = '' self.prev_pastebin_url = '' self.prev_removal_url = '' # Necessary to fix mercurial.ui.ui expecting sys.stderr to have this # attribute self.closed = False self.clipboard = get_clipboard() pythonhist = os.path.expanduser(self.config.hist_file) if os.path.exists(pythonhist): try: self.rl_history.load(pythonhist, getpreferredencoding() or "ascii") except EnvironmentError: pass self.completers = autocomplete.get_default_completer( config.autocomplete_mode) if self.config.pastebin_helper: self.paster = PasteHelper(self.config.pastebin_helper) else: self.paster = PastePinnwand(self.config.pastebin_url, self.config.pastebin_expiry, self.config.pastebin_show_url, self.config.pastebin_removal_url) @property def ps1(self): try: if not py3: return sys.ps1.decode(getpreferredencoding()) else: return sys.ps1 except AttributeError: return u'>>> ' @property def ps2(self): try: if not py3: return sys.ps2.decode(getpreferredencoding()) else: return sys.ps2 except AttributeError: return u'... ' def startup(self): """ Execute PYTHONSTARTUP file if it exits. Call this after front end-specific initialisation. """ filename = os.environ.get('PYTHONSTARTUP') if filename: encoding = inspection.get_encoding_file(filename) with io.open(filename, 'rt', encoding=encoding) as f: source = f.read() if not py3: # Python 2.6 and early 2.7.X need bytes. source = source.encode(encoding) self.interp.runsource(source, filename, 'exec', encode=False) def current_string(self, concatenate=False): """If the line ends in a string get it, otherwise return ''""" tokens = self.tokenize(self.current_line) string_tokens = list(takewhile(token_is_any_of([Token.String, Token.Text]), reversed(tokens))) if not string_tokens: return '' opening = string_tokens.pop()[1] string = list() for (token, value) in reversed(string_tokens): if token is Token.Text: continue elif opening is None: opening = value elif token is Token.String.Doc: string.append(value[3:-3]) opening = None elif value == opening: opening = None if not concatenate: string = list() else: string.append(value) if opening is None: return '' return ''.join(string) def get_object(self, name): attributes = name.split('.') obj = eval(attributes.pop(0), self.interp.locals) while attributes: with inspection.AttrCleaner(obj): obj = getattr(obj, attributes.pop(0)) return obj def get_args(self): """Check if an unclosed parenthesis exists, then attempt to get the argspec() for it. On success, update self.argspec and return True, otherwise set self.argspec to None and return False""" self.current_func = None if not self.config.arg_spec: return False # Get the name of the current function and where we are in # the arguments stack = [['', 0, '']] try: for (token, value) in PythonLexer().get_tokens( self.current_line): if token is Token.Punctuation: if value in '([{': stack.append(['', 0, value]) elif value in ')]}': stack.pop() elif value == ',': try: stack[-1][1] += 1 except TypeError: stack[-1][1] = '' stack[-1][0] = '' elif value == ':' and stack[-1][2] == 'lambda': stack.pop() else: stack[-1][0] = '' elif (token is Token.Name or token in Token.Name.subtypes or token is Token.Operator and value == '.'): stack[-1][0] += value elif token is Token.Operator and value == '=': stack[-1][1] = stack[-1][0] stack[-1][0] = '' elif token is Token.Keyword and value == 'lambda': stack.append(['', 0, value]) else: stack[-1][0] = '' while stack[-1][2] in '[{': stack.pop() _, arg_number, _ = stack.pop() func, _, _ = stack.pop() except IndexError: return False if not func: return False try: f = self.get_object(func) except Exception: # another case of needing to catch every kind of error # since user code is run in the case of descriptors # XXX: Make sure you raise here if you're debugging the completion # stuff ! return False if inspect.isclass(f): try: if f.__init__ is not object.__init__: f = f.__init__ except AttributeError: return None self.current_func = f self.argspec = inspection.getargspec(func, f) if self.argspec: self.argspec.append(arg_number) return True return False def get_source_of_current_name(self): """Return the unicode source code of the object which is bound to the current name in the current input line. Throw `SourceNotFound` if the source cannot be found.""" obj = self.current_func try: if obj is None: line = self.current_line if not line.strip(): raise SourceNotFound(_("Nothing to get source of")) if inspection.is_eval_safe_name(line): obj = self.get_object(line) return inspection.get_source_unicode(obj) except (AttributeError, NameError) as e: msg = _(u"Cannot get source: %s") % (e, ) except IOError as e: msg = u"%s" % (e, ) except TypeError as e: if "built-in" in u"%s" % (e, ): msg = _("Cannot access source of %r") % (obj, ) else: msg = _("No source code found for %s") % (self.current_line, ) raise SourceNotFound(msg) def set_docstring(self): self.docstring = None if not self.get_args(): self.argspec = None elif self.current_func is not None: try: self.docstring = pydoc.getdoc(self.current_func) except IndexError: self.docstring = None else: # pydoc.getdoc() returns an empty string if no # docstring was found if not self.docstring: self.docstring = None # What complete() does: # Should we show the completion box? (are there matches, or is there a # docstring to show?) # Some completions should always be shown, other only if tab=True # set the current docstring to the "current function's" docstring # Populate the matches_iter object with new matches from the current state # if none, clear the matches iterator # If exactly one match that is equal to current line, clear matches # If example one match and tab=True, then choose that and clear matches def complete(self, tab=False): """Construct a full list of possible completions and display them in a window. Also check if there's an available argspec (via the inspect module) and bang that on top of the completions too. The return value is whether the list_win is visible or not. If no matches are found, just return whether there's an argspec to show If any matches are found, save them and select the first one. If tab is True exactly one match found, make the replacement and return the result of running complete() again on the new line. """ self.set_docstring() matches, completer = autocomplete.get_completer( self.completers, cursor_offset=self.cursor_offset, line=self.current_line, locals_=self.interp.locals, argspec=self.argspec, current_block='\n'.join(self.buffer + [self.current_line]), complete_magic_methods=self.config.complete_magic_methods, history=self.history) # TODO implement completer.shown_before_tab == False (filenames # shouldn't fill screen) if len(matches) == 0: self.matches_iter.clear() return bool(self.argspec) self.matches_iter.update(self.cursor_offset, self.current_line, matches, completer) if len(matches) == 1: if tab: # if this complete is being run for a tab key press, substitute # common sequence self._cursor_offset, self._current_line = \ self.matches_iter.substitute_cseq() return Repl.complete(self) # again for elif self.matches_iter.current_word == matches[0]: self.matches_iter.clear() return False return completer.shown_before_tab else: assert len(matches) > 1 return tab or completer.shown_before_tab def format_docstring(self, docstring, width, height): """Take a string and try to format it into a sane list of strings to be put into the suggestion box.""" lines = docstring.split('\n') out = [] i = 0 for line in lines: i += 1 if not line.strip(): out.append('\n') for block in textwrap.wrap(line, width): out.append(' ' + block + '\n') if i >= height: return out i += 1 # Drop the last newline out[-1] = out[-1].rstrip() return out def next_indentation(self): """Return the indentation of the next line based on the current input buffer.""" if self.buffer: indentation = next_indentation(self.buffer[-1], self.config.tab_length) if indentation and self.config.dedent_after > 0: line_is_empty = lambda line: not line.strip() empty_lines = takewhile(line_is_empty, reversed(self.buffer)) if sum(1 for _ in empty_lines) >= self.config.dedent_after: indentation -= 1 else: indentation = 0 return indentation def formatforfile(self, s): """Format the stdout buffer to something suitable for writing to disk, i.e. without >>> and ... at input lines and with "# OUT: " prepended to output lines.""" def process(): for line in s.split('\n'): if line.startswith(self.ps1): yield line[len(self.ps1):] elif line.startswith(self.ps2): yield line[len(self.ps2):] elif line.rstrip(): yield "# OUT: %s" % (line,) return "\n".join(process()) def write2file(self): """Prompt for a filename and write the current contents of the stdout buffer to disk.""" try: fn = self.interact.file_prompt(_('Save to file (Esc to cancel): ')) if not fn: self.interact.notify(_('Save cancelled.')) return except ValueError: self.interact.notify(_('Save cancelled.')) return if fn.startswith('~'): fn = os.path.expanduser(fn) if not fn.endswith('.py') and self.config.save_append_py: fn = fn + '.py' mode = 'w' if os.path.exists(fn): mode = self.interact.file_prompt(_('%s already exists. Do you ' 'want to (c)ancel, ' ' (o)verwrite or ' '(a)ppend? ') % (fn, )) if mode in ('o', 'overwrite', _('overwrite')): mode = 'w' elif mode in ('a', 'append', _('append')): mode = 'a' else: self.interact.notify(_('Save cancelled.')) return s = self.formatforfile(self.getstdout()) try: with open(fn, mode) as f: f.write(s) except IOError as e: self.interact.notify(_("Error writing file '%s': %s") % (fn, e)) else: self.interact.notify(_('Saved to %s.') % (fn, )) def copy2clipboard(self): """Copy current content to clipboard.""" if self.clipboard is None: self.interact.notify(_('No clipboard available.')) return content = self.formatforfile(self.getstdout()) try: self.clipboard.copy(content) except CopyFailed: self.interact.notify(_('Could not copy to clipboard.')) else: self.interact.notify(_('Copied content to clipboard.')) def pastebin(self, s=None): """Upload to a pastebin and display the URL in the status bar.""" if s is None: s = self.getstdout() if (self.config.pastebin_confirm and not self.interact.confirm(_("Pastebin buffer? (y/N) "))): self.interact.notify(_("Pastebin aborted.")) return return self.do_pastebin(s) def do_pastebin(self, s): """Actually perform the upload.""" if s == self.prev_pastebin_content: self.interact.notify(_('Duplicate pastebin. Previous URL: %s. ' 'Removal URL: %s') % (self.prev_pastebin_url, self.prev_removal_url), 10) return self.prev_pastebin_url self.interact.notify(_('Posting data to pastebin...')) try: paste_url, removal_url = self.paster.paste(s) except PasteFailed as e: self.interact.notify(_('Upload failed: %s') % e) return self.prev_pastebin_content = s self.prev_pastebin_url = paste_url self.prev_removal_url = removal_url if removal_url is not None: self.interact.notify(_('Pastebin URL: %s - Removal URL: %s') % (paste_url, removal_url), 10) else: self.interact.notify(_('Pastebin URL: %s') % (paste_url, ), 10) return paste_url def push(self, s, insert_into_history=True): """Push a line of code onto the buffer so it can process it all at once when a code block ends""" s = s.rstrip('\n') self.buffer.append(s) if insert_into_history: self.insert_into_history(s) more = self.interp.runsource('\n'.join(self.buffer)) if not more: self.buffer = [] return more def insert_into_history(self, s): try: self.rl_history.append_reload_and_write(s, self.config.hist_file, getpreferredencoding()) except RuntimeError as e: self.interact.notify(u"%s" % (e, )) def prompt_undo(self): """Returns how many lines to undo, 0 means don't undo""" if (self.config.single_undo_time < 0 or self.interp.timer.estimate() < self.config.single_undo_time): return 1 est = self.interp.timer.estimate() n = self.interact.file_prompt( _("Undo how many lines? (Undo will take up to ~%.1f seconds) [1]") % (est,)) try: if n == '': n = '1' n = int(n) except ValueError: self.interact.notify(_('Undo canceled'), .1) return 0 else: if n == 0: self.interact.notify(_('Undo canceled'), .1) return 0 else: message = ngettext('Undoing %d line... (est. %.1f seconds)', 'Undoing %d lines... (est. %.1f seconds)', n) self.interact.notify(message % (n, est), .1) return n def undo(self, n=1): """Go back in the undo history n steps and call reevaluate() Note that in the program this is called "Rewind" because I want it to be clear that this is by no means a true undo implementation, it is merely a convenience bonus.""" if not self.history: return None self.interp.timer.reset_timer() if len(self.history) < n: n = len(self.history) entries = list(self.rl_history.entries) self.history = self.history[:-n] self.reevaluate() self.rl_history.entries = entries def flush(self): """Olivier Grisel brought it to my attention that the logging module tries to call this method, since it makes assumptions about stdout that may not necessarily be true. The docs for sys.stdout say: "stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument." So I consider this to be a bug in logging, and this is a hack to fix it, unfortunately. I'm sure it's not the only module to do it.""" def close(self): """See the flush() method docstring.""" def tokenize(self, s, newline=False): """Tokenizes a line of code, returning pygments tokens with side effects/impurities: - reads self.cpos to see what parens should be highlighted - reads self.buffer to see what came before the passed in line - sets self.highlighted_paren to (buffer_lineno, tokens_for_that_line) for buffer line that should replace that line to unhighlight it, or None if no paren is currently highlighted - calls reprint_line with a buffer's line's tokens and the buffer lineno that has changed if line other than the current line changes """ highlighted_paren = None source = '\n'.join(self.buffer + [s]) cursor = len(source) - self.cpos if self.cpos: cursor += 1 stack = list() all_tokens = list(PythonLexer().get_tokens(source)) # Unfortunately, Pygments adds a trailing newline and strings with # no size, so strip them while not all_tokens[-1][1]: all_tokens.pop() all_tokens[-1] = (all_tokens[-1][0], all_tokens[-1][1].rstrip('\n')) line = pos = 0 parens = dict(zip('{([', '})]')) line_tokens = list() saved_tokens = list() search_for_paren = True for (token, value) in split_lines(all_tokens): pos += len(value) if token is Token.Text and value == '\n': line += 1 # Remove trailing newline line_tokens = list() saved_tokens = list() continue line_tokens.append((token, value)) saved_tokens.append((token, value)) if not search_for_paren: continue under_cursor = (pos == cursor) if token is Token.Punctuation: if value in parens: if under_cursor: line_tokens[-1] = (Parenthesis.UnderCursor, value) # Push marker on the stack stack.append((Parenthesis, value)) else: stack.append((line, len(line_tokens) - 1, line_tokens, value)) elif value in itervalues(parens): saved_stack = list(stack) try: while True: opening = stack.pop() if parens[opening[-1]] == value: break except IndexError: # SyntaxError.. more closed parentheses than # opened or a wrong closing paren opening = None if not saved_stack: search_for_paren = False else: stack = saved_stack if opening and opening[0] is Parenthesis: # Marker found line_tokens[-1] = (Parenthesis, value) search_for_paren = False elif opening and under_cursor and not newline: if self.cpos: line_tokens[-1] = (Parenthesis.UnderCursor, value) else: # The cursor is at the end of line and next to # the paren, so it doesn't reverse the paren. # Therefore, we insert the Parenthesis token # here instead of the Parenthesis.UnderCursor # token. line_tokens[-1] = (Parenthesis, value) (lineno, i, tokens, opening) = opening if lineno == len(self.buffer): highlighted_paren = (lineno, saved_tokens) line_tokens[i] = (Parenthesis, opening) else: highlighted_paren = (lineno, list(tokens)) # We need to redraw a line tokens[i] = (Parenthesis, opening) self.reprint_line(lineno, tokens) search_for_paren = False elif under_cursor: search_for_paren = False self.highlighted_paren = highlighted_paren if line != len(self.buffer): return list() return line_tokens def clear_current_line(self): """This is used as the exception callback for the Interpreter instance. It prevents autoindentation from occuring after a traceback.""" def send_to_external_editor(self, text, filename=None): """Returns modified text from an editor, or the oriignal text if editor exited with non-zero""" encoding = getpreferredencoding() editor_args = shlex.split(prepare_for_exec(self.config.editor, encoding)) with tempfile.NamedTemporaryFile(suffix='.py') as temp: temp.write(text.encode(encoding)) temp.flush() args = editor_args + [prepare_for_exec(temp.name, encoding)] if subprocess.call(args) == 0: with open(temp.name) as f: if py3: return f.read() else: return f.read().decode(encoding) else: return text def open_in_external_editor(self, filename): encoding = getpreferredencoding() editor_args = shlex.split(prepare_for_exec(self.config.editor, encoding)) args = editor_args + [prepare_for_exec(filename, encoding)] if subprocess.call(args) == 0: return True return False def edit_config(self): if not (os.path.isfile(self.config.config_path)): if self.interact.confirm(_("Config file does not exist - create " "new from default? (y/N)")): try: default_config = pkgutil.get_data('bpython', 'sample-config') if py3: # py3 files need unicode default_config = default_config.decode('ascii') bpython_dir, script_name = os.path.split(__file__) containing_dir = os.path.dirname( os.path.abspath(self.config.config_path)) if not os.path.exists(containing_dir): os.makedirs(containing_dir) with open(self.config.config_path, 'w') as f: f.write(default_config) except (IOError, OSError) as e: self.interact.notify(_("Error writing file '%s': %s") % (self.config.config.path, e)) return False else: return False if self.open_in_external_editor(self.config.config_path): self.interact.notify(_('bpython config file edited. Restart ' 'bpython for changes to take effect.')) else: self.interact.notify(_('Error editing config file.'))
class Repl(object): """Implements the necessary guff for a Python-repl-alike interface The execution of the code entered and all that stuff was taken from the Python code module, I had to copy it instead of inheriting it, I can't remember why. The rest of the stuff is basically what makes it fancy. It reads what you type, passes it to a lexer and highlighter which returns a formatted string. This then gets passed to echo() which parses that string and prints to the curses screen in appropriate colours and/or bold attribute. The Repl class also keeps two stacks of lines that the user has typed in: One to be used for the undo feature. I am not happy with the way this works. The only way I have been able to think of is to keep the code that's been typed in in memory and re-evaluate it in its entirety for each "undo" operation. Obviously this means some operations could be extremely slow. I'm not even by any means certain that this truly represents a genuine "undo" implementation, but it does seem to be generally pretty effective. If anyone has any suggestions for how this could be improved, I'd be happy to hear them and implement it/accept a patch. I researched a bit into the idea of keeping the entire Python state in memory, but this really seems very difficult (I believe it may actually be impossible to work) and has its own problems too. The other stack is for keeping a history for pressing the up/down keys to go back and forth between lines. XXX Subclasses should implement echo, current_line, current_word """ def __init__(self, interp, config): """Initialise the repl. interp is a Python code.InteractiveInterpreter instance config is a populated bpython.config.Struct. """ self.config = config self.buffer = [] self.interp = interp self.interp.syntaxerror_callback = self.clear_current_line self.match = False self.s = "" self.cpos = 0 self.s_hist = [] self.rl_history = History(allow_duplicates=self.config.hist_duplicates) self.stdin_history = History() self.stdout_history = History() self.evaluating = False self.completer = BPythonCompleter(self.interp.locals, config) self.parser = ReplParser(self) self.matches = [] self.matches_iter = MatchesIterator() self.argspec = None self.list_win_visible = False self._C = {} self.interact = Interaction(self.config) self.ps1 = '>>> ' self.ps2 = '... ' # Necessary to fix mercurial.ui.ui expecting sys.stderr to have this # attribute self.closed = False pythonhist = os.path.expanduser(self.config.hist_file) if os.path.exists(pythonhist): self.rl_history.load(pythonhist, getpreferredencoding() or "ascii") def register_command(self, name, function=None, without_completion=False): def inner(function, name=name): if not name: name = function.__name__.replace('_', '-') if self.interp.register_command(name, function) and not without_completion: name += " " self.completer.register_command(name) if not function: return inner else: return inner(function, name) @property def history(self): return self.stdin_history @property def current_line(self): raise (NotImplementedError("current_line should be implemented in subclass")) def clear_current_line(self): """This is used as the exception callback for the Interpreter instance. It prevents autoindentation from occuring after a traceback.""" raise (NotImplementedError("clear_current_line should be implemented in subclass")) def reevaluate(self): raise (NotImplementedError("reevaluate should be implemented in subclass")) def tab(self): raise (NotImplementedError("tab should be implemented in subclass")) def tokenize(self, s, newline=False): """Tokenize a line of code.""" return self.parser.tokenize(s, newline) def startup(self): """ Execute PYTHONSTARTUP file if it exits. Call this after front end-specific initialisation. """ self.interp.startup() @property def stdout(self): return str(self.stdout_history) @property def stdin(self): return str(self.stdin_history) @property def current_string(self): """If the line ends in a string get it, otherwise return ''""" return self.parser.get_current_string() @property def current_word(self): """Return the current word, i.e. the (incomplete) word directly to the left of the cursor""" return self.parser.get_current_word() def get_current_sbracket(self): return self.parser.get_current_sbracket() @property def is_first_word(self): return self.parser.is_first_word() @property def is_only_word(self): return self.parser.is_only_word() @property def is_assignment_statement(self): return self.parser.is_assignment_statement() def get_object(self, name): return self.interp.get_object(name) def set_argspec(self): """Check if an unclosed parenthesis exists, then attempt to get the argspec() for it. On success, update self.argspec and return True, otherwise set self.argspec to None and return False""" if not self.config.arg_spec: self.argspec = None else: func, arg_number = self.parser.get_current_func() self.argspec = self.interp.get_argspec(self, func, arg_number) @property def current_object(self): """Return the object which is bound to the current name in the current input line. Return `None` if the source cannot be found.""" obj = None line = self.current_line if inspection.is_eval_safe_name(line): obj = self.get_object(line) return obj def complete(self, tab=False): """Construct a full list of possible completions and construct and display them in a window. Also check if there's an available argspec (via the inspect module) and bang that on top of the completions too. The return value is whether the list_win is visible or not.""" self.set_argspec() current_word = self.current_word current_string = self.current_string sb_expr, sb_attr = self.get_current_sbracket() line = self.current_line.lstrip() if sb_expr: self.completer.get_item_complete(sb_expr, sb_attr) self.matches = self.completer.matches self.matches_iter.update(sb_attr, self.matches) return bool(self.matches) elif not current_word: self.matches = [] self.matches_iter.update() return bool(self.argspec) elif not (current_word or current_string): return bool(self.argspec) elif current_string: if tab: # Filename completion self.completer.file_complete(current_string) self.matches = self.completer.matches self.matches_iter.update(current_string, self.matches) return bool(self.matches) else: # Do not provide suggestions inside strings, as one cannot tab # them so they would be really confusing. self.matches = [] self.matches_iter.update() return False elif (self.config.complete_magic_methods and self.buffer and self.buffer[0].startswith("class ") and line.startswith('def ')): self.matches = [name for name in self.config.magic_methods if name.startswith(current_word)] self.matches_iter.update(current_word, self.matches) return bool(self.matches) elif line.startswith('class ') or line.startswith('def '): self.matches = [] self.matches_iter.update() return False elif line.startswith('from ') or line.startswith('import '): self.completer.import_complete(current_word, self.current_line) self.matches = self.completer.matches self.matches_iter.update(current_word, self.matches) return bool(self.matches) e = False try: if len(self.buffer) == 0 and self.is_first_word: self.completer.complete(current_word, with_command=True) else: self.completer.complete(current_word) except (AttributeError, re.error, TimeOutException): e = True except Exception as err: raise err # This sucks, but it's either that or list all the exceptions that could # possibly be raised here, so if anyone wants to do that, feel free to send me # a patch. XXX: Make sure you raise here if you're debugging the completion # stuff ! e = True else: matches = self.completer.matches if not e and self.argspec and isinstance(self.argspec, inspection.ArgSpec): matches.extend(name + '=' for name in self.argspec[1][0] if isinstance(name, basestring) and name.startswith(current_word)) if PY3: matches.extend(name + '=' for name in self.argspec[1][4] if name.startswith(current_word)) if e or not matches: self.matches = [] self.matches_iter.update() if not self.argspec: return False else: # remove duplicates self.matches = sorted(set(matches)) if len(self.matches) == 1 and not self.config.auto_display_list: self.list_win_visible = True self.tab() return False self.matches_iter.update(current_word, self.matches) return True def format_docstring(self, docstring, width, height): """Take a string and try to format it into a sane list of strings to be put into the suggestion box.""" lines = docstring.split('\n') out = [] i = 0 for line in lines: i += 1 if not line.strip(): out.append('\n') for block in textwrap.wrap(line, width): out.append(' ' + block + '\n') if i >= height: return out i += 1 # Drop the last newline out[-1] = out[-1].rstrip() return out def next_indentation(self): """Return the indentation of the next line based on the current input buffer.""" if self.buffer: indentation = next_indentation(self.buffer[-1], self.config.tab_length) if indentation and self.config.dedent_after > 0: line_is_empty = lambda line: not line.strip() empty_lines = takewhile(line_is_empty, reversed(self.buffer)) if sum(1 for _ in empty_lines) >= self.config.dedent_after: indentation -= 1 else: indentation = 0 return indentation def formatforfile(self, s): """Format the stdout buffer to something suitable for writing to disk, i.e. without >>> and ... at input lines and with "# OUT: " prepended to output lines.""" def process(): for line in s.split('\n'): if line.startswith(self.ps1): yield line[len(self.ps1):] elif line.startswith(self.ps2): yield line[len(self.ps2):] elif line.rstrip(): yield "# OUT: %s" % (line,) return "\n".join(process()) def write2file(self): """Prompt for a filename and write the current contents of the stdout buffer to disk.""" try: fn = self.interact.file_prompt('Save to file (Esc to cancel): ') if not fn: self.interact.notify("Save cancelled.") return except ValueError: self.interact.notify("Save cancelled.") return if fn.startswith('~'): fn = os.path.expanduser(fn) if not fn.endswith('.py') and self.config.save_append_py: fn += '.py' mode = 'w' if os.path.exists(fn): mode = self.interact.file_prompt('%s already exists. Do you want ' 'to (c)ancel, (o)verwrite or ' '(a)ppend? ' % (fn, )) if mode in ('o', 'overwrite'): mode = 'w' elif mode in ('a', 'append'): mode = 'a' else: self.interact.notify('Save cancelled.') return s = self.formatforfile(self.stdout) try: f = open(fn, mode) f.write(s) f.close() except IOError: self.interact.notify("Disk write error for file '%s'." % (fn, )) else: self.interact.notify('Saved to %s.' % (fn, )) def push(self, s, insert_into_history=True): """Push a line of code onto the buffer so it can process it all at once when a code block ends""" if s.lstrip(' ') and s.lstrip(' ')[0] == '!': self.buffer = [] return s = s.rstrip('\n') self.buffer.append(s) if insert_into_history: if self.config.hist_length: histfilename = os.path.expanduser(self.config.hist_file) oldhistory = self.rl_history.entries self.rl_history.entries = [] if os.path.exists(histfilename): self.rl_history.load(histfilename, getpreferredencoding()) self.rl_history.append(s) try: self.rl_history.save(histfilename, getpreferredencoding(), self.config.hist_length) except EnvironmentError as e: self.interact.notify("Error occured while writing to file %s (%s) " % (histfilename, e.strerror)) self.rl_history.entries = oldhistory self.rl_history.append(s) else: self.rl_history.append(s) if len(self.buffer) == 1: line = self.buffer[0] if self.interp.is_commandline(line) and not self.is_assignment_statement: result = self.interp.runcommand(line) self.buffer = [] return result more = self.interp.runsource('\n'.join(self.buffer)) if not more: self.buffer = [] return more def undo(self, n=1): """Go back in the undo history n steps and call reeavluate() Note that in the program this is called "Rewind" because I want it to be clear that this is by no means a true undo implementation, it is merely a convenience bonus.""" if not self.history: return None if len(self.history) < n: n = len(self.history) entries = list(self.rl_history.entries) self.history.entries = self.history[:-n] self.reevaluate() self.rl_history.entries = entries def flush(self): """Olivier Grisel brought it to my attention that the logging module tries to call this method, since it makes assumptions about stdout that may not necessarily be true. The docs for sys.stdout say: "stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument." So I consider this to be a bug in logging, and this is a hack to fix it, unfortunately. I'm sure it's not the only module to do it.""" def close(self): """See the flush() method docstring."""
class Repl(object): """Implements the necessary guff for a Python-repl-alike interface The execution of the code entered and all that stuff was taken from the Python code module, I had to copy it instead of inheriting it, I can't remember why. The rest of the stuff is basically what makes it fancy. It reads what you type, passes it to a lexer and highlighter which returns a formatted string. This then gets passed to echo() which parses that string and prints to the curses screen in appropriate colours and/or bold attribute. The Repl class also keeps two stacks of lines that the user has typed in: One to be used for the undo feature. I am not happy with the way this works. The only way I have been able to think of is to keep the code that's been typed in in memory and re-evaluate it in its entirety for each "undo" operation. Obviously this means some operations could be extremely slow. I'm not even by any means certain that this truly represents a genuine "undo" implementation, but it does seem to be generally pretty effective. If anyone has any suggestions for how this could be improved, I'd be happy to hear them and implement it/accept a patch. I researched a bit into the idea of keeping the entire Python state in memory, but this really seems very difficult (I believe it may actually be impossible to work) and has its own problems too. The other stack is for keeping a history for pressing the up/down keys to go back and forth between lines. XXX Subclasses should implement echo, current_line, cw """ def __init__(self, interp, config): """Initialise the repl. interp is a Python code.InteractiveInterpreter instance config is a populated bpython.config.Struct. """ self.config = config self.cut_buffer = '' self.buffer = [] self.interp = interp self.interp.syntaxerror_callback = self.clear_current_line self.match = False self.rl_history = History(duplicates=config.hist_duplicates, hist_size=config.hist_length) self.s_hist = [] self.history = [] self.evaluating = False self.matches_iter = MatchesIterator() self.funcprops = None self.arg_pos = None self.current_func = None self.highlighted_paren = None self._C = {} self.prev_block_finished = 0 self.interact = Interaction(self.config) # previous pastebin content to prevent duplicate pastes, filled on call # to repl.pastebin self.prev_pastebin_content = '' self.prev_pastebin_url = '' self.prev_removal_url = '' # Necessary to fix mercurial.ui.ui expecting sys.stderr to have this # attribute self.closed = False self.clipboard = get_clipboard() pythonhist = os.path.expanduser(self.config.hist_file) if os.path.exists(pythonhist): try: self.rl_history.load(pythonhist, getpreferredencoding() or "ascii") except EnvironmentError: pass self.completers = autocomplete.get_default_completer( config.autocomplete_mode) if self.config.pastebin_helper: self.paster = PasteHelper(self.config.pastebin_helper) else: self.paster = PastePinnwand(self.config.pastebin_url, self.config.pastebin_expiry, self.config.pastebin_show_url, self.config.pastebin_removal_url) @property def ps1(self): try: if not py3: return sys.ps1.decode(getpreferredencoding()) else: return sys.ps1 except AttributeError: return u'>>> ' @property def ps2(self): try: if not py3: return sys.ps2.decode(getpreferredencoding()) else: return sys.ps2 except AttributeError: return u'... ' def startup(self): """ Execute PYTHONSTARTUP file if it exits. Call this after front end-specific initialisation. """ filename = os.environ.get('PYTHONSTARTUP') if filename: encoding = inspection.get_encoding_file(filename) with io.open(filename, 'rt', encoding=encoding) as f: source = f.read() if not py3: # Python 2.6 and early 2.7.X need bytes. source = source.encode(encoding) self.interp.runsource(source, filename, 'exec', encode=False) def current_string(self, concatenate=False): """If the line ends in a string get it, otherwise return ''""" tokens = self.tokenize(self.current_line) string_tokens = list(takewhile(token_is_any_of([Token.String, Token.Text]), reversed(tokens))) if not string_tokens: return '' opening = string_tokens.pop()[1] string = list() for (token, value) in reversed(string_tokens): if token is Token.Text: continue elif opening is None: opening = value elif token is Token.String.Doc: string.append(value[3:-3]) opening = None elif value == opening: opening = None if not concatenate: string = list() else: string.append(value) if opening is None: return '' return ''.join(string) def get_object(self, name): attributes = name.split('.') obj = eval(attributes.pop(0), self.interp.locals) while attributes: with inspection.AttrCleaner(obj): obj = getattr(obj, attributes.pop(0)) return obj def get_args(self): """Check if an unclosed parenthesis exists, then attempt to get the argspec() for it. On success, update self.funcprops,self.arg_pos and return True, otherwise set self.funcprops to None and return False""" self.current_func = None if not self.config.arg_spec: return False # Get the name of the current function and where we are in # the arguments stack = [['', 0, '']] try: for (token, value) in PythonLexer().get_tokens( self.current_line): if token is Token.Punctuation: if value in '([{': stack.append(['', 0, value]) elif value in ')]}': stack.pop() elif value == ',': try: stack[-1][1] += 1 except TypeError: stack[-1][1] = '' stack[-1][0] = '' elif value == ':' and stack[-1][2] == 'lambda': stack.pop() else: stack[-1][0] = '' elif (token is Token.Name or token in Token.Name.subtypes or token is Token.Operator and value == '.'): stack[-1][0] += value elif token is Token.Operator and value == '=': stack[-1][1] = stack[-1][0] stack[-1][0] = '' elif token is Token.Keyword and value == 'lambda': stack.append(['', 0, value]) else: stack[-1][0] = '' while stack[-1][2] in '[{': stack.pop() _, arg_number, _ = stack.pop() func, _, _ = stack.pop() except IndexError: return False if not func: return False try: if inspection.is_eval_safe_name(func): f = self.get_object(func) else: try: fake_cursor = self.current_line.index(func) + len(func) f = simpleeval.evaluate_current_attribute( fake_cursor, self.current_line, self.interp.locals) except simpleeval.EvaluationError: return False except Exception: # another case of needing to catch every kind of error # since user code is run in the case of descriptors # XXX: Make sure you raise here if you're debugging the completion # stuff ! return False if inspect.isclass(f): class_f = None if (hasattr(f, '__init__') and f.__init__ is not object.__init__): class_f = f.__init__ if ((not class_f or not inspection.getfuncprops(func, class_f)) and hasattr(f, '__new__') and f.__new__ is not object.__new__ and # py3 f.__new__.__class__ is not object.__new__.__class__): class_f = f.__new__ if class_f: f = class_f self.current_func = f self.funcprops = inspection.getfuncprops(func, f) if self.funcprops: self.arg_pos = arg_number return True self.arg_pos = None return False def get_source_of_current_name(self): """Return the unicode source code of the object which is bound to the current name in the current input line. Throw `SourceNotFound` if the source cannot be found.""" obj = self.current_func try: if obj is None: line = self.current_line if not line.strip(): raise SourceNotFound(_("Nothing to get source of")) if inspection.is_eval_safe_name(line): obj = self.get_object(line) return inspection.get_source_unicode(obj) except (AttributeError, NameError) as e: msg = _(u"Cannot get source: %s") % (e, ) except IOError as e: msg = u"%s" % (e, ) except TypeError as e: if "built-in" in u"%s" % (e, ): msg = _("Cannot access source of %r") % (obj, ) else: msg = _("No source code found for %s") % (self.current_line, ) raise SourceNotFound(msg) def set_docstring(self): self.docstring = None if not self.get_args(): self.funcprops = None if self.current_func is not None: try: self.docstring = pydoc.getdoc(self.current_func) except IndexError: self.docstring = None else: # pydoc.getdoc() returns an empty string if no # docstring was found if not self.docstring: self.docstring = None # What complete() does: # Should we show the completion box? (are there matches, or is there a # docstring to show?) # Some completions should always be shown, other only if tab=True # set the current docstring to the "current function's" docstring # Populate the matches_iter object with new matches from the current state # if none, clear the matches iterator # If exactly one match that is equal to current line, clear matches # If example one match and tab=True, then choose that and clear matches def complete(self, tab=False): """Construct a full list of possible completions and display them in a window. Also check if there's an available argspec (via the inspect module) and bang that on top of the completions too. The return value is whether the list_win is visible or not. If no matches are found, just return whether there's an argspec to show If any matches are found, save them and select the first one. If tab is True exactly one match found, make the replacement and return the result of running complete() again on the new line. """ self.set_docstring() matches, completer = autocomplete.get_completer( self.completers, cursor_offset=self.cursor_offset, line=self.current_line, locals_=self.interp.locals, argspec=self.funcprops, current_block='\n'.join(self.buffer + [self.current_line]), complete_magic_methods=self.config.complete_magic_methods, history=self.history) if len(matches) == 0: self.matches_iter.clear() return bool(self.funcprops) self.matches_iter.update(self.cursor_offset, self.current_line, matches, completer) if len(matches) == 1: if tab: # if this complete is being run for a tab key press, substitute # common sequence self._cursor_offset, self._current_line = \ self.matches_iter.substitute_cseq() return Repl.complete(self) # again for elif self.matches_iter.current_word == matches[0]: self.matches_iter.clear() return False return completer.shown_before_tab else: return tab or completer.shown_before_tab def format_docstring(self, docstring, width, height): """Take a string and try to format it into a sane list of strings to be put into the suggestion box.""" lines = docstring.split('\n') out = [] i = 0 for line in lines: i += 1 if not line.strip(): out.append('\n') for block in textwrap.wrap(line, width): out.append(' ' + block + '\n') if i >= height: return out i += 1 # Drop the last newline out[-1] = out[-1].rstrip() return out def next_indentation(self): """Return the indentation of the next line based on the current input buffer.""" if self.buffer: indentation = next_indentation(self.buffer[-1], self.config.tab_length) if indentation and self.config.dedent_after > 0: def line_is_empty(line): return not line.strip() empty_lines = takewhile(line_is_empty, reversed(self.buffer)) if sum(1 for _ in empty_lines) >= self.config.dedent_after: indentation -= 1 else: indentation = 0 return indentation def formatforfile(self, s): """Format the stdout buffer to something suitable for writing to disk, i.e. without >>> and ... at input lines and with "# OUT: " prepended to output lines.""" def process(): for line in s.split('\n'): if line.startswith(self.ps1): yield line[len(self.ps1):] elif line.startswith(self.ps2): yield line[len(self.ps2):] elif line.rstrip(): yield "# OUT: %s" % (line,) return "\n".join(process()) def write2file(self): """Prompt for a filename and write the current contents of the stdout buffer to disk.""" try: fn = self.interact.file_prompt(_('Save to file (Esc to cancel): ')) if not fn: self.interact.notify(_('Save cancelled.')) return except ValueError: self.interact.notify(_('Save cancelled.')) return if fn.startswith('~'): fn = os.path.expanduser(fn) if not fn.endswith('.py') and self.config.save_append_py: fn = fn + '.py' mode = 'w' if os.path.exists(fn): mode = self.interact.file_prompt(_('%s already exists. Do you ' 'want to (c)ancel, ' ' (o)verwrite or ' '(a)ppend? ') % (fn, )) if mode in ('o', 'overwrite', _('overwrite')): mode = 'w' elif mode in ('a', 'append', _('append')): mode = 'a' else: self.interact.notify(_('Save cancelled.')) return s = self.formatforfile(self.getstdout()) try: with open(fn, mode) as f: f.write(s) except IOError as e: self.interact.notify(_("Error writing file '%s': %s") % (fn, e)) else: self.interact.notify(_('Saved to %s.') % (fn, )) def copy2clipboard(self): """Copy current content to clipboard.""" if self.clipboard is None: self.interact.notify(_('No clipboard available.')) return content = self.formatforfile(self.getstdout()) try: self.clipboard.copy(content) except CopyFailed: self.interact.notify(_('Could not copy to clipboard.')) else: self.interact.notify(_('Copied content to clipboard.')) def pastebin(self, s=None): """Upload to a pastebin and display the URL in the status bar.""" if s is None: s = self.getstdout() if (self.config.pastebin_confirm and not self.interact.confirm(_("Pastebin buffer? (y/N) "))): self.interact.notify(_("Pastebin aborted.")) return return self.do_pastebin(s) def do_pastebin(self, s): """Actually perform the upload.""" if s == self.prev_pastebin_content: self.interact.notify(_('Duplicate pastebin. Previous URL: %s. ' 'Removal URL: %s') % (self.prev_pastebin_url, self.prev_removal_url), 10) return self.prev_pastebin_url self.interact.notify(_('Posting data to pastebin...')) try: paste_url, removal_url = self.paster.paste(s) except PasteFailed as e: self.interact.notify(_('Upload failed: %s') % e) return self.prev_pastebin_content = s self.prev_pastebin_url = paste_url self.prev_removal_url = removal_url if removal_url is not None: self.interact.notify(_('Pastebin URL: %s - Removal URL: %s') % (paste_url, removal_url), 10) else: self.interact.notify(_('Pastebin URL: %s') % (paste_url, ), 10) return paste_url def push(self, s, insert_into_history=True): """Push a line of code onto the buffer so it can process it all at once when a code block ends""" s = s.rstrip('\n') self.buffer.append(s) if insert_into_history: self.insert_into_history(s) more = self.interp.runsource('\n'.join(self.buffer)) if not more: self.buffer = [] return more def insert_into_history(self, s): try: self.rl_history.append_reload_and_write(s, self.config.hist_file, getpreferredencoding()) except RuntimeError as e: self.interact.notify(u"%s" % (e, )) def prompt_undo(self): """Returns how many lines to undo, 0 means don't undo""" if (self.config.single_undo_time < 0 or self.interp.timer.estimate() < self.config.single_undo_time): return 1 est = self.interp.timer.estimate() n = self.interact.file_prompt( _("Undo how many lines? (Undo will take up to ~%.1f seconds) [1]") % (est,)) try: if n == '': n = '1' n = int(n) except ValueError: self.interact.notify(_('Undo canceled'), .1) return 0 else: if n == 0: self.interact.notify(_('Undo canceled'), .1) return 0 else: message = ngettext('Undoing %d line... (est. %.1f seconds)', 'Undoing %d lines... (est. %.1f seconds)', n) self.interact.notify(message % (n, est), .1) return n def undo(self, n=1): """Go back in the undo history n steps and call reevaluate() Note that in the program this is called "Rewind" because I want it to be clear that this is by no means a true undo implementation, it is merely a convenience bonus.""" if not self.history: return None self.interp.timer.reset_timer() if len(self.history) < n: n = len(self.history) entries = list(self.rl_history.entries) self.history = self.history[:-n] self.reevaluate() self.rl_history.entries = entries def flush(self): """Olivier Grisel brought it to my attention that the logging module tries to call this method, since it makes assumptions about stdout that may not necessarily be true. The docs for sys.stdout say: "stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument." So I consider this to be a bug in logging, and this is a hack to fix it, unfortunately. I'm sure it's not the only module to do it.""" def close(self): """See the flush() method docstring.""" def tokenize(self, s, newline=False): """Tokenizes a line of code, returning pygments tokens with side effects/impurities: - reads self.cpos to see what parens should be highlighted - reads self.buffer to see what came before the passed in line - sets self.highlighted_paren to (buffer_lineno, tokens_for_that_line) for buffer line that should replace that line to unhighlight it, or None if no paren is currently highlighted - calls reprint_line with a buffer's line's tokens and the buffer lineno that has changed if line other than the current line changes """ highlighted_paren = None source = '\n'.join(self.buffer + [s]) cursor = len(source) - self.cpos if self.cpos: cursor += 1 stack = list() all_tokens = list(PythonLexer().get_tokens(source)) # Unfortunately, Pygments adds a trailing newline and strings with # no size, so strip them while not all_tokens[-1][1]: all_tokens.pop() all_tokens[-1] = (all_tokens[-1][0], all_tokens[-1][1].rstrip('\n')) line = pos = 0 parens = dict(zip('{([', '})]')) line_tokens = list() saved_tokens = list() search_for_paren = True for (token, value) in split_lines(all_tokens): pos += len(value) if token is Token.Text and value == '\n': line += 1 # Remove trailing newline line_tokens = list() saved_tokens = list() continue line_tokens.append((token, value)) saved_tokens.append((token, value)) if not search_for_paren: continue under_cursor = (pos == cursor) if token is Token.Punctuation: if value in parens: if under_cursor: line_tokens[-1] = (Parenthesis.UnderCursor, value) # Push marker on the stack stack.append((Parenthesis, value)) else: stack.append((line, len(line_tokens) - 1, line_tokens, value)) elif value in itervalues(parens): saved_stack = list(stack) try: while True: opening = stack.pop() if parens[opening[-1]] == value: break except IndexError: # SyntaxError.. more closed parentheses than # opened or a wrong closing paren opening = None if not saved_stack: search_for_paren = False else: stack = saved_stack if opening and opening[0] is Parenthesis: # Marker found line_tokens[-1] = (Parenthesis, value) search_for_paren = False elif opening and under_cursor and not newline: if self.cpos: line_tokens[-1] = (Parenthesis.UnderCursor, value) else: # The cursor is at the end of line and next to # the paren, so it doesn't reverse the paren. # Therefore, we insert the Parenthesis token # here instead of the Parenthesis.UnderCursor # token. line_tokens[-1] = (Parenthesis, value) (lineno, i, tokens, opening) = opening if lineno == len(self.buffer): highlighted_paren = (lineno, saved_tokens) line_tokens[i] = (Parenthesis, opening) else: highlighted_paren = (lineno, list(tokens)) # We need to redraw a line tokens[i] = (Parenthesis, opening) self.reprint_line(lineno, tokens) search_for_paren = False elif under_cursor: search_for_paren = False self.highlighted_paren = highlighted_paren if line != len(self.buffer): return list() return line_tokens def clear_current_line(self): """This is used as the exception callback for the Interpreter instance. It prevents autoindentation from occuring after a traceback.""" def send_to_external_editor(self, text, filename=None): """Returns modified text from an editor, or the oriignal text if editor exited with non-zero""" encoding = getpreferredencoding() editor_args = shlex.split(prepare_for_exec(self.config.editor, encoding)) with tempfile.NamedTemporaryFile(suffix='.py') as temp: temp.write(text.encode(encoding)) temp.flush() args = editor_args + [prepare_for_exec(temp.name, encoding)] if subprocess.call(args) == 0: with open(temp.name) as f: if py3: return f.read() else: return f.read().decode(encoding) else: return text def open_in_external_editor(self, filename): encoding = getpreferredencoding() editor_args = shlex.split(prepare_for_exec(self.config.editor, encoding)) args = editor_args + [prepare_for_exec(filename, encoding)] return subprocess.call(args) == 0 def edit_config(self): if not (os.path.isfile(self.config.config_path)): if self.interact.confirm(_("Config file does not exist - create " "new from default? (y/N)")): try: default_config = pkgutil.get_data('bpython', 'sample-config') if py3: # py3 files need unicode default_config = default_config.decode('ascii') bpython_dir, script_name = os.path.split(__file__) containing_dir = os.path.dirname( os.path.abspath(self.config.config_path)) if not os.path.exists(containing_dir): os.makedirs(containing_dir) with open(self.config.config_path, 'w') as f: f.write(default_config) except (IOError, OSError) as e: self.interact.notify(_("Error writing file '%s': %s") % (self.config.config.path, e)) return False else: return False try: if self.open_in_external_editor(self.config.config_path): self.interact.notify(_('bpython config file edited. Restart ' 'bpython for changes to take effect.')) except OSError as e: self.interact.notify(_('Error editing config file: %s') % e)
def test_load(self): history = History() history.load(self.filename, self.encoding) self.assertEqual(history.entries, ["#1", "#2"])