Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def matches_lines(rows, columns, matches, current, config, match_format):
highlight_color = func_for_letter(config.color_scheme["operator"].lower())
if not matches:
return []
color = func_for_letter(config.color_scheme["main"])
max_match_width = max(len(m) for m in matches)
words_wide = max(1, (columns - 1) // (max_match_width + 1))
matches = [match_format(m) for m in matches]
if current:
current = match_format(current)
matches = paginate(rows, matches, current, words_wide)
result = [
fmtstr(" ").join(
color(m.ljust(max_match_width))
if m != current
else highlight_color(m.ljust(max_match_width))
for m in matches[i : i + words_wide]
)
for i in range(0, len(matches), words_wide)
def matches_lines(rows, columns, matches, current, config, format):
highlight_color = func_for_letter(config.color_scheme['operator'].lower())
if not matches:
return []
color = func_for_letter(config.color_scheme['main'])
max_match_width = max(len(m) for m in matches)
words_wide = max(1, (columns - 1) // (max_match_width + 1))
matches = [format(m) for m in matches]
if current:
current = format(current)
matches = paginate(rows, matches, current, words_wide)
matches_lines = [fmtstr(' ').join(color(m.ljust(max_match_width))
if m != current
else highlight_color(
m.ljust(max_match_width))
for m in matches[i:i + words_wide])
for i in range(0, len(matches), words_wide)]
logger.debug('match: %r' % current)
translations.init()
import argparse
parser = argparse.ArgumentParser(
description='the boldly indiscriminate Python interpreter')
parser.add_argument( '-v','--version', action='version',
version='%(prog)s ' + version)
parser.parse_known_args()
# ok, it's not nice, i'm hiding all of these params, but LTS.
#
# TODO: maybe support displays other than raw_display?
config, options, exec_args = bpargs.parse(args, (
'Urwid options', None, [
Option('--twisted', '-T', action='store_true',
help=_('Run twisted reactor.')),
Option('--reactor', '-r',
help=_('Select specific reactor (see --help-reactors). '
'Implies --twisted.')),
Option('--help-reactors', action='store_true',
help=_('List available reactors for -r.')),
Option('--plugin', '-p',
help=_('twistd plugin to run (use twistd for a list). '
'Use "--" to pass further options to the plugin.')),
Option('--server', '-s', type='int',
help=_('Port to run an eval server on (forces Twisted).')),
]))
if options.help_reactors:
try:
from twisted.application import reactors
# Stolen from twisted.application.app (twistd).
if text == for_editor:
self.status_bar.message(
_("Session not reevaluated because it was not edited")
)
return
lines = text.split("\n")
if not lines[-1].strip():
lines.pop() # strip last line if empty
if lines[-1].startswith("### "):
current_line = lines[-1][4:]
else:
current_line = ""
from_editor = [line for line in lines if line[:3] != "###"]
if all(not line.strip() for line in from_editor):
self.status_bar.message(
_("Session not reevaluated because saved file was blank")
)
return
source = preprocess("\n".join(from_editor), self.interp.compile)
lines = source.split("\n")
self.history = lines
self.reevaluate(insert_into_history=True)
self.current_line = current_line
self.cursor_offset = len(self.current_line)
self.status_bar.message(_("Session edited and reevaluated"))
for model in app_models:
try:
imported_objects[model.__name__] = getattr(__import__(app_mod.__name__, {}, {}, model.__name__), model.__name__)
except AttributeError, e:
print self.style.ERROR("Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_mod.__name__.split('.')[-2], str(e)))
continue
try:
if use_plain:
# Don't bother loading B/IPython, because the user wants plain Python.
raise ImportError
try:
if use_ipython:
# User wants IPython
raise ImportError
from bpython import embed
embed(imported_objects)
except ImportError:
# Explicitly pass an empty list as arguments, because otherwise IPython
# would use sys.argv from this script.
try:
from IPython.core.iplib import InteractiveShell
shell = InteractiveShell(user_ns=imported_objects)
except ImportError:
import IPython
shell = IPython.Shell.IPShell(argv=[], user_ns=imported_objects)
shell.mainloop()
except ImportError:
# Using normal Python shell
import code
try: # Try activating rlcompleter, because it's handy.
import readline
except ImportError:
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
# current prompt run will end up appended to the edit widget
# sitting above this prompt:
self.current_output = None
# XXX is this the right place?
self.rl_history.reset()
# XXX what is s_hist?
# We need the caption to use unicode as urwid normalizes later
# input to be the same type, using ascii as encoding. If the
# caption is bytes this breaks typing non-ascii into bpython.
if not more:
caption = ("prompt", self.ps1)
if py3:
self.stdout_hist += self.ps1
else:
self.stdout_hist += self.ps1.encode(getpreferredencoding())
else:
caption = ("prompt_more", self.ps2)
if py3:
self.stdout_hist += self.ps2
else:
self.stdout_hist += self.ps2.encode(getpreferredencoding())
self.edit = BPythonEdit(self.config, caption=caption)
urwid.connect_signal(self.edit, "change", self.on_input_change)
urwid.connect_signal(
self.edit, "edit-pos-changed", self.on_edit_pos_changed
)
# Do this after connecting the change signal handler:
self.edit.insert_text(4 * self.next_indentation() * " ")
self.edits.append(self.edit)
self.listbox.body.append(self.edit)
def write(self, s):
"""For overriding stdout defaults"""
if "\x04" in s:
for block in s.split("\x04"):
self.write(block)
return
if s.rstrip() and "\x03" in s:
t = s.split("\x03")[1]
else:
t = s
if not py3 and isinstance(t, unicode):
t = t.encode(getpreferredencoding())
if not self.stdout_hist:
self.stdout_hist = t
else:
self.stdout_hist += t
self.echo(s)
self.s_hist.append(s.rstrip())
def formatted_docstring(docstring, columns, config):
if isinstance(docstring, bytes):
docstring = docstring.decode('utf8')
elif isinstance(docstring, str if py3 else unicode):
pass
else:
# TODO: fail properly here and catch possible exceptions in callers.
return []
color = func_for_letter(config.color_scheme['comment'])
return sum(([color(x) for x in (display_linize(line, columns) if line else
fmtstr(''))]
for line in docstring.split('\n')), [])
"""
# TODO allow for as's
tokens = line.split()
if not ("from" in tokens or "import" in tokens):
return None
matches = current_from_import_from_re.finditer(line)
for m in matches:
if (m.start(1) < cursor_offset and m.end(1) >= cursor_offset) or (
m.start(2) < cursor_offset and m.end(2) >= cursor_offset
):
return LinePart(m.start(1), m.end(1), m.group(1))
return None
current_from_import_import_re_1 = LazyReCompile(r"from\s([\w0-9_.]*)\s+import")
current_from_import_import_re_2 = LazyReCompile(r"([\w0-9_]+)")
current_from_import_import_re_3 = LazyReCompile(r"[,][ ]([\w0-9_]*)")
def current_from_import_import(cursor_offset, line):
"""If in from import completion, the word after import being completed
returns None if cursor not in or just after one of these words
"""
baseline = current_from_import_import_re_1.search(line)
if baseline is None:
return None
match1 = current_from_import_import_re_2.search(line[baseline.end() :])
if match1 is None:
return None
matches = current_from_import_import_re_3.finditer(line[baseline.end() :])
for m in chain((match1,), matches):