Search is not available for this dataset
text stringlengths 75 104k |
|---|
def prefilter_line_info(self, line_info):
"""Prefilter a line that has been converted to a LineInfo object.
This implements the checker/handler part of the prefilter pipe.
"""
# print "prefilter_line_info: ", line_info
handler = self.find_handler(line_info)
return handler.handle(line_info) |
def find_handler(self, line_info):
"""Find a handler for the line_info by trying checkers."""
for checker in self.checkers:
if checker.enabled:
handler = checker.check(line_info)
if handler:
return handler
return self.get_handler_by_name('normal') |
def transform_line(self, line, continue_prompt):
"""Calls the enabled transformers in order of increasing priority."""
for transformer in self.transformers:
if transformer.enabled:
line = transformer.transform(line, continue_prompt)
return line |
def prefilter_line(self, line, continue_prompt=False):
"""Prefilter a single input line as text.
This method prefilters a single line of text by calling the
transformers and then the checkers/handlers.
"""
# print "prefilter_line: ", line, continue_prompt
# All handlers *must* return a value, even if it's blank ('').
# save the line away in case we crash, so the post-mortem handler can
# record it
self.shell._last_input_line = line
if not line:
# Return immediately on purely empty lines, so that if the user
# previously typed some whitespace that started a continuation
# prompt, he can break out of that loop with just an empty line.
# This is how the default python prompt works.
return ''
# At this point, we invoke our transformers.
if not continue_prompt or (continue_prompt and self.multi_line_specials):
line = self.transform_line(line, continue_prompt)
# Now we compute line_info for the checkers and handlers
line_info = LineInfo(line, continue_prompt)
# the input history needs to track even empty lines
stripped = line.strip()
normal_handler = self.get_handler_by_name('normal')
if not stripped:
if not continue_prompt:
self.shell.displayhook.prompt_count -= 1
return normal_handler.handle(line_info)
# special handlers are only allowed for single line statements
if continue_prompt and not self.multi_line_specials:
return normal_handler.handle(line_info)
prefiltered = self.prefilter_line_info(line_info)
# print "prefiltered line: %r" % prefiltered
return prefiltered |
def prefilter_lines(self, lines, continue_prompt=False):
"""Prefilter multiple input lines of text.
This is the main entry point for prefiltering multiple lines of
input. This simply calls :meth:`prefilter_line` for each line of
input.
This covers cases where there are multiple lines in the user entry,
which is the case when the user goes back to a multiline history
entry and presses enter.
"""
llines = lines.rstrip('\n').split('\n')
# We can get multiple lines in one shot, where multiline input 'blends'
# into one line, in cases like recalling from the readline history
# buffer. We need to make sure that in such cases, we correctly
# communicate downstream which line is first and which are continuation
# ones.
if len(llines) > 1:
out = '\n'.join([self.prefilter_line(line, lnum>0)
for lnum, line in enumerate(llines) ])
else:
out = self.prefilter_line(llines[0], continue_prompt)
return out |
def check(self, line_info):
"Instances of IPyAutocall in user_ns get autocalled immediately"
obj = self.shell.user_ns.get(line_info.ifun, None)
if isinstance(obj, IPyAutocall):
obj.set_ip(self.shell)
return self.prefilter_manager.get_handler_by_name('auto')
else:
return None |
def check(self, line_info):
"Allow ! and !! in multi-line statements if multi_line_specials is on"
# Note that this one of the only places we check the first character of
# ifun and *not* the pre_char. Also note that the below test matches
# both ! and !!.
if line_info.continue_prompt \
and self.prefilter_manager.multi_line_specials:
if line_info.esc == ESC_MAGIC:
return self.prefilter_manager.get_handler_by_name('magic')
else:
return None |
def check(self, line_info):
"""Check for escape character and return either a handler to handle it,
or None if there is no escape char."""
if line_info.line[-1] == ESC_HELP \
and line_info.esc != ESC_SHELL \
and line_info.esc != ESC_SH_CAP:
# the ? can be at the end, but *not* for either kind of shell escape,
# because a ? can be a vaild final char in a shell cmd
return self.prefilter_manager.get_handler_by_name('help')
else:
if line_info.pre:
return None
# This returns None like it should if no handler exists
return self.prefilter_manager.get_handler_by_esc(line_info.esc) |
def check(self, line_info):
"""If the ifun is magic, and automagic is on, run it. Note: normal,
non-auto magic would already have been triggered via '%' in
check_esc_chars. This just checks for automagic. Also, before
triggering the magic handler, make sure that there is nothing in the
user namespace which could shadow it."""
if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
return None
# We have a likely magic method. Make sure we should actually call it.
if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
return None
head = line_info.ifun.split('.',1)[0]
if is_shadowed(head, self.shell):
return None
return self.prefilter_manager.get_handler_by_name('magic') |
def check(self, line_info):
"Check if the initital identifier on the line is an alias."
# Note: aliases can not contain '.'
head = line_info.ifun.split('.',1)[0]
if line_info.ifun not in self.shell.alias_manager \
or head not in self.shell.alias_manager \
or is_shadowed(head, self.shell):
return None
return self.prefilter_manager.get_handler_by_name('alias') |
def check(self, line_info):
"""If the 'rest' of the line begins with a function call or pretty much
any python operator, we should simply execute the line (regardless of
whether or not there's a possible autocall expansion). This avoids
spurious (and very confusing) geattr() accesses."""
if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
return self.prefilter_manager.get_handler_by_name('normal')
else:
return None |
def check(self, line_info):
"Check if the initial word/function is callable and autocall is on."
if not self.shell.autocall:
return None
oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
if not oinfo['found']:
return None
if callable(oinfo['obj']) \
and (not self.exclude_regexp.match(line_info.the_rest)) \
and self.function_name_regexp.match(line_info.ifun):
return self.prefilter_manager.get_handler_by_name('auto')
else:
return None |
def handle(self, line_info):
# print "normal: ", line_info
"""Handle normal input lines. Use as a template for handlers."""
# With autoindent on, we need some way to exit the input loop, and I
# don't want to force the user to have to backspace all the way to
# clear the line. The rule will be in this case, that either two
# lines of pure whitespace in a row, or a line of pure whitespace but
# of a size different to the indent level, will exit the input loop.
line = line_info.line
continue_prompt = line_info.continue_prompt
if (continue_prompt and
self.shell.autoindent and
line.isspace() and
0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
line = ''
return line |
def handle(self, line_info):
"""Handle alias input lines. """
transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
# pre is needed, because it carries the leading whitespace. Otherwise
# aliases won't work in indented sections.
line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed)
return line_out |
def handle(self, line_info):
"""Execute the line in a shell, empty return value"""
magic_handler = self.prefilter_manager.get_handler_by_name('magic')
line = line_info.line
if line.lstrip().startswith(ESC_SH_CAP):
# rewrite LineInfo's line, ifun and the_rest to properly hold the
# call to %sx and the actual command to be executed, so
# handle_magic can work correctly. Note that this works even if
# the line is indented, so it handles multi_line_specials
# properly.
new_rest = line.lstrip()[2:]
line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
line_info.ifun = 'sx'
line_info.the_rest = new_rest
return magic_handler.handle(line_info)
else:
cmd = line.lstrip().lstrip(ESC_SHELL)
line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd)
return line_out |
def handle(self, line_info):
"""Execute magic functions."""
ifun = line_info.ifun
the_rest = line_info.the_rest
cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
(ifun + " " + the_rest))
return cmd |
def handle(self, line_info):
"""Handle lines which can be auto-executed, quoting if requested."""
line = line_info.line
ifun = line_info.ifun
the_rest = line_info.the_rest
pre = line_info.pre
esc = line_info.esc
continue_prompt = line_info.continue_prompt
obj = line_info.ofind(self.shell)['obj']
#print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
# This should only be active for single-line input!
if continue_prompt:
return line
force_auto = isinstance(obj, IPyAutocall)
# User objects sometimes raise exceptions on attribute access other
# than AttributeError (we've seen it in the past), so it's safest to be
# ultra-conservative here and catch all.
try:
auto_rewrite = obj.rewrite
except Exception:
auto_rewrite = True
if esc == ESC_QUOTE:
# Auto-quote splitting on whitespace
newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
elif esc == ESC_QUOTE2:
# Auto-quote whole string
newcmd = '%s("%s")' % (ifun,the_rest)
elif esc == ESC_PAREN:
newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
else:
# Auto-paren.
if force_auto:
# Don't rewrite if it is already a call.
do_rewrite = not the_rest.startswith('(')
else:
if not the_rest:
# We only apply it to argument-less calls if the autocall
# parameter is set to 2.
do_rewrite = (self.shell.autocall >= 2)
elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
# Don't autocall in this case: item access for an object
# which is BOTH callable and implements __getitem__.
do_rewrite = False
else:
do_rewrite = True
# Figure out the rewritten command
if do_rewrite:
if the_rest.endswith(';'):
newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
else:
newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
else:
normal_handler = self.prefilter_manager.get_handler_by_name('normal')
return normal_handler.handle(line_info)
# Display the rewritten call
if auto_rewrite:
self.shell.auto_rewrite_input(newcmd)
return newcmd |
def handle(self, line_info):
"""Try to get some help for the object.
obj? or ?obj -> basic information.
obj?? or ??obj -> more details.
"""
normal_handler = self.prefilter_manager.get_handler_by_name('normal')
line = line_info.line
# We need to make sure that we don't process lines which would be
# otherwise valid python, such as "x=1 # what?"
try:
codeop.compile_command(line)
except SyntaxError:
# We should only handle as help stuff which is NOT valid syntax
if line[0]==ESC_HELP:
line = line[1:]
elif line[-1]==ESC_HELP:
line = line[:-1]
if line:
#print 'line:<%r>' % line # dbg
self.shell.magic('pinfo %s' % line_info.ifun)
else:
self.shell.show_usage()
return '' # Empty string is needed here!
except:
raise
# Pass any other exceptions through to the normal handler
return normal_handler.handle(line_info)
else:
# If the code compiles ok, we should handle it normally
return normal_handler.handle(line_info) |
def eventFilter(self, obj, event):
""" Reimplemented to hide on certain key presses and on text edit focus
changes.
"""
if obj == self._text_edit:
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
key = event.key()
if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.hide()
elif key == QtCore.Qt.Key_Escape:
self.hide()
return True
elif etype == QtCore.QEvent.FocusOut:
self.hide()
elif etype == QtCore.QEvent.Enter:
self._hide_timer.stop()
elif etype == QtCore.QEvent.Leave:
self._leave_event_hide()
return super(CallTipWidget, self).eventFilter(obj, event) |
def enterEvent(self, event):
""" Reimplemented to cancel the hide timer.
"""
super(CallTipWidget, self).enterEvent(event)
self._hide_timer.stop() |
def paintEvent(self, event):
""" Reimplemented to paint the background panel.
"""
painter = QtGui.QStylePainter(self)
option = QtGui.QStyleOptionFrame()
option.initFrom(self)
painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option)
painter.end()
super(CallTipWidget, self).paintEvent(event) |
def show_call_info(self, call_line=None, doc=None, maxlines=20):
""" Attempts to show the specified call line and docstring at the
current cursor location. The docstring is possibly truncated for
length.
"""
if doc:
match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc)
if match:
doc = doc[:match.end()] + '\n[Documentation continues...]'
else:
doc = ''
if call_line:
doc = '\n\n'.join([call_line, doc])
return self.show_tip(doc) |
def show_tip(self, tip):
""" Attempts to show the specified tip at the current cursor location.
"""
# Attempt to find the cursor position at which to show the call tip.
text_edit = self._text_edit
document = text_edit.document()
cursor = text_edit.textCursor()
search_pos = cursor.position() - 1
self._start_position, _ = self._find_parenthesis(search_pos,
forward=False)
if self._start_position == -1:
return False
# Set the text and resize the widget accordingly.
self.setText(tip)
self.resize(self.sizeHint())
# Locate and show the widget. Place the tip below the current line
# unless it would be off the screen. In that case, decide the best
# location based trying to minimize the area that goes off-screen.
padding = 3 # Distance in pixels between cursor bounds and tip box.
cursor_rect = text_edit.cursorRect(cursor)
screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit)
point = text_edit.mapToGlobal(cursor_rect.bottomRight())
point.setY(point.y() + padding)
tip_height = self.size().height()
tip_width = self.size().width()
vertical = 'bottom'
horizontal = 'Right'
if point.y() + tip_height > screen_rect.height():
point_ = text_edit.mapToGlobal(cursor_rect.topRight())
# If tip is still off screen, check if point is in top or bottom
# half of screen.
if point_.y() - tip_height < padding:
# If point is in upper half of screen, show tip below it.
# otherwise above it.
if 2*point.y() < screen_rect.height():
vertical = 'bottom'
else:
vertical = 'top'
else:
vertical = 'top'
if point.x() + tip_width > screen_rect.width():
point_ = text_edit.mapToGlobal(cursor_rect.topRight())
# If tip is still off-screen, check if point is in the right or
# left half of the screen.
if point_.x() - tip_width < padding:
if 2*point.x() < screen_rect.width():
horizontal = 'Right'
else:
horizontal = 'Left'
else:
horizontal = 'Left'
pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal))
point = text_edit.mapToGlobal(pos())
if vertical == 'top':
point.setY(point.y() - tip_height - padding)
if horizontal == 'Left':
point.setX(point.x() - tip_width - padding)
self.move(point)
self.show()
return True |
def _find_parenthesis(self, position, forward=True):
""" If 'forward' is True (resp. False), proceed forwards
(resp. backwards) through the line that contains 'position' until an
unmatched closing (resp. opening) parenthesis is found. Returns a
tuple containing the position of this parenthesis (or -1 if it is
not found) and the number commas (at depth 0) found along the way.
"""
commas = depth = 0
document = self._text_edit.document()
char = document.characterAt(position)
# Search until a match is found or a non-printable character is
# encountered.
while category(char) != 'Cc' and position > 0:
if char == ',' and depth == 0:
commas += 1
elif char == ')':
if forward and depth == 0:
break
depth += 1
elif char == '(':
if not forward and depth == 0:
break
depth -= 1
position += 1 if forward else -1
char = document.characterAt(position)
else:
position = -1
return position, commas |
def _leave_event_hide(self):
""" Hides the tooltip after some time has passed (assuming the cursor is
not over the tooltip).
"""
if (not self._hide_timer.isActive() and
# If Enter events always came after Leave events, we wouldn't need
# this check. But on Mac OS, it sometimes happens the other way
# around when the tooltip is created.
QtGui.qApp.topLevelAt(QtGui.QCursor.pos()) != self):
self._hide_timer.start(300, self) |
def _cursor_position_changed(self):
""" Updates the tip based on user cursor movement.
"""
cursor = self._text_edit.textCursor()
if cursor.position() <= self._start_position:
self.hide()
else:
position, commas = self._find_parenthesis(self._start_position + 1)
if position != -1:
self.hide() |
def proxied_attribute(local_attr, proxied_attr, doc):
"""Create a property that proxies attribute ``proxied_attr`` through
the local attribute ``local_attr``.
"""
def fget(self):
return getattr(getattr(self, local_attr), proxied_attr)
def fset(self, value):
setattr(getattr(self, local_attr), proxied_attr, value)
def fdel(self):
delattr(getattr(self, local_attr), proxied_attr)
return property(fget, fset, fdel, doc) |
def canonicalize_path(cwd, path):
"""
Canonicalizes a path relative to a given working directory. That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.
:param cwd: The working directory.
:param path: The path to canonicalize.
:returns: The absolute path.
"""
if not os.path.isabs(path):
path = os.path.join(cwd, path)
return os.path.abspath(path) |
def schema_validate(instance, schema, exc_class, *prefix, **kwargs):
"""
Schema validation helper. Performs JSONSchema validation. If a
schema validation error is encountered, an exception of the
designated class is raised with the validation error message
appropriately simplified and passed as the sole positional
argument.
:param instance: The object to schema validate.
:param schema: The schema to use for validation.
:param exc_class: The exception class to raise instead of the
``jsonschema.ValidationError`` exception.
:param prefix: Positional arguments are interpreted as a list of
keys to prefix to the path contained in the
validation error.
:param kwargs: Keyword arguments to pass to the exception
constructor.
"""
try:
# Do the validation
jsonschema.validate(instance, schema)
except jsonschema.ValidationError as exc:
# Assemble the path
path = '/'.join((a if isinstance(a, six.string_types) else '[%d]' % a)
for a in itertools.chain(prefix, exc.path))
# Construct the message
message = 'Failed to validate "%s": %s' % (path, exc.message)
# Raise the target exception
raise exc_class(message, **kwargs) |
def iter_prio_dict(prio_dict):
"""
Iterate over a priority dictionary. A priority dictionary is a
dictionary keyed by integer priority, with the values being lists
of objects. This generator will iterate over the dictionary in
priority order (from lowest integer value to highest integer
value), yielding each object in the lists in turn.
:param prio_dict: A priority dictionary, as described above.
:returns: An iterator that yields each object in the correct
order, based on priority and ordering within the
priority values.
"""
for _prio, objs in sorted(prio_dict.items(), key=lambda x: x[0]):
for obj in objs:
yield obj |
def masked(self):
"""
Retrieve a read-only subordinate mapping. All values are
stringified, and sensitive values are masked. The subordinate
mapping implements the context manager protocol for
convenience.
"""
if self._masked is None:
self._masked = MaskedDict(self)
return self._masked |
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as file_handler:
return file_handler.read() |
def virtualenv_no_global():
"""
Return True if in a venv and no system site packages.
"""
#this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file
site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')
if running_under_virtualenv() and os.path.isfile(no_global_file):
return True |
def pwordfreq(view, fnames):
"""Parallel word frequency counter.
view - An IPython DirectView
fnames - The filenames containing the split data.
"""
assert len(fnames) == len(view.targets)
view.scatter('fname', fnames, flatten=True)
ar = view.apply(wordfreq, Reference('fname'))
freqs_list = ar.get()
word_set = set()
for f in freqs_list:
word_set.update(f.keys())
freqs = dict(zip(word_set, repeat(0)))
for f in freqs_list:
for word, count in f.iteritems():
freqs[word] += count
return freqs |
def view_decorator(function_decorator):
"""Convert a function based decorator into a class based decorator usable
on class based Views.
Can't subclass the `View` as it breaks inheritance (super in particular),
so we monkey-patch instead.
Based on http://stackoverflow.com/a/8429311
"""
def simple_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return simple_decorator |
def default_aliases():
"""Return list of shell aliases to auto-define.
"""
# Note: the aliases defined here should be safe to use on a kernel
# regardless of what frontend it is attached to. Frontends that use a
# kernel in-process can define additional aliases that will only work in
# their case. For example, things like 'less' or 'clear' that manipulate
# the terminal should NOT be declared here, as they will only work if the
# kernel is running inside a true terminal, and not over the network.
if os.name == 'posix':
default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'),
('cat', 'cat'),
]
# Useful set of ls aliases. The GNU and BSD options are a little
# different, so we make aliases that provide as similar as possible
# behavior in ipython, by passing the right flags for each platform
if sys.platform.startswith('linux'):
ls_aliases = [('ls', 'ls -F --color'),
# long ls
('ll', 'ls -F -o --color'),
# ls normal files only
('lf', 'ls -F -o --color %l | grep ^-'),
# ls symbolic links
('lk', 'ls -F -o --color %l | grep ^l'),
# directories or links to directories,
('ldir', 'ls -F -o --color %l | grep /$'),
# things which are executable
('lx', 'ls -F -o --color %l | grep ^-..x'),
]
else:
# BSD, OSX, etc.
ls_aliases = [('ls', 'ls -F'),
# long ls
('ll', 'ls -F -l'),
# ls normal files only
('lf', 'ls -F -l %l | grep ^-'),
# ls symbolic links
('lk', 'ls -F -l %l | grep ^l'),
# directories or links to directories,
('ldir', 'ls -F -l %l | grep /$'),
# things which are executable
('lx', 'ls -F -l %l | grep ^-..x'),
]
default_aliases = default_aliases + ls_aliases
elif os.name in ['nt', 'dos']:
default_aliases = [('ls', 'dir /on'),
('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
]
else:
default_aliases = []
return default_aliases |
def soft_define_alias(self, name, cmd):
"""Define an alias, but don't raise on an AliasError."""
try:
self.define_alias(name, cmd)
except AliasError, e:
error("Invalid alias: %s" % e) |
def define_alias(self, name, cmd):
"""Define a new alias after validating it.
This will raise an :exc:`AliasError` if there are validation
problems.
"""
nargs = self.validate_alias(name, cmd)
self.alias_table[name] = (nargs, cmd) |
def validate_alias(self, name, cmd):
"""Validate an alias and return the its number of arguments."""
if name in self.no_alias:
raise InvalidAliasError("The name %s can't be aliased "
"because it is a keyword or builtin." % name)
if not (isinstance(cmd, basestring)):
raise InvalidAliasError("An alias command must be a string, "
"got: %r" % cmd)
nargs = cmd.count('%s')
if nargs>0 and cmd.find('%l')>=0:
raise InvalidAliasError('The %s and %l specifiers are mutually '
'exclusive in alias definitions.')
return nargs |
def call_alias(self, alias, rest=''):
"""Call an alias given its name and the rest of the line."""
cmd = self.transform_alias(alias, rest)
try:
self.shell.system(cmd)
except:
self.shell.showtraceback() |
def transform_alias(self, alias,rest=''):
"""Transform alias to system command string."""
nargs, cmd = self.alias_table[alias]
if ' ' in cmd and os.path.isfile(cmd):
cmd = '"%s"' % cmd
# Expand the %l special to be the user's input line
if cmd.find('%l') >= 0:
cmd = cmd.replace('%l', rest)
rest = ''
if nargs==0:
# Simple, argument-less aliases
cmd = '%s %s' % (cmd, rest)
else:
# Handle aliases with positional arguments
args = rest.split(None, nargs)
if len(args) < nargs:
raise AliasError('Alias <%s> requires %s arguments, %s given.' %
(alias, nargs, len(args)))
cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
return cmd |
def expand_alias(self, line):
""" Expand an alias in the command line
Returns the provided command line, possibly with the first word
(command) translated according to alias expansion rules.
[ipython]|16> _ip.expand_aliases("np myfile.txt")
<16> 'q:/opt/np/notepad++.exe myfile.txt'
"""
pre,_,fn,rest = split_user_input(line)
res = pre + self.expand_aliases(fn, rest)
return res |
def expand_aliases(self, fn, rest):
"""Expand multiple levels of aliases:
if:
alias foo bar /tmp
alias baz foo
then:
baz huhhahhei -> bar /tmp huhhahhei
"""
line = fn + " " + rest
done = set()
while 1:
pre,_,fn,rest = split_user_input(line, shell_line_split)
if fn in self.alias_table:
if fn in done:
warn("Cyclic alias definition, repeated '%s'" % fn)
return ""
done.add(fn)
l2 = self.transform_alias(fn, rest)
if l2 == line:
break
# ls -> ls -F should not recurse forever
if l2.split(None,1)[0] == line.split(None,1)[0]:
line = l2
break
line=l2
else:
break
return line |
def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in '"', "'", "\\", "#":
if c in arg: return repr(arg)
if arg.split()<>[arg]:
return repr(arg)
return arg |
def autohelp_directive(dirname, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""produces rst from nose help"""
config = Config(parserClass=OptBucket,
plugins=BuiltinPluginManager())
parser = config.getParser(TestProgram.usage())
rst = ViewList()
for line in parser.format_help().split('\n'):
rst.append(line, '<autodoc>')
rst.append('Options', '<autodoc>')
rst.append('-------', '<autodoc>')
rst.append('', '<autodoc>')
for opt in parser:
rst.append(opt.options(), '<autodoc>')
rst.append(' \n', '<autodoc>')
rst.append(' ' + opt.help + '\n', '<autodoc>')
rst.append('\n', '<autodoc>')
node = nodes.section()
node.document = state.document
surrounding_title_styles = state.memo.title_styles
surrounding_section_level = state.memo.section_level
state.memo.title_styles = []
state.memo.section_level = 0
state.nested_parse(rst, 0, node, match_titles=1)
state.memo.title_styles = surrounding_title_styles
state.memo.section_level = surrounding_section_level
return node.children |
def reset_sgr(self):
""" Reset graphics attributs to their default values.
"""
self.intensity = 0
self.italic = False
self.bold = False
self.underline = False
self.foreground_color = None
self.background_color = None |
def split_string(self, string):
""" Yields substrings for which the same escape code applies.
"""
self.actions = []
start = 0
# strings ending with \r are assumed to be ending in \r\n since
# \n is appended to output strings automatically. Accounting
# for that, here.
last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None
string = string[:-1] if last_char is not None else string
for match in ANSI_OR_SPECIAL_PATTERN.finditer(string):
raw = string[start:match.start()]
substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
if substring or self.actions:
yield substring
self.actions = []
start = match.end()
groups = filter(lambda x: x is not None, match.groups())
g0 = groups[0]
if g0 == '\a':
self.actions.append(BeepAction('beep'))
yield None
self.actions = []
elif g0 == '\r':
self.actions.append(CarriageReturnAction('carriage-return'))
yield None
self.actions = []
elif g0 == '\b':
self.actions.append(BackSpaceAction('backspace'))
yield None
self.actions = []
elif g0 == '\n' or g0 == '\r\n':
self.actions.append(NewLineAction('newline'))
yield g0
self.actions = []
else:
params = [ param for param in groups[1].split(';') if param ]
if g0.startswith('['):
# Case 1: CSI code.
try:
params = map(int, params)
except ValueError:
# Silently discard badly formed codes.
pass
else:
self.set_csi_code(groups[2], params)
elif g0.startswith(']'):
# Case 2: OSC code.
self.set_osc_code(params)
raw = string[start:]
substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
if substring or self.actions:
yield substring
if last_char is not None:
self.actions.append(NewLineAction('newline'))
yield last_char |
def set_csi_code(self, command, params=[]):
""" Set attributes based on CSI (Control Sequence Introducer) code.
Parameters
----------
command : str
The code identifier, i.e. the final character in the sequence.
params : sequence of integers, optional
The parameter codes for the command.
"""
if command == 'm': # SGR - Select Graphic Rendition
if params:
self.set_sgr_code(params)
else:
self.set_sgr_code([0])
elif (command == 'J' or # ED - Erase Data
command == 'K'): # EL - Erase in Line
code = params[0] if params else 0
if 0 <= code <= 2:
area = 'screen' if command == 'J' else 'line'
if code == 0:
erase_to = 'end'
elif code == 1:
erase_to = 'start'
elif code == 2:
erase_to = 'all'
self.actions.append(EraseAction('erase', area, erase_to))
elif (command == 'S' or # SU - Scroll Up
command == 'T'): # SD - Scroll Down
dir = 'up' if command == 'S' else 'down'
count = params[0] if params else 1
self.actions.append(ScrollAction('scroll', dir, 'line', count)) |
def set_osc_code(self, params):
""" Set attributes based on OSC (Operating System Command) parameters.
Parameters
----------
params : sequence of str
The parameters for the command.
"""
try:
command = int(params.pop(0))
except (IndexError, ValueError):
return
if command == 4:
# xterm-specific: set color number to color spec.
try:
color = int(params.pop(0))
spec = params.pop(0)
self.color_map[color] = self._parse_xterm_color_spec(spec)
except (IndexError, ValueError):
pass |
def set_sgr_code(self, params):
""" Set attributes based on SGR (Select Graphic Rendition) codes.
Parameters
----------
params : sequence of ints
A list of SGR codes for one or more SGR commands. Usually this
sequence will have one element per command, although certain
xterm-specific commands requires multiple elements.
"""
# Always consume the first parameter.
if not params:
return
code = params.pop(0)
if code == 0:
self.reset_sgr()
elif code == 1:
if self.bold_text_enabled:
self.bold = True
else:
self.intensity = 1
elif code == 2:
self.intensity = 0
elif code == 3:
self.italic = True
elif code == 4:
self.underline = True
elif code == 22:
self.intensity = 0
self.bold = False
elif code == 23:
self.italic = False
elif code == 24:
self.underline = False
elif code >= 30 and code <= 37:
self.foreground_color = code - 30
elif code == 38 and params and params.pop(0) == 5:
# xterm-specific: 256 color support.
if params:
self.foreground_color = params.pop(0)
elif code == 39:
self.foreground_color = None
elif code >= 40 and code <= 47:
self.background_color = code - 40
elif code == 48 and params and params.pop(0) == 5:
# xterm-specific: 256 color support.
if params:
self.background_color = params.pop(0)
elif code == 49:
self.background_color = None
# Recurse with unconsumed parameters.
self.set_sgr_code(params) |
def get_color(self, color, intensity=0):
""" Returns a QColor for a given color code, or None if one cannot be
constructed.
"""
if color is None:
return None
# Adjust for intensity, if possible.
if color < 8 and intensity > 0:
color += 8
constructor = self.color_map.get(color, None)
if isinstance(constructor, basestring):
# If this is an X11 color name, we just hope there is a close SVG
# color name. We could use QColor's static method
# 'setAllowX11ColorNames()', but this is global and only available
# on X11. It seems cleaner to aim for uniformity of behavior.
return QtGui.QColor(constructor)
elif isinstance(constructor, (tuple, list)):
return QtGui.QColor(*constructor)
return None |
def get_format(self):
""" Returns a QTextCharFormat that encodes the current style attributes.
"""
format = QtGui.QTextCharFormat()
# Set foreground color
qcolor = self.get_color(self.foreground_color, self.intensity)
if qcolor is not None:
format.setForeground(qcolor)
# Set background color
qcolor = self.get_color(self.background_color, self.intensity)
if qcolor is not None:
format.setBackground(qcolor)
# Set font weight/style options
if self.bold:
format.setFontWeight(QtGui.QFont.Bold)
else:
format.setFontWeight(QtGui.QFont.Normal)
format.setFontItalic(self.italic)
format.setFontUnderline(self.underline)
return format |
def set_background_color(self, color):
""" Given a background color (a QColor), attempt to set a color map
that will be aesthetically pleasing.
"""
# Set a new default color map.
self.default_color_map = self.darkbg_color_map.copy()
if color.value() >= 127:
# Colors appropriate for a terminal with a light background. For
# now, only use non-bright colors...
for i in xrange(8):
self.default_color_map[i + 8] = self.default_color_map[i]
# ...and replace white with black.
self.default_color_map[7] = self.default_color_map[15] = 'black'
# Update the current color map with the new defaults.
self.color_map.update(self.default_color_map) |
def generate(secret, age, **payload):
"""Generate a one-time jwt with an age in seconds"""
jti = str(uuid.uuid1()) # random id
if not payload:
payload = {}
payload['exp'] = int(time.time() + age)
payload['jti'] = jti
return jwt.encode(payload, decode_secret(secret)) |
def mutex(func):
"""use a thread lock on current method, if self.lock is defined"""
def wrapper(*args, **kwargs):
"""Decorator Wrapper"""
lock = args[0].lock
lock.acquire(True)
try:
return func(*args, **kwargs)
except:
raise
finally:
lock.release()
return wrapper |
def _clean(self):
"""Run by housekeeper thread"""
now = time.time()
for jwt in self.jwts.keys():
if (now - self.jwts[jwt]) > (self.age * 2):
del self.jwts[jwt] |
def already_used(self, tok):
"""has this jwt been used?"""
if tok in self.jwts:
return True
self.jwts[tok] = time.time()
return False |
def valid(self, token):
"""is this token valid?"""
now = time.time()
if 'Bearer ' in token:
token = token[7:]
data = None
for secret in self.secrets:
try:
data = jwt.decode(token, secret)
break
except jwt.DecodeError:
continue
except jwt.ExpiredSignatureError:
raise JwtFailed("Jwt expired")
if not data:
raise JwtFailed("Jwt cannot be decoded")
exp = data.get('exp')
if not exp:
raise JwtFailed("Jwt missing expiration (exp)")
if now - exp > self.age:
raise JwtFailed("Jwt bad expiration - greater than I want to accept")
jti = data.get('jti')
if not jti:
raise JwtFailed("Jwt missing one-time id (jti)")
if self.already_used(jti):
raise JwtFailed("Jwt re-use disallowed (jti={})".format(jti))
return data |
def split_lines(nb):
"""split likely multiline text into lists of strings
For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will
reverse the effects of ``split_lines(nb)``.
Used when writing JSON files.
"""
for ws in nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
if 'input' in cell and isinstance(cell.input, basestring):
cell.input = cell.input.splitlines()
for output in cell.outputs:
for key in _multiline_outputs:
item = output.get(key, None)
if isinstance(item, basestring):
output[key] = item.splitlines()
else: # text cell
for key in ['source', 'rendered']:
item = cell.get(key, None)
if isinstance(item, basestring):
cell[key] = item.splitlines()
return nb |
def write(self, nb, fp, **kwargs):
"""Write a notebook to a file like object"""
return fp.write(self.writes(nb,**kwargs)) |
def semaphore(count: int, bounded: bool=False):
'''
use `Semaphore` to keep func access thread-safety.
example:
``` py
@semaphore(3)
def func(): pass
```
'''
lock_type = threading.BoundedSemaphore if bounded else threading.Semaphore
lock_obj = lock_type(value=count)
return with_it(lock_obj) |
def inputhook_glut():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
signal.signal(signal.SIGINT, glut_int_handler)
try:
t = clock()
# Make sure the default window is set after a window has been closed
if glut.glutGetWindow() == 0:
glut.glutSetWindow( 1 )
glutMainLoopEvent()
return 0
while not stdin_ready():
glutMainLoopEvent()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 5*60.0:
# print 'Sleep for 5 s' # dbg
time.sleep(5.0)
elif used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
except KeyboardInterrupt:
pass
return 0 |
def commonprefix(items):
"""Get common prefix for completions
Return the longest common prefix of a list of strings, but with special
treatment of escape characters that might precede commands in IPython,
such as %magic functions. Used in tab completion.
For a more general function, see os.path.commonprefix
"""
# the last item will always have the least leading % symbol
# min / max are first/last in alphabetical order
first_match = ESCAPE_RE.match(min(items))
last_match = ESCAPE_RE.match(max(items))
# common suffix is (common prefix of reversed items) reversed
if first_match and last_match:
prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1]
else:
prefix = ''
items = [s.lstrip(ESCAPE_CHARS) for s in items]
return prefix+os.path.commonprefix(items) |
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.qApp.sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Ensure that drags are safe. The problem is that the drag starting
# logic, which determines whether the drag is a Copy or Move, is locked
# down in QTextControl. If the widget is editable, which it must be if
# we're not executing, the drag will be a Move. The following hack
# prevents QTextControl from deleting the text by clearing the selection
# when a drag leave event originating from this widget is dispatched.
# The fact that we have to clear the user's selection is unfortunate,
# but the alternative--trying to prevent Qt from using its hardwired
# drag logic and writing our own--is worse.
elif etype == QtCore.QEvent.DragEnter and \
obj == self._control.viewport() and \
event.source() == self._control.viewport():
self._filter_drag = True
elif etype == QtCore.QEvent.DragLeave and \
obj == self._control.viewport() and \
self._filter_drag:
cursor = self._control.textCursor()
cursor.clearSelection()
self._control.setTextCursor(cursor)
self._filter_drag = False
# Ensure that drops are safe.
elif etype == QtCore.QEvent.Drop and obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
if self._in_buffer(cursor.position()):
text = event.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
# Qt is expecting to get something here--drag and drop occurs in its
# own event loop. Send a DragLeave event to end it.
QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent())
return True
# Handle scrolling of the vsplit pager. This hack attempts to solve
# problems with tearing of the help text inside the pager window. This
# happens only on Mac OS X with both PySide and PyQt. This fix isn't
# perfect but makes the pager more usable.
elif etype in self._pager_scroll_events and \
obj == self._page_control:
self._page_control.repaint()
return True
return super(ConsoleWidget, self).eventFilter(obj, event) |
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * 81 + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * 25 + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height) |
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position())) |
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False |
def clear(self, keep_input=True):
""" Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer |
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText() |
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters:
-----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises:
-------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns:
--------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
complete = self._is_complete(source, interactive)
if hidden:
if complete:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._input_buffer_executing = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete |
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing and not force:
return self._input_buffer_executing
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n') |
def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the text for later.
if self._executing:
self._input_buffer_pending = string
return
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End) |
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font) |
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters:
-----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtGui.QApplication.clipboard().text(mode).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text)) |
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer) |
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor) |
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco
fallback = 'Monaco'
else:
# Monospace should always exist
fallback = 'Monospace'
font = get_font(self.font_family, fallback)
if self.font_size:
font.setPointSize(self.font_size)
else:
font.setPointSize(QtGui.qApp.font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font) |
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font) |
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width |
def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
cursor.setPosition(self._append_before_prompt_pos)
else:
cursor.movePosition(QtGui.QTextCursor.End)
start_pos = cursor.position()
# Perform the insertion.
result = insert(cursor, input)
# Adjust the prompt position if we have inserted before it. This is safe
# because buffer truncation is disabled when not executing.
if before_prompt and not self._executing:
diff = cursor.position() - start_pos
self._append_before_prompt_pos += diff
self._prompt_pos += diff
return result |
def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt) |
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt) |
def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt) |
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True) |
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items) |
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True |
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu |
def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier) |
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
# Install event filters. The filter on the viewport is needed for
# mouse events and drag events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control |
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control |
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0:
self.exit_requested.emit(self)
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
# real tab-key, insert four spaces
cursor.insertText(' '*4)
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
cursor.movePosition(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
if shift_down and self._in_buffer(position):
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted |
def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
return False |
def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.viewport().width()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth) |
def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText() |
def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor |
def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt) |
def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):] |
def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None |
def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor |
def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.