Example #1
0
    def _get_completions(self):
        """Return a list of possible completions for the string ending at the point.

        Also set begidx and endidx in the process.
        """
        completions = []
        self.begidx = self.l_buffer.point
        self.endidx = self.l_buffer.point
        buf = self.l_buffer.line_buffer
        if self.completer:
            # get the string to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in self.completer_delims:
                    self.begidx += 1
                    break
            text = ensure_str("".join(buf[self.begidx: self.endidx]))
            log('complete text="%s"' % ensure_unicode(text))
            i = 0
            while 1:
                try:
                    r = self.completer(ensure_unicode(text), i)
                except IndexError:
                    break
                i += 1
                if r is None:
                    break
                elif r and r not in completions:
                    completions.append(r)
                else:
                    pass
            log("text completions=<%s>" %
                list(map(ensure_unicode, completions)))
        if (self.complete_filesystem == "on") and not completions:
            # get the filename to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in " \t\n":
                    self.begidx += 1
                    break
            text = ensure_str("".join(buf[self.begidx: self.endidx]))
            log('file complete text="%s"' % ensure_unicode(text))
            completions = list(
                map(
                    ensure_unicode,
                    glob.glob(os.path.expanduser(text) + "*".encode("ascii")),
                )
            )
            if self.mark_directories == "on":
                mc = []
                for f in completions:
                    if os.path.isdir(f):
                        mc.append(f + os.sep)
                    else:
                        mc.append(f)
                completions = mc
            log("fnames=<%s>" % list(map(ensure_unicode, completions)))
        return completions
Example #2
0
 def _get_completions(self):
     """Return a list of possible completions for the string ending at the point.
     Also set begidx and endidx in the process."""
     completions = []
     self.begidx = self.l_buffer.point
     self.endidx = self.l_buffer.point
     buf = self.l_buffer.line_buffer
     if self.completer:
         # get the string to complete
         while self.begidx > 0:
             self.begidx -= 1
             if buf[self.begidx] in self.completer_delims:
                 self.begidx += 1
                 break
         text = ensure_str(''.join(buf[self.begidx:self.endidx]))
         log('complete text="%s"' % ensure_unicode(text))
         i = 0
         while 1:
             try:
                 r = self.completer(ensure_unicode(text), i)
             except IndexError:
                 break
             except AttributeError:
                 # This is a quick hotfix, completer throws an error whenever
                 # it finds nothing.
                 break
             i += 1
             if r is None:
                 break
             elif r and r not in completions:
                 completions.append(r)
             else:
                 pass
         log('text completions=<%s>' %
             list(map(ensure_unicode, completions)))
     if (self.complete_filesystem == "on") and not completions:
         # get the filename to complete
         while self.begidx > 0:
             self.begidx -= 1
             if buf[self.begidx] in ' \t\n':
                 self.begidx += 1
                 break
         text = ensure_str(''.join(buf[self.begidx:self.endidx]))
         log('file complete text="%s"' % ensure_unicode(text))
         completions = list(
             map(ensure_unicode,
                 glob.glob(os.path.expanduser(text) + '*'.encode('ascii'))))
         if self.mark_directories == 'on':
             mc = []
             for f in completions:
                 if os.path.isdir(f):
                     mc.append(f + os.sep)
                 else:
                     mc.append(f)
             completions = mc
         log('fnames=<%s>' % list(map(ensure_unicode, completions)))
     return completions
Example #3
0
def log_sock(s, event_type=None):
    if sock_silent:
        pass
    else:
        if event_type is None:
            logsocket.sendto(ensure_str(s), (host, port))
        elif event_type in show_event:
            logsocket.sendto(ensure_str(s), (host, port))
        else:
            pass
Example #4
0
 def _get_completions(self):
     """Return a list of possible completions for the string ending at the point.
     Also set begidx and endidx in the process."""
     completions = []
     self.begidx = self.l_buffer.point
     self.endidx = self.l_buffer.point
     buf=self.l_buffer.line_buffer
     if self.completer:
         # get the string to complete
         while self.begidx > 0:
             self.begidx -= 1
             if buf[self.begidx] in self.completer_delims:
                 self.begidx += 1
                 break
         text = ensure_str(''.join(buf[self.begidx:self.endidx]))
         log('complete text="%s"' % ensure_unicode(text))
         i = 0
         while 1:
             try:
                 r = self.completer(ensure_unicode(text), i)
             except IndexError:
                 break
             except TypeError:
                 break
             i += 1
             if r is None:
                 break
             elif r and r not in completions:
                 completions.append(r)
             else:
                 pass
         log('text completions=<%s>' % list(map(ensure_unicode, completions)))
     if (self.complete_filesystem == "on") and not completions:
         # get the filename to complete
         while self.begidx > 0:
             self.begidx -= 1
             if buf[self.begidx] in ' \t\n':
                 self.begidx += 1
                 break
         text = ensure_str(''.join(buf[self.begidx:self.endidx]))
         log('file complete text="%s"' % ensure_unicode(text))
         completions = list(map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*'.encode('ascii'))))
         if self.mark_directories == 'on':
             mc = []
             for f in completions:
                 if os.path.isdir(f):
                     mc.append(f + os.sep)
                 else:
                     mc.append(f)
             completions = mc
         log('fnames=<%s>' % list(map(ensure_unicode, completions)))
     return completions
Example #5
0
    def _get_completions(self):
        '''Return a list of possible completions for the string ending at the point.

        Also set begidx and endidx in the process.'''
        completions = []
        self.begidx = self.l_buffer.point
        self.endidx = self.l_buffer.point
        buf = self.l_buffer.line_buffer
        if self.completer:
            # get the string to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in self.completer_delims:
                    self.begidx += 1
                    break
            text = ensure_str(''.join(buf[self.begidx:self.endidx]))
            log('complete text="%s"' % text)
            i = 0
            while 1:
                try:
                    r = ensure_unicode(self.completer(text, i))
                except:
                    break
                i += 1
                if r and r not in completions:
                    completions.append(r)
                else:
                    break
            log('text completions=%s' % completions)
        if not completions:
            # get the filename to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in ' \t\n':
                    self.begidx += 1
                    break
            text = ensure_str(''.join(buf[self.begidx:self.endidx]))
            log('file complete text="%s"' % text)
            completions = map(ensure_unicode,
                              glob.glob(os.path.expanduser(text) + '*'))
            if self.mark_directories == 'on':
                mc = []
                for f in completions:
                    if os.path.isdir(f):
                        mc.append(f + os.sep)
                    else:
                        mc.append(f)
                completions = mc
            log('fnames=%s' % completions)
        return completions
Example #6
0
    def _get_completions(self):
       
        '''Return a list of possible completions for the string ending at the point.

        Also set begidx and endidx in the process.'''
        completions = []
        self.begidx = self.l_buffer.point
        self.endidx = self.l_buffer.point
        buf=self.l_buffer.line_buffer
        if self.completer:
            # get the string to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in self.completer_delims:
                    self.begidx += 1
                    break
            text = ensure_str(''.join(buf[self.begidx:self.endidx]))
            log('complete text="%s"' % text)
            i = 0
            while 1:
                try:
                    r = ensure_unicode(self.completer(text, i))
                except:
                    break
                i += 1
                if r and r not in completions:
                    completions.append(r)
                else:
                    break
            log('text completions=%s' % completions)
        if not completions:
            # get the filename to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in ' \t\n':
                    self.begidx += 1
                    break
            text = ensure_str(''.join(buf[self.begidx:self.endidx]))
            log('file complete text="%s"' % text)
            completions = map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*'))
            if self.mark_directories == 'on':
                mc = []
                for f in completions:
                    if os.path.isdir(f):
                        mc.append(f + os.sep)
                    else:
                        mc.append(f)
                completions = mc
            log('fnames=%s' % completions)
        return completions
Example #7
0
 def __init__(self):
     self.history = []
     self._history_length = 100
     self._history_cursor = 0
     self.history_filename = os.path.expanduser(ensure_str('~/.history')) #Cannot expand unicode strings correctly on python2.4
     self.lastcommand = None
     self.query = ""
     self.last_search_for = ""
Example #8
0
 def __init__(self):
     self.history = []
     self._history_length = 100
     self._history_cursor = 0
     self.history_filename = os.path.expanduser(ensure_str('~/.history')) #Cannot expand unicode strings correctly on python2.4
     self.lastcommand = None
     self.query = ""
     self.last_search_for = ""
Example #9
0
 def write_history_file(self, filename=None):
     '''Save a readline history file.'''
     if filename is None:
         filename = self.history_filename
     fp = open(filename, 'wb')
     for line in self.history[-self.history_length:]:
         fp.write(ensure_str(line.get_line_text()))
         fp.write('\n')
     fp.close()
 def write_history_file(self, filename=None):
     """Save a readline history file."""
     if filename is None:
         filename = self.history_filename
     fp = open(filename, "wb")
     for line in self.history[-self.history_length :]:
         fp.write(ensure_str(line.get_line_text()))
         fp.write("\n")
     fp.close()
Example #11
0
 def write_history_file(self, filename = None): 
     '''Save a readline history file.'''
     if filename is None:
         filename = self.history_filename
     fp = open(filename, 'wb')
     for line in self.history[-self.history_length:]:
         fp.write(ensure_str(line.get_line_text()))
         fp.write('\n'.encode('ascii'))
     fp.close()
Example #12
0
 def write_history_file(self, filename=None):
     """Save a readline history file."""
     if filename is None:
         filename = self.history_filename
     fp = open(filename, "wb")
     for line in self.history[-self.history_length:]:
         fp.write(ensure_str(line.get_line_text()))
         fp.write("\n")
     fp.close()
Example #13
0
    def write_scrolling(self, text, attr=None):
        '''write text at current cursor position while watching for scrolling.

        If the window scrolls because you are at the bottom of the screen
        buffer, all positions that you are storing will be shifted by the
        scroll amount. For example, I remember the cursor position of the
        prompt so that I can redraw the line but if the window scrolls,
        the remembered position is off.

        This variant of write tries to keep track of the cursor position
        so that it will know when the screen buffer is scrolled. It
        returns the number of lines that the buffer scrolled.

        '''
        x, y = self.pos()
        w, h = self.size()
        scroll = 0  # the result
        # split the string into ordinary characters and funny characters
        chunks = self.motion_char_re.split(ensure_str(text))
        for chunk in chunks:
            n = self.write_color(chunk, attr)
            if len(chunk) == 1:  # the funny characters will be alone
                if chunk[0] == '\n':  # newline
                    x = 0
                    y += 1
                elif chunk[0] == '\r':  # carriage return
                    x = 0
                elif chunk[0] == '\t':  # tab
                    x = 8 * (int(x / 8) + 1)
                    if x > w:  # newline
                        x -= w
                        y += 1
                elif chunk[0] == '\007':  # bell
                    pass
                elif chunk[0] == '\010':
                    x -= 1
                    if x < 0:
                        y -= 1  # backed up 1 line
                else:  # ordinary character
                    x += 1
                if x == w:  # wrap
                    x = 0
                    y += 1
                if y == h:  # scroll
                    scroll += 1
                    y = h - 1
            else:  # chunk of ordinary characters
                x += n
                l = int(x / w)  # lines we advanced
                x = x % w  # new x value
                y += l
                if y >= h:  # scroll
                    scroll += y - h + 1
                    y = h - 1
        return scroll
Example #14
0
    def write_scrolling(self, text, attr=None):
        '''write text at current cursor position while watching for scrolling.

        If the window scrolls because you are at the bottom of the screen
        buffer, all positions that you are storing will be shifted by the
        scroll amount. For example, I remember the cursor position of the
        prompt so that I can redraw the line but if the window scrolls,
        the remembered position is off.

        This variant of write tries to keep track of the cursor position
        so that it will know when the screen buffer is scrolled. It
        returns the number of lines that the buffer scrolled.

        '''
        x, y = self.pos()
        w, h = self.size()
        scroll = 0 # the result
        # split the string into ordinary characters and funny characters
        chunks = self.motion_char_re.split(ensure_str(text))
        for chunk in chunks:
            n = self.write_color(chunk, attr)
            if len(chunk) == 1: # the funny characters will be alone
                if chunk[0] == '\n': # newline
                    x = 0
                    y += 1
                elif chunk[0] == '\r': # carriage return
                    x = 0
                elif chunk[0] == '\t': # tab
                    x = 8 * (int(x / 8) + 1)
                    if x > w: # newline
                        x -= w
                        y += 1
                elif chunk[0] == '\007': # bell
                    pass
                elif chunk[0] == '\010':
                    x -= 1
                    if x < 0:
                        y -= 1 # backed up 1 line
                else: # ordinary character
                    x += 1
                if x == w: # wrap
                    x = 0
                    y += 1
                if y == h: # scroll
                    scroll += 1
                    y = h - 1
            else: # chunk of ordinary characters
                x += n
                l = int(x / w) # lines we advanced
                x = x % w # new x value
                y += l
                if y >= h: # scroll
                    scroll += y - h + 1
                    y = h - 1
        return scroll
Example #15
0
    def scroll(self, rect, dx, dy, attr=None, fill=" "):
        u"""Scroll a rectangle."""
        if attr is None:
            attr = self.attr
        x0, y0, x1, y1 = rect
        source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
        dest = self.fixcoord(x0 + dx, y0 + dy)
        style = CHAR_INFO()
        style.Char.AsciiChar = ensure_str(fill[0])
        style.Attributes = attr

        return self.ScrollConsoleScreenBufferW(self.hout, byref(source), byref(source), dest, byref(style))
Example #16
0
 def scroll(self, rect, dx, dy, attr=None, fill=' '):
     if attr is None:
         attr = self.attr
     x0, y0, x1, y1 = rect
     source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
     dest = self.fixcoord(x0 + dx, y0 + dy)
     style = CHAR_INFO()
     style.Char.AsciiChar = ensure_str(fill[0])
     style.Attributes = attr
     return self.ScrollConsoleScreenBufferW(self.hout, byref(source),
                                            byref(source), dest,
                                            byref(style))
def SetClipboardText(text):
    buffer = c_buffer(ensure_str(text))
    bufferSize = sizeof(buffer)
    hGlobalMem = GlobalAlloc(c_int(GHND), c_int(bufferSize))
    GlobalLock.restype = c_void_p
    lpGlobalMem = GlobalLock(c_int(hGlobalMem))
    memcpy(lpGlobalMem, addressof(buffer), c_int(bufferSize))
    GlobalUnlock(c_int(hGlobalMem))
    if OpenClipboard(0):
        EmptyClipboard()
        SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem))
        CloseClipboard()
Example #18
0
def SetClipboardText(text):
    buffer = c_buffer(ensure_str(text))
    bufferSize = sizeof(buffer)
    hGlobalMem = GlobalAlloc(c_int(GHND), c_int(bufferSize))
    GlobalLock.restype = c_void_p
    lpGlobalMem = GlobalLock(c_int(hGlobalMem))
    memcpy(lpGlobalMem, addressof(buffer), c_int(bufferSize))
    GlobalUnlock(c_int(hGlobalMem))
    if OpenClipboard(0):
        EmptyClipboard()
        SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem))
        CloseClipboard()
Example #19
0
def hook_wrapper_23(stdin, stdout, prompt):
    """Wrap a Python readline so it behaves like GNU readline.

    The following code uses ctypes to allow a Python callable to
    substitute for GNU readline within the Python interpreter. Calling
    raw_input or other functions that do input, inside your callable
    might be a bad idea, then again, it might work.

    The Python callable can raise EOFError or KeyboardInterrupt and
    these will be translated into the appropriate outputs from readline
    so that they will then be translated back!

    If the Python callable raises any other exception, a traceback will
    be printed and readline will appear to return an empty line.

    I use ctypes to create a C-callable from a Python wrapper that
    handles the exceptions and gets the result into the right form.

    """
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, bytes):
            raise TypeError("readline must return a string.")
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = ensure_str("")
    except:
        print("Readline internal error", file=sys.stderr)
        traceback.print_exc()
        res = ensure_str("\n")
    # we have to make a copy because the caller expects to free the result
    n = len(res)
    p = Console.PyMem_Malloc(n + 1)
    _strncpy(cast(p, c_char_p), res, n + 1)
    return p
Example #20
0
def hook_wrapper_23(stdin, stdout, prompt):
    '''Wrap a Python readline so it behaves like GNU readline.'''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, bytes):
            raise TypeError('readline must return a string.')
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = ensure_str('')
    except:
        print('Readline internal error', file=sys.stderr)
        traceback.print_exc()
        res = ensure_str('\n')
    # we have to make a copy because the caller expects to free the result
    n = len(res)
    p = Console.PyMem_Malloc(n + 1)
    _strncpy(cast(p, c_char_p), res, n + 1)
    return p
Example #21
0
def hook_wrapper_23(stdin, stdout, prompt):
    '''Wrap a Python readline so it behaves like GNU readline.'''
    # print(type(stdin), type(stdout), type(prompt), prompt)
    try:
        try:
            IMP = sys._mercurial[0]
        except AttributeError:
            IMP = sys._git[0]

        # call the Python hook
        res = readline_hook(prompt)

        if IMP.lower(
        ) == "pypy" and sys.version > "3.0":  # hay un bug cuando tipea sys.´´ "enter"  aparece  sys.|--
            # make sure it returned the right sort of thing
            if res and isinstance(res, bytes):
                raise TypeError('readline must return a string.')
        else:
            res = ensure_str(res)  # python2/3 o pypy2 only
            # make sure it returned the right sort of thing
            if res and not isinstance(res, bytes):
                raise TypeError('readline must return a string.')
        # print("hook_wrapper_23:_:", type(res))
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        if IMP.lower() != "pypy" and sys.version > "3.0":
            res = b''
        else:
            res = ''
    except:
        print('Readline internal error', file=sys.stderr)
        traceback.print_exc()
        if IMP.lower() != "pypy" and sys.version > "3.0":
            res = b'\n'
        else:
            res = '\n'

    if IMP.lower() == "pypy":
        #        print("\n\ntp: %s, v: %s"%(type(res), res))
        return res
    else:
        #we have to make a copy because the caller expects to free the result
        n = len(res)
        p = Console.PyMem_Malloc(n + 1)
        #        print("\n\ntp: %s, v: %s\ntp: %s, v: %s\ntp: %s, v: %s"%(type(p), p, type(c_char_p), c_char_p, type(res), res))
        _strncpy(cast(p, c_char_p), res, n + 1)
        return p
Example #22
0
def hook_wrapper_23(stdin, stdout, prompt):
    '''Wrap a Python readline so it behaves like GNU readline.'''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, bytes):
            raise TypeError('readline must return a string.')
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = ensure_str('')
    except:
        print('Readline internal error', file=sys.stderr)
        traceback.print_exc()
        res = ensure_str('\n')
    # we have to make a copy because the caller expects to free the result
    n = len(res)
    p = Console.PyMem_Malloc(n + 1)
    _strncpy(cast(p, c_char_p), res, n + 1)
    return p
Example #23
0
    def read_inputrc(self, inputrcpath=None):
        """In this method we `exec` `compile` the inputrc.

        As a result, it's a bit meaningless that it's an ini file.
        It's treated as a python file.

        The context it's executed in is in all the methods of this class.
        """
        if inputrcpath is None:
            inputrcpath = os.path.expanduser(
                ensure_str("~/pyreadlineconfig.ini"))

        loc = {
            # "branch": release.branch,
            # "version": release.version,
            "mode": self.editingmodes[0].mode,
            "modes": dict([(x.mode, x) for x in self.editingmodes]),
            "set_mode": self.setmode,
            "bind_key": self.bind_key,
            "disable_readline": self.disable_readline,
            "bind_exit_key": self.bind_exit_key,
            "un_bind_key": self.un_bind_key,
            "un_bind_exit_key": self.un_bind_exit_key,
            "bell_style": self.setbellstyle,
            "mark_directories": self.mark_directories,
            "show_all_if_ambiguous": self.show_all_if_ambiguous,
            "completer_delims": self.completer_delims,
            "complete_filesystem": self.complete_filesystem,
            "debug_output": debug_output,
            "history_filename": self.sethistoryfilename,
            "history_length": self.sethistorylength,
            "set_prompt_color": self.set_prompt_color,
            "set_input_color": self.set_input_color,
            "allow_ctrl_c": self.allow_ctrl_c,
            "ctrl_c_tap_time_interval": self.ctrl_c_tap_time_interval,
            "kill_ring_to_clipboard": self.setkill_ring_to_clipboard,
            "enable_ipython_paste_for_paths":
            self.enable_ipython_paste_for_paths,
        }
        if os.path.isfile(inputrcpath):
            try:
                execfile(inputrcpath, loc, loc)
            except Exception as x:
                log("Error reading .pyinputrc")
                log(x)
                # old line. wtf
                # filepath, lineno = traceback.extract_tb(sys.exc_traceback)[1][:2]
                # raise ReadlineError("Error reading .pyinputrc")
                raise
Example #24
0
def hook_wrapper(prompt):
    try:
        res = ensure_str(readline_hook(prompt))
        if res and not isinstance(res, str):
            raise TypeError, 'readline must return a string.'
    except KeyboardInterrupt:
        return 0
    except EOFError:
        res = ''
    except:
        print >> sys.stderr, 'Readline internal error'
        traceback.print_exc()
        res = '\n'

    p = _strdup(res)
    return p
Example #25
0
def hook_wrapper_23(stdin, stdout, prompt):
    global readline_hook
    try:
        res = ensure_str(readline_hook(prompt))
        if res and not isinstance(res, str):
            raise TypeError, 'readline must return a string.'
    except KeyboardInterrupt:
        return 0
    except EOFError:
        res = ''
    except:
        print >> sys.stderr, 'Readline internal error'
        traceback.print_exc()
        res = '\n'

    n = len(res)
    p = Console.PyMem_Malloc(n + 1)
    _strncpy(cast(p, c_char_p), res, n + 1)
    return p
Example #26
0
def hook_wrapper(prompt):
    '''Wrap a Python readline so it behaves like GNU readline.'''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, str):
            raise TypeError, 'readline must return a string.'
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = ''
    except:
        print >> sys.stderr, 'Readline internal error'
        traceback.print_exc()
        res = '\n'
    # we have to make a copy because the caller expects to free the result
    p = cdll.msvcrt._strdup(res)
    return p
Example #27
0
def hook_wrapper(prompt):
    '''Wrap a Python readline so it behaves like GNU readline.'''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, str):
            raise TypeError, 'readline must return a string.'
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = ''
    except:
        print >>sys.stderr, 'Readline internal error'
        traceback.print_exc()
        res = '\n'
    # we have to make a copy because the caller expects to free the result
    p = cdll.msvcrt._strdup(res)
    return p
Example #28
0
 def get_current_completed_word(self):
     """Return a current word_between completion separators"""
     begidx = self.l_buffer.point
     endidx = self.l_buffer.point
     buf = self.l_buffer.line_buffer
     l = len(buf)
     if l == 0:
         return ""
     # if we immediately after the symbol go one character back
     if begidx == l or buf[begidx] in self.completer_delims:
         begidx -= 1
     # find the beginning of the word
     while begidx > 0:
         if buf[begidx] in self.completer_delims:
             begidx += 1
             break
         begidx -= 1
     # find the end of the word
     while endidx < l:
         if buf[endidx] in self.completer_delims:
             break
         endidx += 1
     text = ensure_str(u''.join(buf[begidx:endidx]))
     return text
Example #29
0
 def get_current_completed_word(self):
     """Return a current word_between completion separators"""
     begidx = self.l_buffer.point
     endidx = self.l_buffer.point
     buf=self.l_buffer.line_buffer
     l = len(buf)
     if l == 0:
         return ""
     # if we immediately after the symbol go one character back
     if begidx == l or buf[begidx] in self.completer_delims:
         begidx -= 1
     # find the beginning of the word
     while begidx > 0:
         if buf[begidx] in self.completer_delims:
             begidx += 1
             break
         begidx -= 1
     # find the end of the word
     while endidx < l:
         if buf[endidx] in self.completer_delims:
             break
         endidx += 1
     text = ensure_str(u''.join(buf[begidx:endidx]))
     return text
Example #30
0
 def write(self, s):
     self.logsocket.sendto(ensure_str(s), (host, port))
Example #31
0
 def write_color(self, text, attr=None):
     text = ensure_str(text)
     junk = DWORD(0)
     self.WriteFile(self.hout, text, len(text), byref(junk), None)
     return len(text)
Example #32
0
 def sethistoryfilename(filename):
     self.mode._history.history_filename = os.path.expanduser(ensure_str(filename))
Example #33
0
    def read_inputrc(self, #in 2.4 we cannot call expanduser with unicode string
                     inputrcpath=os.path.expanduser(ensure_str("~/pyreadlineconfig.ini"))):
        modes = dict([(x.mode,x) for x in self.editingmodes])
        mode = self.editingmodes[0].mode

        def setmode(name):
            self.mode = modes[name]

        def bind_key(key, name):
            import types
            if callable(name):
                modes[mode]._bind_key(key, types.MethodType(name, modes[mode]))
            elif hasattr(modes[mode], name):
                modes[mode]._bind_key(key, getattr(modes[mode], name))
            else:
                print("Trying to bind unknown command '%s' to key '%s'"%(name, key))

        def un_bind_key(key):
            keyinfo = make_KeyPress_from_keydescr(key).tuple()
            if keyinfo in modes[mode].key_dispatch:
                del modes[mode].key_dispatch[keyinfo]

        def bind_exit_key(key):
            modes[mode]._bind_exit_key(key)

        def un_bind_exit_key(key):
            keyinfo = make_KeyPress_from_keydescr(key).tuple()
            if keyinfo in modes[mode].exit_dispatch:
                del modes[mode].exit_dispatch[keyinfo]

        def setkill_ring_to_clipboard(killring):
            import pyreadline.lineeditor.lineobj
            pyreadline.lineeditor.lineobj.kill_ring_to_clipboard = killring

        def sethistoryfilename(filename):
            self.mode._history.history_filename = os.path.expanduser(ensure_str(filename))

        def setbellstyle(mode):
            self.bell_style = mode

        def disable_readline(mode):
            self.disable_readline = mode

        def sethistorylength(length):
            self.mode._history.history_length = int(length)

        def allow_ctrl_c(mode):
            log("allow_ctrl_c:%s:%s"%(self.allow_ctrl_c, mode))
            self.allow_ctrl_c = mode

        def show_all_if_ambiguous(mode):
            self.mode.show_all_if_ambiguous = mode

        def ctrl_c_tap_time_interval(mode):
            self.ctrl_c_tap_time_interval = mode

        def mark_directories(mode):
            self.mode.mark_directories = mode

        def completer_delims(delims):
            self.mode.completer_delims = delims

        def complete_filesystem(delims):
            self.mode.complete_filesystem = delims.lower()

        def enable_ipython_paste_for_paths(boolean):
            self.mode.enable_ipython_paste_for_paths = boolean

        def debug_output(on, filename="pyreadline_debug_log.txt"): #Not implemented yet
            if on in ["on", "on_nologfile"]:
                self.debug=True

            if on == "on":
                logger.start_file_log(filename)
                logger.start_socket_log()
                logger.log("STARTING LOG")
            elif on == "on_nologfile":
                logger.start_socket_log()
                logger.log("STARTING LOG")
            else:
                logger.log("STOPING LOG")
                logger.stop_file_log()
                logger.stop_socket_log()

        _color_trtable={"black":0,      "darkred":4,  "darkgreen":2,
                        "darkyellow":6, "darkblue":1, "darkmagenta":5,
                        "darkcyan":3,   "gray":7,     "red":4+8,
                        "green":2+8,    "yellow":6+8, "blue":1+8,
                        "magenta":5+8,  "cyan":3+8,   "white":7+8}

        def set_prompt_color(color):
            self.prompt_color = _color_trtable.get(color.lower(),7)

        def set_input_color(color):
            self.command_color = _color_trtable.get(color.lower(),7)

        loc = {"branch":release.branch,
               "version":release.version,
               "mode":mode,
               "modes":modes,
               "set_mode":setmode,
               "bind_key":bind_key,
               "disable_readline":disable_readline,
               "bind_exit_key":bind_exit_key,
               "un_bind_key":un_bind_key,
               "un_bind_exit_key":un_bind_exit_key,
               "bell_style":setbellstyle,
               "mark_directories":mark_directories,
               "show_all_if_ambiguous":show_all_if_ambiguous,
               "completer_delims":completer_delims,
               "complete_filesystem":complete_filesystem,
               "debug_output":debug_output,
               "history_filename":sethistoryfilename,
               "history_length":sethistorylength,
               "set_prompt_color":set_prompt_color,
               "set_input_color":set_input_color,
               "allow_ctrl_c":allow_ctrl_c,
               "ctrl_c_tap_time_interval":ctrl_c_tap_time_interval,
               "kill_ring_to_clipboard":setkill_ring_to_clipboard,
               "enable_ipython_paste_for_paths":enable_ipython_paste_for_paths,
              }
        if os.path.isfile(inputrcpath):
            try:
                execfile(inputrcpath, loc, loc)
            except Exception as x:
                raise
                import traceback
                print("Error reading .pyinputrc", file=sys.stderr)
                if hasattr(sys, 'exc_traceback'):
                    last_traceback = getattr(sys, 'exc_traceback')
                else:
                    last_traceback = sys.exc_info()[2]
                filepath, lineno = traceback.extract_tb(last_traceback)[1][:2]
                print("Line: %s in file %s"%(lineno, filepath), file=sys.stderr)
                print(x, file=sys.stderr)
                raise ReadlineError("Error reading .pyinputrc")
Example #34
0
 def write_color(self, text, attr=None):
     text = ensure_str(text)
     junk = c_int(0)
     self.WriteFile(self.hout, text, len(text), byref(junk), None)
     return len(text)
Example #35
0
def log(s):
    s = ensure_str(s)
    pyreadline_logger.debug(s)
Example #36
0
 def write(self, s):
     self.logsocket.sendto(ensure_str(s), (host, port))
Example #37
0
def log(s):
    s = ensure_str(s)
    root_logger.debug(s)
Example #38
0
def log(s):
    if _logfile:
        s = ensure_str(s)
        print >> _logfile, s
        _logfile.flush()
Example #39
0
def log(s):
    s = ensure_str(s)
    root_logger.debug(s)
Example #40
0
 def sethistoryfilename(filename):
     self.mode._history.history_filename = os.path.expanduser(
         ensure_str(filename))
Example #41
0
    def read_inputrc(self, #in 2.4 we cannot call expanduser with unicode string
                     inputrcpath=os.path.expanduser(ensure_str("~/pyreadlineconfig.ini"))):
        modes = dict([(x.mode, x) for x in self.editingmodes])
        mode = self.editingmodes[0].mode

        def setmode(name):
            self.mode = modes[name]

        def bind_key(key, name):
            import types
            if callable(name):
                modes[mode]._bind_key(key, types.MethodType(name, modes[mode]))
            elif hasattr(modes[mode], name):
                modes[mode]._bind_key(key, getattr(modes[mode], name))
            else:
                print("Trying to bind unknown command '%s' to key '%s'" %
                      (name, key))

        def un_bind_key(key):
            keyinfo = make_KeyPress_from_keydescr(key).tuple()
            if keyinfo in modes[mode].key_dispatch:
                del modes[mode].key_dispatch[keyinfo]

        def bind_exit_key(key):
            modes[mode]._bind_exit_key(key)

        def un_bind_exit_key(key):
            keyinfo = make_KeyPress_from_keydescr(key).tuple()
            if keyinfo in modes[mode].exit_dispatch:
                del modes[mode].exit_dispatch[keyinfo]

        def setkill_ring_to_clipboard(killring):
            import pyreadline.lineeditor.lineobj
            pyreadline.lineeditor.lineobj.kill_ring_to_clipboard = killring

        def sethistoryfilename(filename):
            self.mode._history.history_filename = os.path.expanduser(
                ensure_str(filename))

        def setbellstyle(mode):
            self.bell_style = mode

        def disable_readline(mode):
            self.disable_readline = mode

        def sethistorylength(length):
            self.mode._history.history_length = int(length)

        def allow_ctrl_c(mode):
            log("allow_ctrl_c:%s:%s" % (self.allow_ctrl_c, mode))
            self.allow_ctrl_c = mode

        def setbellstyle(mode):
            self.bell_style = mode

        def show_all_if_ambiguous(mode):
            self.mode.show_all_if_ambiguous = mode

        def ctrl_c_tap_time_interval(mode):
            self.ctrl_c_tap_time_interval = mode

        def mark_directories(mode):
            self.mode.mark_directories = mode

        def completer_delims(delims):
            self.mode.completer_delims = delims

        def complete_filesystem(delims):
            self.mode.complete_filesystem = delims.lower()

        def enable_ipython_paste_for_paths(boolean):
            self.mode.enable_ipython_paste_for_paths = boolean

        def debug_output(
                on, filename="pyreadline_debug_log.txt"):  #Not implemented yet
            if on in ["on", "on_nologfile"]:
                self.debug = True

            if on == "on":
                logger.start_file_log(filename)
                logger.start_socket_log()
                logger.log("STARTING LOG")
            elif on == "on_nologfile":
                logger.start_socket_log()
                logger.log("STARTING LOG")
            else:
                logger.log("STOPING LOG")
                logger.stop_file_log()
                logger.stop_socket_log()

        _color_trtable = {"black": 0,
                          "darkred": 4,
                          "darkgreen": 2,
                          "darkyellow": 6,
                          "darkblue": 1,
                          "darkmagenta": 5,
                          "darkcyan": 3,
                          "gray": 7,
                          "red": 4 + 8,
                          "green": 2 + 8,
                          "yellow": 6 + 8,
                          "blue": 1 + 8,
                          "magenta": 5 + 8,
                          "cyan": 3 + 8,
                          "white": 7 + 8}

        def set_prompt_color(color):
            self.prompt_color = self._color_trtable.get(color.lower(), 7)

        def set_input_color(color):
            self.command_color = self._color_trtable.get(color.lower(), 7)

        loc = {"branch": release.branch,
               "version": release.version,
               "mode": mode,
               "modes": modes,
               "set_mode": setmode,
               "bind_key": bind_key,
               "disable_readline": disable_readline,
               "bind_exit_key": bind_exit_key,
               "un_bind_key": un_bind_key,
               "un_bind_exit_key": un_bind_exit_key,
               "bell_style": setbellstyle,
               "mark_directories": mark_directories,
               "show_all_if_ambiguous": show_all_if_ambiguous,
               "completer_delims": completer_delims,
               "complete_filesystem": complete_filesystem,
               "debug_output": debug_output,
               "history_filename": sethistoryfilename,
               "history_length": sethistorylength,
               "set_prompt_color": set_prompt_color,
               "set_input_color": set_input_color,
               "allow_ctrl_c": allow_ctrl_c,
               "ctrl_c_tap_time_interval": ctrl_c_tap_time_interval,
               "kill_ring_to_clipboard": setkill_ring_to_clipboard,
               "enable_ipython_paste_for_paths":
               enable_ipython_paste_for_paths, }
        if os.path.isfile(inputrcpath):
            try:
                execfile(inputrcpath, loc, loc)
            except Exception as x:
                raise
                import traceback
                print("Error reading .pyinputrc", file=sys.stderr)
                filepath, lineno = traceback.extract_tb(sys.exc_traceback)[
                    1][:2]
                print("Line: %s in file %s" % (lineno, filepath),
                      file=sys.stderr)
                print(x, file=sys.stderr)
                raise ReadlineError("Error reading .pyinputrc")