Ejemplo n.º 1
0
    def deactivate(self):
        commands.Commands().stop()

        if self._path in sys.path:
            sys.path.remove(self._path)

        self.app.remove_accelerator("win.commander", None)
        self.menu_ext = None
Ejemplo n.º 2
0
    def deactivate(self, window):
        self._instances[window].deactivate()
        del self._instances[window]

        if len(self._instances) == 0:
            commands.Commands().stop()

            if self._path in sys.path:
                sys.path.remove(self._path)
Ejemplo n.º 3
0
    def do_activate(self):
        self._path = os.path.dirname(__file__)

        if not self._path in sys.path:
            sys.path.insert(0, self._path)

        commands.Commands().set_dirs([
            os.path.join(GLib.get_user_config_dir(), 'gedit/commander/modules'),
            os.path.join(self.plugin_info.get_data_dir(), 'modules')
        ])
Ejemplo n.º 4
0
def _expand_commands(cmds):
    if not cmds:
        cmds.extend(commands.Commands().modules())
        return

    old = list(cmds)
    del cmds[:]

    # Expand 'commands' to all the respective subcommands

    for cmd in old:
        for c in cmd.commands():
            bisect.insort(cmds, c)
Ejemplo n.º 5
0
    def __init__(self):
        pluma.Plugin.__init__(self)

        self._instances = {}
        self._path = os.path.dirname(__file__)

        if not self._path in sys.path:
            sys.path.insert(0, self._path)

        commands.Commands().set_dirs([
            os.path.expanduser('~/.config/pluma/commander/modules'),
            os.path.join(self.get_data_dir(), 'modules')
        ])
Ejemplo n.º 6
0
    def do_activate(self):
        self._path = os.path.dirname(__file__)

        if not self._path in sys.path:
            sys.path.insert(0, self._path)

        commands.Commands().set_dirs([
            os.path.join(GLib.get_user_config_dir(), 'gedit/commander/modules'),
            os.path.join(self.plugin_info.get_data_dir(), 'modules')
        ])

        self.app.add_accelerator("<Primary>period", "win.commander", None)

        self.menu_ext = self.extend_menu("view-section-1")
        item = Gio.MenuItem.new(_('Commander Mode'), "win.commander")
        self.menu_ext.append_menu_item(item)
Ejemplo n.º 7
0
    def on_execute(self, dummy, modifier):
        if self._info_window and not self._suspended:
            self._info_window.destroy()

        text = self._entry.get_text().strip()
        words = list(self._re_complete.finditer(text))
        wordsstr = []

        for word in words:
            spec = self._complete_word_match(word)
            wordsstr.append(spec[0])

        if not wordsstr and not self._command_state:
            self._entry.set_text('')
            return

        self.run_command(lambda: commands.Commands().execute(
            self._command_state, text, words, wordsstr, self, modifier))

        return True
Ejemplo n.º 8
0
    def on_execute(self, dummy, modifier):
        if self._info_window and not self._suspended:
            self._info_window.destroy()

        text = self._entry.get_text().strip()
        words = list(self._re_complete.finditer(text))
        wordsstr = []

        for word in words:
            spec = self._complete_word_match(word)
            wordsstr.append(spec[0])

        if not wordsstr and not self._command_state:
            self._entry.set_text('')
            return

        self._suspended = None

        try:
            ret = commands.Commands().execute(self._command_state, text, words,
                                              wordsstr, self, modifier)
        except Exception, e:
            self.command_history_done()
            self._command_state.clear()

            self.prompt()

            # Show error in info
            self.info_show(
                '<b><span color="#f66">Error:</span></b> ' +
                saxutils.escape(str(e)), True)

            if not isinstance(e, commands.exceptions.Execute):
                self.info_show(traceback.format_exc(), False)

            return True
Ejemplo n.º 9
0
    def on_complete(self, dummy, modifier):
        # First split all the text in words
        text = self._entry.get_text()
        pos = self._entry.get_position()

        words = list(self._re_complete.finditer(text))
        wordsstr = []

        for word in words:
            spec = self._complete_word_match(word)
            wordsstr.append(spec[0])

        # Find out at which word the cursor actually is
        # Examples:
        #  * hello world|
        #  * hello| world
        #  * |hello world
        #  * hello wor|ld
        #  * hello  |  world
        #  * "hello world|"
        posidx = None

        for idx in range(0, len(words)):
            spec = self._complete_word_match(words[idx])

            if words[idx].start(0) > pos:
                # Empty space, new completion
                wordsstr.insert(idx, '')
                words.insert(idx, None)
                posidx = idx
                break
            elif spec[2] == pos:
                # At end of word, resume completion
                posidx = idx
                break
            elif spec[1] <= pos and spec[2] > pos:
                # In middle of word, do not complete
                return True

        if posidx == None:
            wordsstr.append('')
            words.append(None)
            posidx = len(wordsstr) - 1

        # First word completes a command, if not in any special 'mode'
        # otherwise, relay completion to the command, or complete by advice
        # from the 'mode' (prompt)
        cmds = commands.Commands()

        if not self._command_state and posidx == 0:
            # Complete the first command
            ret = commands.completion.command(words=wordsstr, idx=posidx)
        else:
            complete = None
            realidx = posidx

            if not self._command_state:
                # Get the command first
                cmd = commands.completion.single_command(wordsstr, 0)
                realidx -= 1

                ww = wordsstr[1:]
            else:
                cmd = self._command_state.top()
                ww = wordsstr

            if cmd:
                complete = cmd.autocomplete_func()

            if not complete:
                return True

            # 'complete' contains a dict with arg -> func to do the completion
            # of the named argument the command (or stack item) expects
            args, varargs = cmd.args()

            # Remove system arguments
            s = ['argstr', 'args', 'entry', 'view']
            args = list(filter(lambda x: not x in s, args))

            if realidx < len(args):
                arg = args[realidx]
            elif varargs:
                arg = '*'
            else:
                return True

            if not arg in complete:
                return True

            func = complete[arg]

            try:
                spec = utils.getargspec(func)

                if not ww:
                    ww = ['']

                kwargs = {'words': ww, 'idx': realidx, 'view': self._view}

                if not spec.keywords:
                    for k in list(kwargs.keys()):
                        if not k in spec.args:
                            del kwargs[k]

                ret = func(**kwargs)
            except Exception as e:
                # Can be number of arguments, or return values or simply buggy
                # modules
                print(e)
                traceback.print_exc()
                return True

        if not ret or not ret[0]:
            return True

        res = ret[0]
        completed = ret[1]

        if len(ret) > 2:
            after = ret[2]
        else:
            after = ' '

        # Replace the word
        if words[posidx] == None:
            # At end of everything, just append
            spec = None

            self._entry.insert_text(completed, self._entry.get_text_length())
            self._entry.set_position(-1)
        else:
            spec = self._complete_word_match(words[posidx])

            self._entry.delete_text(spec[1], spec[2])
            self._entry.insert_text(completed, spec[1])
            self._entry.set_position(spec[1] + len(completed))

        if len(res) == 1:
            # Full completion
            lastpos = self._entry.get_position()

            if not isinstance(res[0],
                              commands.module.Module) or not res[0].commands():
                if words[posidx] and after == ' ' and (
                        words[posidx].group(2) != None
                        or words[posidx].group(3) != None):
                    lastpos = lastpos + 1

                self._entry.insert_text(after, lastpos)
                self._entry.set_position(lastpos + 1)
            elif completed == wordsstr[posidx] or not res[0].method:
                self._entry.insert_text('.', lastpos)
                self._entry.set_position(lastpos + 1)

            if self._info_window:
                self._info_window.destroy()
        else:
            # Show popup with completed items
            if self._info_window:
                self._info_window.clear()

            ret = []

            for x in res:
                if isinstance(x, commands.method.Method):
                    ret.append('<b>' + saxutils.escape(x.name) + '</b> (<i>' +
                               x.oneline_doc() + '</i>)')
                else:
                    ret.append(str(x))

            self.info_show("\n".join(ret), True)

        return True
Ejemplo n.º 10
0
    def on_entry_key_press(self, widget, evnt):
        state = evnt.state & Gtk.accelerator_get_default_mod_mask()
        text = self._entry.get_text()

        if evnt.keyval == Gdk.KEY_Escape:
            if self._info_window:
                if self._suspended:
                    self._suspended.resume()

                if self._info_window:
                    self._info_window.destroy()

                self._entry.set_sensitive(True)
            elif self._accel_group:
                self._accel_group = self._accel_group.parent

                if not self._accel_group or not self._accel_group.parent:
                    self._entry.set_editable(True)
                    self._accel_group = None

                self.prompt()
            elif text:
                self._entry.set_text('')
            elif self._command_state:
                self._command_state.clear()
                self.prompt()
            else:
                self._view.grab_focus()
                self.destroy()

            return True

        if state or self._accel_group:
            # Check if it should be handled by the accel group
            group = self._accel_group

            if not self._accel_group:
                group = commands.Commands().accelerator_group()

            accel = group.activate(evnt.keyval, state)

            if isinstance(accel, commands.accel_group.AccelGroup):
                self._accel_group = accel
                self._entry.set_text('')
                self._entry.set_editable(False)
                self.prompt()

                return True
            elif isinstance(accel, commands.accel_group.AccelCallback):
                self._entry.set_editable(True)
                self.run_command(
                    lambda: accel.activate(self._command_state, self))
                return True

        if not self._entry.get_editable():
            return True

        for handler in self._handlers:
            if (handler[0] == None or handler[0]
                    == state) and evnt.keyval == handler[1] and handler[2](
                        handler[3], state):
                return True

        if self._info_window and self._info_window.empty():
            self._info_window.destroy()

        self._history_prefix = None
        return False
Ejemplo n.º 11
0
    def on_complete(self, dummy, modifier):
        # First split all the text in words
        text = self._entry.get_text()
        pos = self._entry.get_position()

        words = list(self._re_complete.finditer(text))
        wordsstr = []

        for word in words:
            spec = self._complete_word_match(word)
            wordsstr.append(spec[0])

        # Find out at which word the cursor actually is
        # Examples:
        #  * hello world|
        #  * hello| world
        #  * |hello world
        #  * hello wor|ld
        #  * hello  |  world
        #  * "hello world|"
        posidx = None

        for idx in xrange(0, len(words)):
            spec = self._complete_word_match(words[idx])

            if words[idx].start(0) > pos:
                # Empty space, new completion
                wordsstr.insert(idx, '')
                words.insert(idx, None)
                posidx = idx
                break
            elif spec[2] == pos:
                # At end of word, resume completion
                posidx = idx
                break
            elif spec[1] <= pos and spec[2] > pos:
                # In middle of word, do not complete
                return True

        if posidx == None:
            wordsstr.append('')
            words.append(None)
            posidx = len(wordsstr) - 1

        # First word completes a command, if not in any special 'mode'
        # otherwise, relay completion to the command, or complete by advice
        # from the 'mode' (prompt)
        cmds = commands.Commands()

        if not self._command_state and posidx == 0:
            # Complete the first command
            ret = commands.completion.command(words=wordsstr, idx=posidx)
        else:
            complete = None
            realidx = posidx

            if not self._command_state:
                # Get the command first
                cmd = commands.completion.single_command(wordsstr, 0)
                realidx -= 1

                ww = wordsstr[1:]
            else:
                cmd = self._command_state.top()
                ww = wordsstr

            if cmd:
                complete = cmd.autocomplete_func()

            if not complete:
                return True

            # 'complete' contains a dict with arg -> func to do the completion
            # of the named argument the command (or stack item) expects
            args, varargs = cmd.args()

            # Remove system arguments
            s = ['argstr', 'args', 'entry', 'view']
            args = filter(lambda x: not x in s, args)

            if realidx < len(args):
                arg = args[realidx]
            elif varargs:
                arg = '*'
            else:
                return True

            if not arg in complete:
                return True

            func = complete[arg]

            try:
                spec = utils.getargspec(func)

                if not ww:
                    ww = ['']

                kwargs = {'words': ww, 'idx': realidx, 'view': self._view}

                if not spec.keywords:
                    for k in kwargs.keys():
                        if not k in spec.args:
                            del kwargs[k]

                ret = func(**kwargs)
            except Exception, e:
                # Can be number of arguments, or return values or simply buggy
                # modules
                print e
                traceback.print_exc()
                return True
Ejemplo n.º 12
0
    def deactivate(self):
        commands.Commands().stop()

        if self._path in sys.path:
            sys.path.remove(self._path)