completion for file command
969030
def complete_visualize(self, text, line, begidx, endidx):
        """"""

        opts = self.VISUALIZE_OPTS

        if not text:
            completions = opts
        else:
            completions = [f
                           for f in opts
                           if f.startswith(text)
                           ]
        return completions
396588
void complete()
    {
        _file=_stack[_top].getFileName()+":"+_stack[_top].getLineNumber();
        _method=_stack[_top].getClassName()+"."+_stack[_top].getMethodName();
        _depth=_stack.length-_top;
        _thread = Thread.currentThread().getName();
    }
848728
def postprocess(self):
        
        # Add suffix to all sub_dir/{items}
        for path in self.neb_dirs:
            for f in VASP_NEB_OUTPUT_SUB_FILES:
                f = os.path.join(path, f)
                if os.path.exists(f):
                    if self.final and self.suffix != "":
                        shutil.move(f, "{}{}".format(f, self.suffix))
                    elif self.suffix != "":
                        shutil.copy(f, "{}{}".format(f, self.suffix))

        # Add suffix to all output files
        for f in VASP_NEB_OUTPUT_FILES + [self.output_file]:
            if os.path.exists(f):
                if self.final and self.suffix != "":
                    shutil.move(f, "{}{}".format(f, self.suffix))
                elif self.suffix != "":
                    shutil.copy(f, "{}{}".format(f, self.suffix))
805077
def complete_command_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]:
        """"""
        for idx, token in enumerate(tokens):
            if idx >= self._token_start_index:
                if self._positional_completers:
                    # For now argparse only allows 1 sub-command group per level
                    # so this will only loop once.
                    for completers in self._positional_completers.values():
                        if token in completers:
                            return completers[token].complete_command_help(tokens, text, line, begidx, endidx)
                        else:
                            return self._cmd2_app.basic_complete(text, line, begidx, endidx, completers.keys())
        return []
45244
def files(input)
      (::Readline::FILENAME_COMPLETION_PROC.call(input) || []).map {|f|
        f =~ /^~/ ?  File.expand_path(f) : f
      }
    end
983986
@Override
    public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {
        if(!ctx.isDomainMode()) {
            return -1;
        }
        if(buffer.isEmpty()) {
            candidates.add("{rollout");
            return 0;
        }

        try {
            parsedOp.parseOperation(null, buffer, ctx);
        } catch (CommandFormatException e) {
            return -1;
        }
        if(parsedOp.isRequestComplete()) {
            return -1;
        }

        if(parsedOp.endsOnHeaderListStart() || parsedOp.endsOnHeaderSeparator()) {
            candidates.add("rollout");
            return parsedOp.getLastSeparatorIndex() + 1;
        }
        if(parsedOp.getLastHeader() == null) {
            if(ctx.getParsedCommandLine().getOriginalLine().endsWith(" ") /* '{rollout ' */) {
                final String originalLine = ctx.getParsedCommandLine().getOriginalLine();
                int bufferIndex = originalLine.lastIndexOf(buffer);
                if(bufferIndex == -1) { // that's illegal state
                    return -1;
                }
                candidates.add("name=");
                candidates.addAll(Util.getServerGroups(ctx.getModelControllerClient()));
                return originalLine.length() - bufferIndex;
            } else if (ctx.getParsedCommandLine().getOriginalLine().endsWith("rollout")) {
                // In order to have the completion to be allowed to continue
                candidates.add(" ");
            }
            return buffer.length();
        }
        final ParsedOperationRequestHeader lastHeader = parsedOp.getLastHeader();
        if(!(lastHeader instanceof ParsedRolloutPlanHeader)) {
            throw new IllegalStateException("Expected " + ParsedRolloutPlanHeader.class + " but got " + lastHeader.getName() + " of " + lastHeader);
        }
        final ParsedRolloutPlanHeader rollout = (ParsedRolloutPlanHeader) lastHeader;

        if(rollout.endsOnPlanIdValueSeparator()) {
            candidates.addAll(Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN));
            return rollout.getLastSeparatorIndex() + 1;
        }

        final String planRef = rollout.getPlanRef();
        if(planRef != null) {
            final List<String> nodeNames = Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN);
            for(String name : nodeNames) {
                if(name.startsWith(planRef)) {
                    candidates.add(name);
                }
            }
            return rollout.getLastChunkIndex();
        }

        if(rollout.hasProperties()) {
            final String lastName = rollout.getLastPropertyName();
            if (Util.ROLLBACK_ACROSS_GROUPS.equals(lastName)) {
                if (rollout.getLastPropertyValue() != null) {
                    return -1;
                }
                candidates.add("}");
                candidates.add(";");
                return rollout.getLastChunkIndex() + lastName.length();
            }
            if (Util.ROLLBACK_ACROSS_GROUPS.startsWith(lastName)) {
                candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
            }
            return rollout.getLastChunkIndex();
        }

        final List<String> serverGroups = Util.getServerGroups(ctx.getModelControllerClient());
        boolean containsAllGroups = true;
        for (String group : serverGroups) {
            if (!rollout.containsGroup(group)) {
                containsAllGroups = false;
                break;
            }
        }

        if(rollout.endsOnGroupSeparator()) {
            if (containsAllGroups) {
                return -1;
            }
            for(String group : serverGroups) {
                if(!rollout.containsGroup(group)) {
                    candidates.add(group);
                }
            }
            return buffer.length();
        }

        final SingleRolloutPlanGroup lastGroup = rollout.getLastGroup();
        if(lastGroup == null) {
            return -1;
        }

        if (lastGroup.endsOnPropertyListEnd()) {
            if (!containsAllGroups) {
                candidates.add("^");
                candidates.add(",");
            } else if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
                candidates.add(Util.ROLLBACK_ACROSS_GROUPS);

            } else {
                candidates.add(" ");
            }
            return buffer.length();
        }

        if(lastGroup.endsOnPropertyListStart()) {
            candidates.add(Util.MAX_FAILED_SERVERS);
            candidates.add(Util.MAX_FAILURE_PERCENTAGE);
            candidates.add(Util.ROLLING_TO_SERVERS);
            candidates.add(Util.NOT_OPERATOR);
            return buffer.length();
        }

        // Only return the set of boolean properties
        if (lastGroup.endsOnNotOperator()) {
            candidates.add(Util.ROLLING_TO_SERVERS);
            return buffer.length();
        }

        if (lastGroup.hasProperties()) {
            // To propose the right end character
            boolean containsAll = lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)
                    && lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)
                    && lastGroup.hasProperty(Util.ROLLING_TO_SERVERS);

            final String propValue = lastGroup.getLastPropertyValue();
            if(propValue != null) {
                if(Util.TRUE.startsWith(propValue)) {
                    candidates.add(Util.TRUE);
                } else if(Util.FALSE.startsWith(propValue)) {
                    candidates.add(Util.FALSE);
                } else {
                    candidates.add(containsAll ? ")" : ",");
                    return buffer.length();
                }
            } else if(lastGroup.endsOnPropertyValueSeparator()) {
                if(Util.ROLLING_TO_SERVERS.equals(lastGroup.getLastPropertyName())) {
                    candidates.add(Util.FALSE);
                    candidates.add(containsAll ? ")" : ",");
                }
                return buffer.length();
            } else if(lastGroup.endsOnPropertySeparator()) {
                if(!lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)) {
                    candidates.add(Util.MAX_FAILED_SERVERS);
                }
                if(!lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)) {
                    candidates.add(Util.MAX_FAILURE_PERCENTAGE);
                }
                if(!lastGroup.hasProperty(Util.ROLLING_TO_SERVERS)) {
                    candidates.add(Util.ROLLING_TO_SERVERS);
                    candidates.add(Util.NOT_OPERATOR);
                }
                return lastGroup.getLastSeparatorIndex() + 1;
            } else {
                final String propName = lastGroup.getLastPropertyName();
                if(Util.MAX_FAILED_SERVERS.startsWith(propName)) {
                    candidates.add(Util.MAX_FAILED_SERVERS + '=');
                }
                if(Util.MAX_FAILURE_PERCENTAGE.startsWith(propName)) {
                    candidates.add(Util.MAX_FAILURE_PERCENTAGE + '=');
                } else if (Util.ROLLING_TO_SERVERS.equals(propName)) {
                    if (lastGroup.isLastPropertyNegated() && !containsAll) {
                        candidates.add(Util.ROLLING_TO_SERVERS + ",");
                    } else {
                        candidates.add("=" + Util.FALSE);
                        if (!containsAll) {
                            candidates.add(",");
                        } else {
                            candidates.add(")");
                        }
                    }

                } else if (Util.ROLLING_TO_SERVERS.startsWith(propName)) {
                    candidates.add(Util.ROLLING_TO_SERVERS);
                }
            }
            if (candidates.isEmpty() && containsAll) {
                candidates.add(")");
            }
            return lastGroup.getLastChunkIndex();
        }

        if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
            candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
            return buffer.length();
        }

        int result = lastGroup.getLastChunkIndex();

        final String groupName = lastGroup.getGroupName();

        boolean isLastGroup = false;
        for (String group : serverGroups) {
            if (group.equals(groupName)) {
                isLastGroup = true;
            }
            if (!isLastGroup && group.startsWith(groupName)) {
                candidates.add(group);
            }
        }

        if(Util.NAME.startsWith(groupName)) {
            candidates.add("name=");
        } else {
            if (candidates.isEmpty()) {
                if (isLastGroup) {
                    candidates.add("(");
                    if (containsAllGroups) {
                        candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
                    } else {
                        candidates.add(",");
                        candidates.add("^");
                    }
                }
            }
        }

        return result;
    }
950509
function (args, callback) {
        if (ternserver) {
          ternserver.request({
              query: {
                type: "completions",  //$NON-NLS-1$
                file: args.meta.location,
                types: true,
                origins: true,
                urls: true,
                docs: true,
                end: args.params.offset,
                sort: true,
                filter: false,
                ecma: args.params.ecma,
                expandWordForward: false,
                omitObjectPrototype: false,
                includeKeywords: args.params.keywords,
                includeTemplates: args.params.template,
                caseInsensitive: true,
                docFormat: "full" //$NON-NLS-1$
              },
              files: args.files
            },
            function (error, comps) {
              if (error) {
                callback({
                  request: 'completions',
                  proposals: [],
                  error: error.message,
                  message: Messages['failedToComputeProposals']
                }); //$NON-NLS-1$
              } else if (comps && comps.completions) {
                callback({request: 'completions', proposals: comps.completions}); //$NON-NLS-1$
              } else {
                callback({request: 'completions', proposals: []}); //$NON-NLS-1$
              }
            });

        } else {
          callback({request: 'completions', message: Messages['failedToComputeProposalsNoServer']}); //$NON-NLS-1$
        }
      }
137257
def completedefault(self, text, line, begidx, endidx):
        """"""
        if self.argparser_completer and any((line.startswith(x) for x in self.argparse_names())):
            self.argparser_completer.rl_complete(line, 0)
            return [x[begidx:] for x in self.argparser_completer._rl_matches]
        else:
            return []
158641
def full_command(filename)
      include_args = include_path.map { |path| "-I#{path}" }
      macro_args = macros.sort.map { |key, val| "-D#{key}" + (val ? "=#{val}" : '') }
      [*Preprocessor.command.shellsplit, *include_args, *macro_args, filename].shelljoin
    end
627451
def autocomplete():
    
    # Don't complete if user hasn't sourced bash_completion file.
    if 'PIP_AUTO_COMPLETE' not in os.environ:
        return
    cwords = os.environ['COMP_WORDS'].split()[1:]
    cword = int(os.environ['COMP_CWORD'])
    try:
        current = cwords[cword-1]
    except IndexError:
        current = ''
    load_all_commands()
    subcommands = [cmd for cmd, cls in command_dict.items() if not cls.hidden]
    options = []
    # subcommand
    try:
        subcommand_name = [w for w in cwords if w in subcommands][0]
    except IndexError:
        subcommand_name = None
    # subcommand options
    if subcommand_name:
        # special case: 'help' subcommand has no options
        if subcommand_name == 'help':
            sys.exit(1)
        # special case: list locally installed dists for uninstall command
        if subcommand_name == 'uninstall' and not current.startswith('-'):
            installed = []
            lc = current.lower()
            for dist in get_installed_distributions(local_only=True):
                if dist.key.startswith(lc) and dist.key not in cwords[1:]:
                    installed.append(dist.key)
            # if there are no dists installed, fall back to option completion
            if installed:
                for dist in installed:
                    print(dist)
                sys.exit(1)
        subcommand = command_dict.get(subcommand_name)
        options += [(opt.get_opt_string(), opt.nargs)
                    for opt in subcommand.parser.option_list
                    if opt.help != optparse.SUPPRESS_HELP]
        # filter out previously specified options from available options
        prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]]
        options = [(x, v) for (x, v) in options if x not in prev_opts]
        # filter options by current input
        options = [(k, v) for k, v in options if k.startswith(current)]
        for option in options:
            opt_label = option[0]
            # append '=' to options which require args
            if option[1]:
                opt_label += '='
            print(opt_label)
    else:
        # show options of main parser only when necessary
        if current.startswith('-') or current.startswith('--'):
            subcommands += [opt.get_opt_string()
                            for opt in parser.option_list
                            if opt.help != optparse.SUPPRESS_HELP]
        print(' '.join([x for x in subcommands if x.startswith(current)]))
    sys.exit(1)
760544
def directory_complete(self, text, line, begidx, endidx):
        """"""
        return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/']
470563
def _autocomplete(ctx, shell):
    """"""
    if not shell:
        shell = os.environ.get("SHELL", "")
        shell = os.path.basename(shell).lower()
    if not shell:
        click.secho(
            "Your shell could not be detected, please pass its name "
            "as the argument.",
            fg="red",
        )
        ctx.exit(-1)

    base = os.path.abspath(os.path.dirname(__file__))
    autocomplete = os.path.join(base, "autocomplete", "{}.sh".format(shell))

    if not os.path.exists(autocomplete):
        click.secho(
            "Autocompletion for your shell ({}) is currently not "
            "supported.",
            fg="red",
        )
        ctx.exit(-1)

    with open(autocomplete) as fh:
        click.echo(fh.read())
133789
def generate_completions(event):
    
    """
    b = event.current_buffer

    # When already navigating through completions, select the next one.
    if b.complete_state:
        b.complete_next()
    else:
        event.cli.start_completion(insert_common_part=True, select_first=False)
1125445
def _auto_complete_filename(self, location):
        
        path = formatted(location, self)
        if path:
            if os.path.isdir(path):
                filename = formatted(self.basename, self)
                if not filename:
                    return None
                path = os.path.join(path, filename)
            if path and ensure_folder(path, fatal=False, logger=LOG.debug, dryrun=False) >= 0:
                return path
267187
def autocomplete(self, line):
        """"""
        current_length = len(line)
        self._current_line = line
        if current_length == 1 and self._last_position > 1:
            # Reset state.  This is likely from a user completing
            # a previous command.
            self.reset()
        elif current_length < self._last_position:
            # The user has hit backspace.  We'll need to check
            # the current words.
            return self._handle_backspace()
        elif not line:
            return []
        elif current_length != self._last_position + 1:
            return self._complete_from_full_parse()

        # This position is important.  We only update the _last_position
        # after we've checked the special cases above where that value
        # matters.
        self._last_position = len(line)
        if line and not line.strip():
            # Special case, the user hits a space on a new line so
            # we autocomplete all the top level commands.
            return self._current['commands']

        last_word = line.split()[-1]
        if last_word in self.arg_metadata or last_word in self._global_options:
            # The last thing we completed was an argument, record
            # this as self.last_arg
            self.last_option = last_word
        if line[-1] == ' ':
            # At this point the user has autocompleted a command
            # or an argument and has hit space.  If they've
            # just completed a command, we need to change the
            # current context and traverse into the subcommand.
            # "ec2 "
            #      ^--here, need to traverse into "ec2"
            #
            # Otherwise:
            # "ec2 --no-validate-ssl "
            #                        ^-- here, stay on "ec2" context.
            if not last_word.startswith('-'):
                next_command = self._current['children'].get(last_word)
                if next_command is not None:
                    self._current = next_command
                    self._current_name = last_word
                    self.cmd_path.append(self._current_name)
            elif last_word in self.arg_metadata and \
                    self.arg_metadata[last_word]['example']:
                # Then this is an arg with a shorthand example so we'll
                # suggest that example.
                return [self.arg_metadata[last_word]['example']]
            # Even if we don't change context, we still want to
            # autocomplete all the commands for the current context
            # in either of the above two cases.
            return self._current['commands'][:]
        elif last_word.startswith('-'):
            # TODO: cache this for the duration of the current context.
            # We don't need to recompute this until the args are
            # different.
            all_args = self._get_all_args()
            if self.match_fuzzy:
                return fuzzy_search(last_word, all_args)
            else:
                return substring_search(last_word, all_args)
        if self.match_fuzzy:
            return fuzzy_search(last_word, self._current['commands'])
        else:
            return substring_search(last_word, self._current['commands'])
354144
private synchronized void complete(String message) {
    
    // This is a weird problem with writing stuff while idling. Need to investigate it more, but
    // for now just ignore it.
    if (MESSAGE_COULDNT_BE_FETCHED_REGEX.matcher(message).matches()) {
      log.warn("Some messages in the batch could not be fetched for {}\n" +
          "---cmd---\n{}\n---wire---\n{}\n---end---\n", new Object[] {
          config.getUsername(),
          getCommandTrace(),
          getWireTrace()
      });
      errorStack.push(new Error(completions.peek(), message, wireTrace.list()));
      final CommandCompletion completion = completions.peek();
      String errorMsg = "Some messages in the batch could not be fetched for user " + config.getUsername();
      RuntimeException ex = new RuntimeException(errorMsg);
      if (completion != null) {
        completion.error(errorMsg, new MailHandlingException(getWireTrace(), errorMsg, ex));
        completions.poll();
      } else {
        throw ex;
      }
    }

    CommandCompletion completion = completions.peek();
    if (completion == null) {
      if ("+ idling".equalsIgnoreCase(message)) {
        synchronized (idleMutex) {
          idler.idleStart();
          log.trace("IDLE entered.");
          idleAcknowledged.set(true);
        }
      } else {
        log.error("Could not find the completion for message {} (Was it ever issued?)", message);
        errorStack.push(new Error(null, "No completion found!", wireTrace.list()));
      }
      return;
    }
    
    if (completion.complete(message)) {
      completions.poll();
    }
  }
1341920
def install_completion(
        shell: arg(choices=('bash', 'fish'), help='Shell to install completion for'),
        to: arg(help='~/.bashrc.d/runcommands.rc or ~/.config/fish/runcommands.fish') = None,
        overwrite: 'Overwrite if exists' = False):
    
    if shell == 'bash':
        source = 'runcommands:completion/bash/runcommands.rc'
        to = to or '~/.bashrc.d'
    elif shell == 'fish':
        source = 'runcommands:completion/fish/runcommands.fish'
        to = to or '~/.config/fish/runcommands.fish'

    source = asset_path(source)
    destination = os.path.expanduser(to)

    if os.path.isdir(destination):
        destination = os.path.join(destination, os.path.basename(source))

    printer.info('Installing', shell, 'completion script to:\n    ', destination)

    if os.path.exists(destination):
        if overwrite:
            printer.info('Overwriting:\n    {destination}'.format_map(locals()))
        else:
            message = 'File exists. Overwrite?'.format_map(locals())
            overwrite = confirm(message, abort_on_unconfirmed=True)

    copy_file(source, destination)
    printer.info('Installed; remember to:\n    source {destination}'.format_map(locals()))