This is the main completion function.
    Inputs:
    - completed_args: a list of already-completed arguments
    - cur: the current "word in progress" or None
    - quoted: is cur part of a quoted string?
171195
def get_all_choices(completed_args, cur, quoted):
    
    ctx = get_completion_context(completed_args)
    if not ctx:
        return []

    # matching rules, so we can toggle by type and such
    def match_with_case(n, m):
        """case matters"""
        return n.startswith(m)

    def match_nocase(n, m):
        """case doesn't matter"""
        return n.lower().startswith(m.lower())

    match_func = match_with_case

    ctx_options = [
        p for p in ctx.command.get_params(ctx) if isinstance(p, click.Option)
    ]

    last_completed = None
    if completed_args:
        last_completed = completed_args[-1]

    # if the last completed argument matches a Choice option, we're going to
    # have to expand cur as a choice param
    matching_choice_opt = None
    for p in ctx_options:
        if isinstance(p.type, click.Choice) and last_completed in p.opts:
            matching_choice_opt = p

    choices = []
    # if we ended on a choice, complete with all of the available values
    if matching_choice_opt:
        # catch the case where it's case insensitive, and we need to change our
        # comparisons / matching later on
        if isinstance(matching_choice_opt.type, CaseInsensitiveChoice):
            match_func = match_nocase
        choices = [
            (x, matching_choice_opt.help) for x in matching_choice_opt.type.choices
        ]
    # if cur looks like an option, just look for options
    # but skip if it's quoted text
    elif cur and cur.startswith("-") and not quoted:
        for param in ctx_options:
            # skip hidden options
            if isinstance(param, HiddenOption):
                continue
            for optset in (param.opts, param.secondary_opts):
                for opt in optset:
                    # only add long-opts, never short opts to completion,
                    # unless the cur appears to be a short opt already
                    if opt.startswith("--") or (len(cur) > 1 and cur[1] != "-"):
                        choices.append((opt, param.help))
    # and if it's a multicommand we see, get the list of subcommands
    elif isinstance(ctx.command, click.MultiCommand) and not quoted:
        choices = [
            (cmdname, ctx.command.get_command(ctx, cmdname).short_help)
            for cmdname in ctx.command.list_commands(ctx)
        ]
    else:
        pass

    # now, do final filtering
    if cur:
        choices = [(n, h) for (n, h) in choices if match_func(n, cur)]

    return choices
20618
def option_completer(cls, k,v):
        ""
        line = v.text_until_cursor
        completions = cls.setup_completer()
        compositor_defs = {el.group:el.output_type.__name__
                           for el in Compositor.definitions if el.group}
        return cls.line_completer(line, completions, compositor_defs)
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$
        }
      }
703192
function _parseForAutocomplete(fullCommandStr) {
    var fullCommandParsed = CommandParser.parse(fullCommandStr);
    var lastArg = _.last(fullCommandParsed.args);

    // If the last argument does not have an index, it means it's a cliff hanger (e.g., a space at
    // the end of the command string). Therefore, we'll assign it an index at the end of the input
    // string
    if (!_.isNumber(lastArg.i)) {
        lastArg.i = fullCommandStr.length;
    }

    return fullCommandParsed;
}
663870
def autocomplete(self):
        
        if self.completion_env_var_name 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 = ''
        cmd_names = self.get_commands().keys()

        if current:
            self.stdout.write(unicode(' '.join(
                [name for name in cmd_names if name.startswith(current)])))

        sys.exit(1)
1050092
def handle_completion(self):
        
        # We don't want these in the help, so handle them explicitely
        if len(sys.argv) > 1 and sys.argv[1].startswith("--help-completion-"):
            handler = getattr(self, sys.argv[1][2:].replace('-', '_'), None)
            if handler:
                print '\n'.join(sorted(handler()))
                self.STD_LOG_LEVEL = logging.DEBUG
                sys.exit(error.EX_OK)
860120
@Override
    public void addCompleter(final CommandLineCompleter completer) {
        console.addCompletion(new Completion() {
            @Override
            public void complete(CompleteOperation co) {
                int offset = completer.complete(cmdCtx, co.getBuffer(), co.getCursor(), co.getCompletionCandidates());

                // TODO : Not sure as of now to set offset
                // co.setOffset(offset);
            }
        });
    }
810029
def complete_help_command(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
        """"""

        # Complete token against topics and visible commands
        topics = set(self.get_help_topics())
        visible_commands = set(self.get_visible_commands())
        strs_to_match = list(topics | visible_commands)
        return self.basic_complete(text, line, begidx, endidx, strs_to_match)
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 []
835530
@Override
    public int complete(String buffer, int cursor, List<CharSequence> candidates)
    {
        // For now only support tab completion at the end of the line.
        if (cursor == buffer.length()) {
            // Check for an initial token match?
            if (cursor <= m_maxCommandPrefixLength) {
                final String bufferu = buffer.toUpperCase();
                for (final String command : m_commandPrefixes) {
                    if (command.startsWith(bufferu)) {
                        candidates.add(command);
                    }
                }
                if (!candidates.isEmpty()) {
                    return 0;
                }
            }
        }
        return cursor;
    }
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)
626636
def complete(self, text, state):
        
        if self.use_main_ns:
            self.namespace = __main__.__dict__
        if state == 0:
            self.matches = self.attr_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None
1109362
def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int,
                              argparser: argparse.ArgumentParser) -> List[str]:
        """"""
        completer = AutoCompleter(argparser, self)

        tokens, _ = self.tokens_for_completion(line, begidx, endidx)
        if not tokens:
            return []

        return completer.complete_command(tokens, text, line, begidx, endidx)
777146
def complete_vrf(arg):
    

    search_string = ''
    if arg is not None:
        search_string = '^%s' % arg

    res = VRF.search({
        'operator': 'regex_match',
        'val1': 'rt',
        'val2':  search_string
        }, { 'max_result': 100000 } )

    ret = []

    for v in res['result']:
        ret.append(v.rt)
    if re.match(search_string, 'none'):
        ret.append('none')

    return ret
251869
def get_completions(
    belstr: str,
    cursor_loc: int,
    bel_spec: BELSpec,
    bel_comp: str,
    bel_fmt: str,
    species_id: str,
    size: int,
):
    

    ast, errors = pparse.get_ast_dict(belstr)

    spans = pparse.collect_spans(ast)

    completion_text = ""
    completions = []
    function_help = []

    log.debug(f"Cursor location BELstr: {belstr}  Cursor idx: {cursor_loc}")
    cursor_results = cursor(belstr, ast, cursor_loc)
    log.debug(f"Cursor results: {cursor_results}")

    if not cursor_results:
        log.debug("Cursor results is empty")
        return (completion_text, completions, function_help, spans)

    completion_text = cursor_results.get("completion_text", "")

    replace_span = cursor_results["replace_span"]
    namespace = cursor_results.get("namespace", None)

    if "parent_function" in cursor_results:
        parent_function = cursor_results["parent_function"]
        function_help = bel_specification.get_function_help(
            cursor_results["parent_function"], bel_spec
        )

        args = cursor_results.get("args", [])
        arg_idx = cursor_results.get("arg_idx")

        replace_list = arg_completions(
            completion_text,
            parent_function,
            args,
            arg_idx,
            bel_spec,
            bel_fmt,
            species_id,
            namespace,
            size,
        )
    elif cursor_results["type"] == "Function":
        function_list = None
        replace_list = function_completions(
            completion_text, bel_spec, function_list, bel_fmt, size
        )
    elif cursor_results["type"] == "Relation":
        replace_list = relation_completions(completion_text, bel_spec, bel_fmt, size)

    completions.extend(
        add_completions(replace_list, belstr, replace_span, completion_text)
    )

    return completion_text, completions, function_help, spans
451287
def gen_enum_completions(self, arg_name):
        
        try:  # if enum completion
            for choice in self.cmdtab[self.current_command].arguments[arg_name].choices:
                if self.validate_completion(choice):
                    yield Completion(choice, -len(self.unfinished_word))

        except TypeError:  # there is no choices option
            pass
1324773
def _on_completions_refreshed(self, new_completer):
        
        with self._completer_lock:
            self.completer = new_completer
            # When cli is first launched we call refresh_completions before
            # instantiating the cli object. So it is necessary to check if cli
            # exists before trying the replace the completer object in cli.
            if self.cli:
                self.cli.current_buffer.completer = new_completer

        if self.cli:
            # After refreshing, redraw the CLI to clear the statusbar
            # "Refreshing completions..." indicator
            self.cli.request_redraw()