(Only for internal use!)
        Get a new completion by splitting this one. Used by
        `CommandLineInterface` when it needs to have a list of new completions
        after inserting the common prefix.
975330
def new_completion_from_position(self, position):
        
        assert isinstance(position, int) and position - self.start_position >= 0

        return Completion(
            text=self.text[position - self.start_position:],
            display=self.display,
            display_meta=self._display_meta,
            get_display_meta=self._get_display_meta)
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 []
256462
private function getRoamedCompletions(string $prefix): \Generator
    {
        foreach ($this->index->getChildDefinitionsForFqn('') as $fqn => $def) {
            if (!$def->roamed || !nameStartsWith($fqn, $prefix)) {
                continue;
            }
            $completionItem = CompletionItemFactory::fromDefinition($def);
            // Second-guessing the user here - do not trust roaming to work. If the same symbol is
            // inserted in the current namespace, the code will stop working.
            $completionItem->insertText =  '\\' . $fqn;
            yield $fqn => $completionItem;
        }
    }
383675
def complete_import(self, text, line, begidx, endidx):
        """"""

        opts = self.IMPORT_OPTS

        if not text:
            completions = opts
        else:
            completions = [f
                           for f in opts
                           if f.startswith(text)
                           ]
        return completions
1166808
def __insert_completion(self, completion):
        

        LOGGER.debug("> Inserting '{0}' completion.".format(completion))

        text_cursor = self.textCursor()
        extra = (completion.length() - self.__completer.completion_prefix().length())
        text_cursor.insertText(completion.right(extra))
        self.setTextCursor(text_cursor)
1042852
def _get_completions(self):
        """"""
        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(u''.join(buf[self.begidx:self.endidx]))
            log(u'complete text="%s"' % ensure_unicode(text))
            i = 0
            while 1:
                try:
                    r = ensure_unicode(self.completer(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(u'text completions=<%s>' % 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 u' \t\n':
                    self.begidx += 1
                    break
            text = ensure_str(u''.join(buf[self.begidx:self.endidx]))
            log(u'file complete text="%s"' % ensure_unicode(text))
            completions = map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*'))
            if self.mark_directories == u'on':
                mc = []
                for f in completions:
                    if os.path.isdir(f):
                        mc.append(f + os.sep)
                    else:
                        mc.append(f)
                completions = mc
            log(u'fnames=<%s>' % map(ensure_unicode, completions))
        return completions
611747
protected int complete(CommandContext ctx, ParsedCommandLine parsedCmd, OperationCandidatesProvider candidatesProvider, final String buffer, int cursor, List<String> candidates) {

        if(parsedCmd.isRequestComplete()) {
            return -1;
        }

        // Headers completion
        if(parsedCmd.endsOnHeaderListStart() || parsedCmd.hasHeaders()) {
            return completeHeaders(ctx, parsedCmd, candidatesProvider, buffer, cursor, candidates);
        }

        // Completed.
        if(parsedCmd.endsOnPropertyListEnd()) {
            return buffer.length();
        }

        // Complete properties
        if (parsedCmd.hasProperties() || parsedCmd.endsOnPropertyListStart()
                || parsedCmd.endsOnNotOperator()) {
            return completeProperties(ctx, parsedCmd, candidatesProvider, buffer, candidates);
        }

        // Complete Operation name
        if (parsedCmd.hasOperationName() || parsedCmd.endsOnAddressOperationNameSeparator()) {
            return completeOperationName(ctx, parsedCmd, candidatesProvider, buffer, candidates);
        }

        // Finally Complete address
        return completeAddress(ctx, parsedCmd, candidatesProvider, buffer, candidates);
    }
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;
    }
1104346
public Opt<String> getAutoCompleteSuffix() {
        if (possibilities.isEmpty()) {
            // There are no auto-complete possibilities.
            return Opt.absent();
        }

        if (possibilities.size() > 1) {
            // Multiple auto complete results are possible.
            // AutoComplete as much as is possible - until the longest common prefix.
            final String longestPrefix = possibilities.getLongestPrefix();
            return StringUtils.getNonEmptyString(calcAutoCompleteSuffix(longestPrefix));
        }

        // TODO: Only 1 possibility, boundParams should be updated to show it...
        // Only a single auto complete result is possible, append it to the command line.
        // Let's be helpful - depending on the autoCompleteType,
        // add the suffix that each valueType must have.
        final Entry<String, CliValueType> entry = possibilities.entrySet().iterator().next();
        final String singlePossibility = entry.getKey();
        final CliValueType type = entry.getValue();
        final String suffix = calcAutoCompleteSuffix(singlePossibility);
        return Opt.of(suffix + type.getSuffix());
    }
752479
public Split<JobXMLDescriptor> getOrCreateSplit()
   {
      List<Node> nodeList = model.get("split");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new SplitImpl<JobXMLDescriptor>(this, "split", model, nodeList.get(0));
      }
      return createSplit();
   }
521402
public List<CompletionProposal> complete(CompletionContext context) {

		String prefix = context.upToCursor();

		List<CompletionProposal> candidates = new ArrayList<>();
		candidates.addAll(commandsStartingWith(prefix));

		String best = findLongestCommand(prefix);
		if (best != null) {
			CompletionContext argsContext = context.drop(best.split(" ").length);
			// Try to complete arguments
			MethodTarget methodTarget = methodTargets.get(best);
			Method method = methodTarget.getMethod();

			List<MethodParameter> parameters = Utils.createMethodParameters(method).collect(Collectors.toList());
			for (ParameterResolver resolver : parameterResolvers) {
				for (int index = 0; index < parameters.size(); index++) {
					MethodParameter parameter = parameters.get(index);
					if (resolver.supports(parameter)) {
						resolver.complete(parameter, argsContext).stream().forEach(candidates::add);
					}
				}
			}
		}
		return candidates;
	}
660466
def complete(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx):
        
        # TODO: Optionally check that flags are not repeated (i.e. exclude
        #       them from the possible matches if they are already in the
        #       command line)
        # TODO: Support groups of mutually-exclusive flags, i.e. if one is
        #       already present, the others in the group are not accepted
        if len(sp_args) == 0 or not line.endswith(sp_args[-1]):
            # if line.endswith(sp_args[-1]) is False, it means that the last
            # sp_args is already complete
            return self.accepted_flags
        else:
            matches = []
            for arg in self.accepted_flags:
                if arg.startswith(sp_args[-1]):
                    matches.append(arg)
            if len(matches) == 1:
                # In general, SPLIT_ARGS and readline use different word
                #  delimiters, see e.g. the docs for
                #  readline.get_completer_delims()
                # If for example there's a 'foo-bar' argument, SPLIT_ARGS sees
                #  it as a single word, but readline by default will split it
                #  in two words, 'foo' and 'bar', and if 'foo-b' is entered in
                #  the command line, and Tab is pressed, the word will be
                #  completed as 'foo-bfoo-bar', unless we compensate here by
                #  subtracting the rl_prefix from the found match
                sub = len(sp_args[-1]) - len(rl_prefix)
                return [matches[0][sub:]]
            else:
                return matches
101100
def complete(text, state):
    """"""
    global completion_results
    if state == 0:
        line = readline.get_line_buffer()
        if line.startswith(':'):
            # Control command completion
            completion_results = complete_control_command(line, text)
        else:
            if line.startswith('!') and text and line.startswith(text):
                dropped_exclam = True
                text = text[1:]
            else:
                dropped_exclam = False
            completion_results = []
            # Complete local paths
            completion_results += complete_local_path(text)
            # Complete from history
            l = len(text)
            completion_results += [w + ' ' for w in history_words if
                                   len(w) > l and w.startswith(text)]
            if readline.get_begidx() == 0:
                # Completing first word from $PATH
                completion_results += [w + ' ' for w in user_commands_in_path
                                           if len(w) > l and w.startswith(text)]
            completion_results = remove_dupes(completion_results)
            if dropped_exclam:
                completion_results = ['!' + r for r in completion_results]

    if state < len(completion_results):
        return completion_results[state]
    completion_results = None
    return None
365943
@Nonnull
  protected Completer discoverCompleter() {
    log.debug("Discovering completer");

    // TODO: Could probably use CliProcessorAware to avoid re-creating this
    CliProcessor cli = new CliProcessor();
    cli.addBean(this);

    List<ArgumentDescriptor> argumentDescriptors = cli.getArgumentDescriptors();
    Collections.sort(argumentDescriptors);

    if (log.isDebugEnabled()) {
      log.debug("Argument descriptors:");
      argumentDescriptors.forEach(descriptor -> log.debug("  {}", descriptor));
    }

    List<Completer> completers = new LinkedList<>();

    // attempt to resolve @Complete on each argument
    argumentDescriptors.forEach(descriptor -> {
      AccessibleObject accessible = descriptor.getSetter().getAccessible();
      if (accessible != null) {
        Complete complete = accessible.getAnnotation(Complete.class);
        if (complete != null) {
          Completer completer = namedCompleters.get(complete.value());
          checkState(completer != null, "Missing named completer: %s", complete.value());
          completers.add(completer);
        }
      }
    });

    // short-circuit if no completers detected
    if (completers.isEmpty()) {
      return NullCompleter.INSTANCE;
    }

    if (log.isDebugEnabled()) {
      log.debug("Discovered completers:");
      completers.forEach(completer -> {
        log.debug("  {}", completer);
      });
    }

    // append terminal completer for strict
    completers.add(NullCompleter.INSTANCE);

    ArgumentCompleter completer = new ArgumentCompleter(completers);
    completer.setStrict(true);
    return completer;
  }
772523
private CompletionProvider helpCompletion() {
        return (code, cursor, anchor) -> {
            List<Suggestion> result;
            int pastSpace = code.indexOf(' ') + 1; // zero if no space
            if (pastSpace == 0) {
                // initially suggest commands (with slash) and subjects,
                // however, if their subject starts without slash, include
                // commands without slash
                boolean noslash = code.length() > 0 && !code.startsWith("/");
                result = new FixedCompletionProvider(commands.values().stream()
                        .filter(cmd -> cmd.kind.showInHelp || cmd.kind == CommandKind.HELP_SUBJECT)
                        .map(c -> ((noslash && c.command.startsWith("/"))
                                ? c.command.substring(1)
                                : c.command) + " ")
                        .toArray(String[]::new))
                        .completionSuggestions(code, cursor, anchor);
            } else if (code.startsWith("/se") || code.startsWith("se")) {
                result = new FixedCompletionProvider(SET_SUBCOMMANDS)
                        .completionSuggestions(code.substring(pastSpace), cursor - pastSpace, anchor);
            } else {
                result = Collections.emptyList();
            }
            anchor[0] += pastSpace;
            return result;
        };
    }
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)
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();
    }
  }