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 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 #3
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 #4
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 #5
0
    def scroll(self, rect, dx, dy, attr=None, fill=' '):
        '''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 #6
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 #7
0
 def sethistoryfilename(filename):
     self.mode._history.history_filename = os.path.expanduser(
         ensure_str(filename))
Example #8
0
    def read_inputrc(
        self,  #in 2.4 we cannot call expanduser with unicode string
        inputrcpath=os.path.expanduser(ensure_str("~/_plineconfig.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 _pline.lineeditor.lineobj
            _pline.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="_pline_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")
Example #9
0
def log(s):
    s = ensure_str(s)
    _pline_logger.debug(s)
Example #10
0
 def write(self, s):
     self.logsocket.sendto(ensure_str(s), (host, port))