def copy_completer(self, event): from IPython.core.error import TryNext from pylada import interactive line = event.line.split()[1:] result = [] if '-h' not in line and '--help' not in line: result.append('-h') if '-r' not in line and '--recursive' not in line: result.append('-r') noop = [k for k in line if k[0] != '-'] if len(noop) > 2: raise TryNext() if '/' in event.symbol: subkey = "" for key in event.symbol.split('/')[:-1]: subkey += key + "/" try: subdict = interactive.jobfolder[subkey] except KeyError: raise TryNext if hasattr(subdict, "children"): if hasattr(subdict.children, "keys"): return [subkey + a + "/" for a in subdict.children.keys()] raise TryNext() else: result += [a + "/" for a in interactive.jobfolder.children.keys()] result.extend(["/"]) if interactive.jobfolder.parent is not None: result.append("../") if len(getattr(interactive, "_pylada_subjob_iterated", [])) != 0: result.append("previous") return result
def completer(self, event): from IPython.core.error import TryNext from pylada import interactive if len(event.line.split()) > 2: raise TryNext() if '/' in event.symbol: subkey = "" for key in event.symbol.split('/')[:-1]: subkey += key + "/" try: subdict = interactive.jobfolder[subkey] except KeyError: raise TryNext() if hasattr(subdict, "children"): if hasattr(subdict.children, "keys"): return [subkey + a + "/" for a in subdict.children.keys()] raise TryNext() else: result = [a + "/" for a in interactive.jobfolder.children.keys()] result.extend(["/", "next", "reset"]) if interactive.jobfolder.parent is not None: result.append("../") if len(getattr(interactive, "_pylada_subjob_iterated", [])) != 0: result.append("previous") return result
class CommandChainDispatcher: """ Dispatch calls to a chain of commands until some func can handle it Usage: instantiate, execute "add" to add commands (with optional priority), execute normally via f() calling mechanism. """ def __init__(self, commands=None): if commands is None: self.chain = [] else: self.chain = commands def __call__(self, *args, **kw): """ Command chain is called just like normal func. This will call all funcs in chain with the same args as were given to this function, and return the result of first func that didn't raise TryNext """ for prio, cmd in self.chain: #print "prio",prio,"cmd",cmd #dbg try: return cmd(*args, **kw) except TryNext, exc: if exc.args or exc.kwargs: args = exc.args kw = exc.kwargs # if no function will accept it, raise TryNext up to the caller raise TryNext(*args, **kw)
def fix_error_editor(self, filename, linenum, column, msg): """DEPRECATED Open the editor at the given filename, linenumber, column and show an error message. This is used for correcting syntax errors. The current implementation only has special support for the VIM editor, and falls back on the 'editor' hook if VIM is not used. Call ip.set_hook('fix_error_editor',yourfunc) to use your own function, """ warnings.warn( """ `fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed in future versions. It appears to be used only for automatically fixing syntax error that has been broken for a few years and has thus been removed. If you happend to use this function and still need it please make your voice heard on the mailing list [email protected] , or on the GitHub Issue tracker: https://github.com/ipython/ipython/issues/9649 """, UserWarning) def vim_quickfix_file(): t = tempfile.NamedTemporaryFile() t.write('%s:%d:%d:%s\n' % (filename, linenum, column, msg)) t.flush() return t if os.path.basename(self.editor) != 'vim': self.hooks.editor(filename, linenum) return t = vim_quickfix_file() try: if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): raise TryNext() finally: t.close()
def editor(self, filename, linenum=None, wait=True): """Open the default editor at the given filename and linenumber. This is IPython's default editor hook, you can use it as an example to write your own modified one. To set your own editor function as the new editor hook, call ip.set_hook('editor',yourfunc).""" # IPython configures a default editor at startup by reading $EDITOR from # the environment, and falling back on vi (unix) or notepad (win32). editor = self.editor # marker for at which line to open the file (for existing objects) if linenum is None or editor == 'notepad': linemark = '' else: linemark = '+%d' % int(linenum) # Enclose in quotes if necessary and legal if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': editor = '"%s"' % editor # Call the actual editor proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename), shell=True) if wait and proc.wait() != 0: raise TryNext()
def tkinter_clipboard_get(): """ Get the clipboard's text using Tkinter. This is the default on systems that are not Windows or OS X. It may interfere with other UI toolkits and should be replaced with an implementation that uses that toolkit. """ try: from tkinter import Tk, TclError # Py 3 except ImportError: try: from Tkinter import Tk, TclError # Py 2 except ImportError: raise TryNext("Getting text from the clipboard on this platform " "requires the %s-tk package." % ("python3" if py3compat.PY3 else "python")) root = Tk() root.withdraw() try: text = root.clipboard_get() except TclError: raise ClipboardEmpty finally: root.destroy() text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) return text
def call_editor(self, file, line=0): if line is None: line = 0 cmd = itplns(run_template, locals()) print ">",cmd if os.system(cmd) != 0: raise TryNext() if wait: raw_input("Press Enter when done editing:")
def call_editor(self, filename, line=0): if line is None: line = 0 cmd = template.format(filename=pipes.quote(filename), line=line) print ">", cmd proc = subprocess.Popen(cmd, shell=True) if wait and proc.wait() != 0: raise TryNext() if wait: raw_input("Press Enter when done editing:")
def edit_in_textmate(self, filename, linenum=None, wait=True): cmd = ['mate'] if wait: cmd.append('-w') if linenum is not None: cmd.extend(['-l', str(linenum)]) cmd.append(filename) proc = Popen(list2cmdline(cmd), shell=True) if wait and proc.wait() != 0: raise TryNext()
def call_editor(self, filename, line=0): if line is None: line = 0 cmd = template.format(filename=pipes.quote(filename), line=line) print(">", cmd) # pipes.quote doesn't work right on Windows, but it does after splitting if sys.platform.startswith('win'): cmd = shlex.split(cmd) proc = subprocess.Popen(cmd, shell=True) if wait and proc.wait() != 0: raise TryNext() if wait: py3compat.input("Press Enter when done editing:")
def __call__(self, *args, **kw): """ Command chain is called just like normal func. This will call all funcs in chain with the same args as were given to this function, and return the result of first func that didn't raise TryNext""" last_exc = TryNext() for prio, cmd in self.chain: #print "prio",prio,"cmd",cmd #dbg try: return cmd(*args, **kw) except TryNext as exc: last_exc = exc # if no function will accept it, raise TryNext up to the caller raise last_exc
def win32_clipboard_get(): """ Get the current clipboard's text on Windows. Requires Mark Hammond's pywin32 extensions. """ try: import win32clipboard except ImportError: raise TryNext("Getting text from the clipboard requires the pywin32 " "extensions: http://sourceforge.net/projects/pywin32/") win32clipboard.OpenClipboard() text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) # FIXME: convert \r\n to \n? win32clipboard.CloseClipboard() return text
def tkinter_clipboard_get(): """ Get the clipboard's text using Tkinter. This is the default on systems that are not Windows or OS X. It may interfere with other UI toolkits and should be replaced with an implementation that uses that toolkit. """ try: import Tkinter except ImportError: raise TryNext("Getting text from the clipboard on this platform " "requires Tkinter.") root = Tkinter.Tk() root.withdraw() text = root.clipboard_get() root.destroy() return text
def fix_error_editor(self,filename,linenum,column,msg): """Open the editor at the given filename, linenumber, column and show an error message. This is used for correcting syntax errors. The current implementation only has special support for the VIM editor, and falls back on the 'editor' hook if VIM is not used. Call ip.set_hook('fix_error_editor',youfunc) to use your own function, """ def vim_quickfix_file(): t = tempfile.NamedTemporaryFile() t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) t.flush() return t if os.path.basename(self.editor) != 'vim': self.hooks.editor(filename,linenum) return t = vim_quickfix_file() try: if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): raise TryNext() finally: t.close()
def win32_clipboard_get(): """ Get the current clipboard's text on Windows. Requires Mark Hammond's pywin32 extensions. """ try: import win32clipboard except ImportError: raise TryNext("Getting text from the clipboard requires the pywin32 " "extensions: http://sourceforge.net/projects/pywin32/") win32clipboard.OpenClipboard() try: text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) except (TypeError, win32clipboard.error): try: text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT) text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING) except (TypeError, win32clipboard.error): raise ClipboardEmpty finally: win32clipboard.CloseClipboard() return text
def __call__(self): self.called = True raise TryNext(self.message)
def shutdown_hook(self): """ The shutdown hook. """ if self.current_sources: self.dump_current_source() raise TryNext()