Example #1
0
    def action_add(self, context):
        """Add a project to ``projectile#data_dir``/projects.json."""
        data_file = expand(self.vars['data_dir'] + '/projects.json')
        root_dir = self.vim.call('getcwd')
        boofer = self.vim.current.buffer.name
        pj_root = path2project(self.vim, boofer, ['.git', '.svn', '.hg'])
        pj_name = basename(normpath(pj_root))
        new_data = {}

        project_root = input(self.vim, context, 'Project Root: ', pj_root)
        if not len(project_root):
            project_root = pj_root

        project_name = input(self.vim, context, 'Project Name: ', pj_name)
        if not len(project_name):
            project_name = pj_name

        new_data = {
            'name': project_name,
            'root': project_root,
            'timestamp': str(datetime.datetime.now().isoformat()),
            'description': '',
            'vcs': isdir("{}/.git".format(
                root_dir))  # TODO: Also check for .hg/ and .svn
        }

        with open(data_file, 'r') as g:
            try:
                json_info = json.load(g)
            except json.JSONDecodeError:
                json_info = []
            json_info.append(new_data)

        with open(data_file, 'w') as f:
            json.dump(json_info, f, indent=2)
Example #2
0
    def action_add(self, context):
        """Add a bookmark to ``projectile#data_dir``/bookmarks.json"""
        data_file = util.expand(self.vars['data_dir'] + '/bookmarks.json')
        boofer = self.vim.current.buffer.name
        linenr = self.vim.current.window.cursor[0]

        bookmark_path = util.input(self.vim, context, 'Bookmark Path: ',
                                   boofer)
        if not len(bookmark_path):
            bookmark_path = boofer

        bookmark_name = util.input(self.vim, context, 'Bookmark Name: ')
        if not len(bookmark_name):
            bookmark_name = ''
            return

        new_data = {
            'name': bookmark_name,
            'path': bookmark_path,
            'line': linenr,
            'col': 1,  # TODO: get column number when adding bookmarks
            'timestamp': str(datetime.datetime.now().isoformat()),
        }

        with open(data_file, 'r') as g:
            try:
                json_info = json.load(g)
            except json.JSONDecodeError:
                json_info = []
            json_info.append(new_data)

        with open(data_file, 'w') as f:
            json.dump(json_info, f, indent=2)
Example #3
0
    def get_code(self, context):
        code = util.input(self.vim, context, 'Stock code: ')
        suggest_url = 'http://smartbox.gtimg.cn/s3/?v=2&q=%s&t=all' % code
        r = context['http'].request('GET', suggest_url, timeout=3.0)
        c = r.data.decode('utf-8')
        items = re.search('"(.*)"', c).groups()[0].split('^')

        if len(items) == 1:
            info = items[0].split('~')
            context['stock_code'] = info[0] + info[1]

        prompt = ''
        if len(items) > 1:
            for i in range(0, len(items)):
                item = items[i]
                info = item.split('~')
                prompt += '%d: %s\n' % \
                        (i,
                        info[2].encode('utf-8').decode('unicode_escape') +
                        ' %s' % (info[0] + info[1]))

            stock_idx = util.input(self.vim, context,
                                   '\n' + prompt + 'Stock code index: ')
            context['stock_code'] = \
                    ''.join(items[int(stock_idx)].split('~')[:2])
Example #4
0
    def on_init(self, context):
        context['__proc'] = None

        # Backwards compatibility for `ack`
        if (self.vars['command'] and
                self.vars['command'][0] == 'ack' and
                self.vars['pattern_opt'] == ['-e']):
            self.vars['pattern_opt'] = ['--match']

        args = dict(enumerate(context['args']))

        # paths
        arg = args.get(0, [])
        if arg:
            if isinstance(arg, str):
                arg = [arg]
            elif not isinstance(arg, list):
                raise AttributeError('`args[0]` needs to be a `str` or `list`')
        elif context['path']:
            arg = [context['path']]
        context['__paths'] = [util.abspath(self.vim, x) for x in arg]

        # arguments
        arg = args.get(1, [])
        if arg:
            if isinstance(arg, str):
                if arg == '!':
                    arg = util.input(self.vim, context, 'Argument: ')
                arg = shlex.split(arg)
            elif not isinstance(arg, list):
                raise AttributeError('`args[1]` needs to be a `str` or `list`')
        context['__arguments'] = arg

        # patterns
        arg = args.get(2, [])
        if arg:
            if isinstance(arg, str):
                if arg == '!':
                    # Interactive mode
                    context['is_interactive'] = True
                    arg = ''
                else:
                    arg = [arg]
            elif not isinstance(arg, list):
                raise AttributeError('`args[2]` needs to be a `str` or `list`')
        elif context['input']:
            arg = [context['input']]
        else:
            pattern = util.input(self.vim, context, 'Pattern: ')
            if pattern:
                arg = [pattern]
        context['__patterns'] = arg
Example #5
0
 def action_edit_and_execute(self, context):
     target = context['targets'][0]
     command = util.input(self.vim, context,
                          "command > ",
                          target['action__command'],
                          'command')
     self._execute(command)
Example #6
0
    def action_delete(self, context):
        target = context['targets'][0]
        root = target['source__root']
        winnr = target['Source__winnr']
        gitdir = os.path.join(target['source__root'], '.git')

        preview_window = self.__get_preview_window()

        if preview_window:
            self.vim.command('pclose!')
            if self._previewed_target == target:
                return

        relpath = os.path.relpath(target['action__path'], root)
        prefix = ''
        if target['source__staged']:
            if target['source__tree']:
                if util.input(self.vim, context, 'Diff cached?[y/n]',
                              'y') == 'y':
                    prefix = '--cached '
            else:
                prefix = '--cached '
        prev_id = self.vim.call('win_getid')
        self.vim.command(str(winnr) + 'wincmd w')
        self.vim.call('denite#git#diffPreview', prefix, relpath, gitdir)

        self.vim.call('win_gotoid', prev_id)
        self._previewed_target = target
 def action_edit_and_execute(self, context):
     target = context['targets'][0]
     command = util.input(self.vim, context,
                          "command > ",
                          target['action__command'],
                          'command')
     self._execute(command)
Example #8
0
 def action_reset(self, context):
     cwd = os.path.normpath(self.vim.eval('expand("%:p:h")'))
     for target in context['targets']:
         filepath = target['action__path']
         root = target['source__root']
         path = os.path.relpath(filepath, root)
         if target['source__tree'] and target['source__staged']:
             res = util.input(self.vim, context,
                              'Select action reset or checkout [r/c]')
             if res == 'c':
                 args = 'git checkout -- ' + path
                 run_command(shlex.split(args), root)
             elif res == 'r':
                 args = 'git reset HEAD -- ' + path
                 run_command(shlex.split(args), root)
         elif target['source__tree']:
             args = 'git checkout -- ' + path
             run_command(shlex.split(args), root)
         elif target['source__staged']:
             args = 'git reset HEAD -- ' + path
             run_command(shlex.split(args), root)
         else:
             if self.remove == 'rm':
                 self.vim.command('Rm ' + os.path.relpath(filepath, cwd))
             elif self.remove == 'rmtrash':
                 run_command(['rmtrash', filepath], root)
             else:
                 self.vim.call('delete', filepath)
         self.vim.command('checktime')
Example #9
0
 def action_reset(self, context):
     cwd = os.path.normpath(self.vim.eval('expand("%:p:h")'))
     for target in context['targets']:
         filepath = target['action__path']
         root = target['source__root']
         path = os.path.relpath(filepath, root)
         if target['source__tree'] and target['source__staged']:
             res = util.input(self.vim, context, 'Select action reset or checkout [r/c]')
             if res == 'c':
                 args = 'git checkout -- ' + path
                 run_command(shlex.split(args), root)
             elif res == 'r':
                 args = 'git reset HEAD -- ' + path
                 run_command(shlex.split(args), root)
         elif target['source__tree']:
             args = 'git checkout -- ' + path
             run_command(shlex.split(args), root)
         elif target['source__staged']:
             args = 'git reset HEAD -- ' + path
             run_command(shlex.split(args), root)
         else:
             if self.remove == 'rm':
                 self.vim.command('Rm ' + os.path.relpath(filepath, cwd))
             elif self.remove == 'rmtrash':
                 run_command(['rmtrash', filepath], root)
             else:
                 self.vim.call('delete', filepath)
         self.vim.command('checktime')
Example #10
0
 def action_apply(self, context):
     target = context['targets'][0]
     confirm = util.input(self.vim, context, 'Apply stash {}? [y/n]: '.format(target['stash_ref']), 'n') == 'y'
     if confirm:
         runProcess(['git', 'stash', 'apply', target['stash_ref']])
     else:
         self.vim.out_write('{} \n'.format(confirm))
Example #11
0
 def action_delete(self, context):
     for target in context['targets']:
         c = util.input(self.vim, context,
                        'Delete source %s ?' % (target['action__path']),
                        'y')
         if c == 'y':
             self.vim.call('delete', target['action__path'])
 def action_edit_and_execute(self, context):
     target = context['targets'][0]
     edited = util.input(self.vim, context,
                         "command > ",
                         target['action__command'],
                         'command')
     if edited:
         self.vim.call('denite#util#execute_command', edited)
Example #13
0
 def action_edit(self, context):
     target = context['targets'][0]
     command = util.input(self.vim, context,
                          "command > ",
                          target['action__command'],
                          'command')
     self._execute(context, command,
                   target.get('action__is_pause', False))
Example #14
0
    def gather_candidates(self, context):
        if len(context["args"]) < 1:
            arg = util.input(self.vim, context, "FASD string: ")
        else:
            arg = context["args"][0]

        sub = subprocess.Popen(["fasd", "-f", "-l", "-R", arg], stdout=subprocess.PIPE)
        return [{"word": x, "action__path": x} for x in sub.communicate()[0].decode("utf-8").split()]
Example #15
0
 def action_apply(self, context):
     target = context['targets'][0]
     confirm = util.input(
         self.vim, context,
         'Apply stash {}? [y/n]: '.format(target['stash_ref']), 'n') == 'y'
     if confirm:
         runProcess(['git', 'stash', 'apply', target['stash_ref']])
     else:
         self.vim.out_write('{} \n'.format(confirm))
Example #16
0
 def action_new(self, context):
     path = util.input(self.vim, context, 'New file: ', completion='file')
     if not path:
         return
     context['targets'] = [{
         'word': path,
         'action__path': util.abspath(self.vim, path),
     }]
     self.action_open(context)
Example #17
0
 def action_doaction(self, context):
     target = context['targets'][0]
     action = target['source__action']
     arg_type = target['source__arg_type']
     arg = ''
     if arg_type is 'yes':
         prompt = target['word'].split(' ')[1]
         arg = util.input(self.vim, context, 'Enter args %s: ' % prompt)
     self.vim.call('cocActionSource#call', action, arg)
Example #18
0
 def action_new(self, context):
     path = util.input(self.vim, context, 'New file: ', completion='file')
     if not path:
         return
     context['targets'] = [{
         'word': path,
         'action__path': util.abspath(self.vim, path),
     }]
     self.action_open(context)
Example #19
0
 def action_edit_title(self, context, conn):
     cursor = conn.cursor()
     target = context['targets'][0]
     title = util.input(self.vim, context, 'Change to: ',
                        target['source__title'])
     if not len(title):
         return
     category = util.input(self.vim, context, 'Enter category: ', '',
                           'custom,buzuo#add_category_candidate')
     if not len(category):
         category = target['source__category']
     the_type = util.input(self.vim, context, 'Enter type: ', '',
                           'custom,buzuo#add_type_candidate')
     if not len(the_type):
         the_type = target['source__type']
     cursor.execute(
         'UPDATE buzuo SET title = ?, category = ?, type = ? WHERE id = ?',
         (title, category, the_type, target['source__id']))
     conn.commit()
Example #20
0
 def action_append(self, context):
     target = context['targets'][0]
     gitignore = os.path.join(self.vim.call('getcwd'), '.gitignore')
     if os.path.isfile(gitignore):
         result = util.input(
                 self.vim, context, '%s exists! (append? Yes/No): ' % gitignore, '')
     else:
         result = util.input(
                 self.vim, context, 'create %s ? Yes/No: ' % gitignore, 'yes')
     if re.match('^yes$', result, re.I):
         templates = target['source__paths']
         content = '\n# create by https://github.com/iamcco/gitignore.vim'
         content += '\n# gitignore templates from https://github.com/dvcs/gitignore\n'
         for p in templates:
             content += '\n### %s ###\n' % os.path.split(p)[-1]
             content += open(p, 'r').read()
         f = open(gitignore, 'a')
         f.write(content)
         f.close()
Example #21
0
 def action_add(self, context, conn):
     title = util.input(self.vim, context, 'Enter title: ')
     if not len(title):
         return
     category = util.input(self.vim, context, 'Enter category: ', '',
                           'custom,buzuo#add_category_candidate')
     if not len(category):
         category = self.vim.eval('g:buzuo_category_default')
     the_type = util.input(self.vim, context, 'Enter type: ', '',
                           'custom,buzuo#add_type_candidate')
     if not len(the_type):
         the_type = self.vim.eval('g:buzuo_type_default')
     cursor = conn.cursor()
     time_now = int(time.time())
     cursor.execute(
         'INSERT INTO buzuo \
             (create_time, modify_time, status, category, type, title) \
             VALUES (?,?,?,?,?,?)',
         (time_now, time_now, 'pending', category, the_type, title))
     conn.commit()
Example #22
0
 def _init_arguments(self, context, args):
     arguments = []
     arg = args.get(1, [])
     if arg:
         if isinstance(arg, str):
             if arg == '!':
                 arg = util.input(self.vim, context, 'Argument: ')
             arguments = shlex.split(arg)
         elif not isinstance(arg, list):
             raise AttributeError('`args[1]` needs to be a `str` or `list`')
     return arguments
Example #23
0
 def _detect_github_user(self, args):
     arg = args.get(0)
     if arg:
         user_name = arg
     else:
         u = self.vim.call('denite_gists#util#github_user')
         if u:
             user_name = u
         else:
             user_name = util.input(self.vim, context, 'Gist User: ')
     return user_name
Example #24
0
 def action_add(self, context):
     conn = context['targets'][0]['source__conn']
     content = util.input(self.vim, context, 'Add: ')
     if not len(content):
         return
     c = conn.cursor()
     now = int(time.time())
     c.execute(
         'INSERT INTO todo (created, modified, status, content) VALUES (?,?,?,?)',
         (now, now, 'pending', content))
     conn.commit()
Example #25
0
 def action_edit(self, context):
     conn = context['targets'][0]['source__conn']
     c = conn.cursor()
     target = context['targets'][0]
     content = util.input(self.vim, context, 'Change to:',
                          target['source__content'])
     if not len(content):
         return
     c.execute('UPDATE todo SET content = ? WHERE id = ?',
               (content, target['source__id']))
     conn.commit()
Example #26
0
 def _init_arguments(self, context, args):
     arguments = []
     arg = args.get(1, [])
     if arg:
         if isinstance(arg, str):
             if arg == '!':
                 arg = util.input(self.vim, context, 'Argument: ')
             arguments = shlex.split(arg)
         elif not isinstance(arg, list):
             raise AttributeError(
                 '`args[1]` needs to be a `str` or `list`')
     return arguments
Example #27
0
    def action_delete(self, context):
        target = context['targets'][0]
        args = []
        root = target['source__root']
        branch = target['source__branch']

        if target['source__remote']:
            branchname = branch.split('/')[-1]
            confirm = util.input(
                    self.vim, context, 'Delete remote branch '
                    + branchname + '? [y/n] : ', 'n') == 'y'
            if confirm:
                args = ['git', 'push', 'origin', '--delete', branchname]
        else:
            force = util.input(
                    self.vim, context, 'Force delete? [y/n] : ', 'n') == 'y'
            args = ['git', 'branch', '-D' if force else '-d', branch]

        if len(args) > 0:
            run_command(args, root, self.vim)
            self.vim.command('bufdo e')
Example #28
0
 def action_delete(self, context):
     target = context['targets'][0]
     root = target['source__root']
     relpath = os.path.relpath(target['action__path'], root)
     prefix = ''
     if target['source__staged']:
         if target['source__tree']:
             if util.input(self.vim, context, 'Diff cached?[y/n]',
                           'y') == 'y':
                 prefix = '--cached '
         else:
             prefix = '--cached '
     self.vim.call('easygit#diffShow', prefix + relpath, 'bot split')
Example #29
0
def _choose_action(denite: Default, params: Params) -> typing.Any:
    candidates = denite._get_selected_candidates()
    if not candidates or not denite._denite:
        return

    action_names = denite._denite.get_action_names(denite._context, candidates)
    denite._vim.vars['denite#_actions'] = action_names
    clear_cmdline(denite._vim)
    action = input(denite._vim, denite._context, 'Action: ', '',
                   'customlist,denite#helper#complete_actions')
    if action == '':
        return
    return denite.do_action(action, is_manual=True)
Example #30
0
 def action_reset(self, context):
     target = context['targets'][0]
     commit = target['source__commit']
     c = util.input(self.vim, context, 'Reset mode mixed|soft|hard [m/s/h]: ')
     opt = ''
     if c == 'm':
         opt = '--mixed'
     elif c == 's':
         opt = '--soft'
     elif c == 'h':
         opt = '--hard'
     else:
         return
     self.vim.call('easygit#reset', opt + ' ' + commit)
Example #31
0
 def _init_arguments(self, context: UserContext,
                     args: typing.Dict[int, str]) -> typing.List[str]:
     arguments: typing.List[str] = []
     arg: typing.Union[str, typing.List[str]] = args.get(1, [])
     if arg:
         if isinstance(arg, str):
             if arg == '!':
                 arg = util.input(self.vim, context, 'Argument: ')
             arguments = shlex.split(arg)
         elif isinstance(arg, list):
             arguments = arg[:]
         else:
             raise AttributeError('`args[1]` needs to be a `str` or `list`')
     return arguments
Example #32
0
 def action_reset(self, context):
     target = context['targets'][0]
     commit = target['source__commit']
     c = util.input(self.vim, context, 'Reset mode mixed|soft|hard [m/s/h]: ')
     opt = ''
     if c == 'm':
         opt = '--mixed'
     elif c == 's':
         opt = '--soft'
     elif c == 'h':
         opt = '--hard'
     else:
         return
     self.vim.call('easygit#reset', opt + ' ' + commit)
Example #33
0
 def action_switch_type(self, context):
     target = context['targets'][0]
     the_type = util.input(self.vim, context, 'Enter type: ', '',
                           'custom,buzuo#add_type_candidate')
     if not len(the_type):
         return
     args = target['source__args'].split(':')
     category = args[0]
     status = args[2]
     context['sources_queue'].append([
         {
             'name': 'buzuo',
             'args': [category, the_type, status]
         },
     ])
Example #34
0
    def action_commit(self, context):
        root = context['targets'][0]['source__root']
        message = util.input(self.vim, context, 'Commit message: ')
        args = ['-v', '-m', message]

        if self.vim.call('exists', ':Gcommit'):
            self.vim.command('Gcommit ' + ' '.join(args))
            return

        for target in context['targets']:
            filepath = target['action__path']
            path = os.path.relpath(filepath, root)
            args.append(path)

        self.vim.call('easygit#commit', ' '.join(args))
Example #35
0
 def _init_patterns(self, context, args):
     patterns = []
     arg = args.get(2, [])
     if arg:
         if isinstance(arg, str):
             if arg == '!':
                 # Interactive mode
                 context['is_interactive'] = True
                 patterns = [context['input']]
             else:
                 patterns = [arg]
         elif not isinstance(arg, list):
             raise AttributeError('`args[2]` needs to be a `str` or `list`')
     elif context['input']:
         patterns = [context['input']]
     else:
         patterns = [util.input(self.vim, context, 'Pattern: ')]
     return [x for x in patterns if x]
Example #36
0
    def on_init(self, context):
        context["__proc"] = None
        context["__query"] = context["input"] if "input" in context else ""

        args = context["args"]
        args.reverse()

        input_arg = None
        if args:
            input_arg = args.pop()
            if input_arg == "!":
                context["is_interactive"] = True
                context["__query"] = context["input"]
            else:
                context["__query"] = input_arg
        elif context["input"]:
            context["__query"] = context["input"]
        else:
            context["__query"] = util.input(self.vim, context, "Query: ")
Example #37
0
    def action_delete(self, context):
        target = context['targets'][0]
        args = []
        root = target['source__root']
        path = target['action__path']

        force = util.input(self.vim, context, 'Force delete? [y/n] : ',
                           'n') == 'y'

        if target['source__remote']:
            if force == True:
                args['git', 'push', 'origin', ':' + target['action__path'][8:]]
        else:
            args = [
                'git', 'branch', '-D' if force == True else '-d',
                target['action__path']
            ]

        if len(args) > 0: run_command(args, root)
Example #38
0
 def _init_patterns(self, context, args):
     patterns = []
     arg = args.get(2, [])
     if arg:
         if isinstance(arg, str):
             if arg == '!':
                 # Interactive mode
                 context['is_interactive'] = True
                 patterns = [context['input']]
             else:
                 patterns = [arg]
         elif not isinstance(arg, list):
             raise AttributeError(
                 '`args[2]` needs to be a `str` or `list`')
     elif context['input']:
         patterns = [context['input']]
     else:
         patterns = [util.input(self.vim, context, 'Pattern: ')]
     return [x for x in patterns if x]
Example #39
0
    def on_init(self, context):
        context["__proc"] = None

        # Backwards compatibility for `ack`
        if len(self.vars["command"]) >= 1 and self.vars["command"][0] == "ack" and self.vars["pattern_opt"] == ["-e"]:
            self.vars["pattern_opt"] = ["--match"]

        args = dict(enumerate(context["args"]))

        # paths
        arg = args.get(0, [])
        if arg:
            if isinstance(arg, str):
                arg = [self.vim.call("expand", arg)]
            elif not isinstance(arg, list):
                raise AttributeError("`args[0]` needs to be a `str` or `list`")
        # Windows needs to specify the directory.
        elif context["is_windows"]:
            arg = [context["path"]]
        context["__paths"] = arg

        # arguments
        arg = args.get(1, [])
        if arg:
            if isinstance(arg, str):
                arg = shlex.split(arg)
            elif not isinstance(arg, list):
                raise AttributeError("`args[1]` needs to be a `str` or `list`")
        context["__arguments"] = arg

        # patterns
        arg = args.get(2, [])
        if arg:
            if isinstance(arg, str):
                arg = [arg]
            elif not isinstance(arg, list):
                raise AttributeError("`args[2]` needs to be a `str` or `list`")
        else:
            pattern = util.input(self.vim, context, "Pattern: ")
            if pattern:
                arg = [pattern]
        context["__patterns"] = arg
Example #40
0
    def action_delete(self, context):
        target = context['targets'][0]
        root = target['source__root']

        preview_window = self.__get_preview_window()
        if (preview_window and self._previewed_target == target):
            self.vim.command('pclose!')
        else:
            relpath = os.path.relpath(target['action__path'], root)
            prefix = ''
            if target['source__staged']:
                if target['source__tree']:
                    if util.input(self.vim, context, 'Diff cached?[y/n]', 'y') == 'y':
                        prefix = '--cached '
                else:
                    prefix = '--cached '
            prev_id = self.vim.call('win_getid')
            self.vim.call('easygit#diffPreview', prefix + relpath)

            self.vim.call('win_gotoid', prev_id)
            self._previewed_target = target