private static List<LookupElement> sortByPresentation(
     Iterable<LookupElement> source, Lookup lookup) {
   ArrayList<LookupElement> startMatches = ContainerUtil.newArrayList();
   ArrayList<LookupElement> middleMatches = ContainerUtil.newArrayList();
   for (LookupElement element : source) {
     (CompletionServiceImpl.isStartMatch(element, lookup) ? startMatches : middleMatches)
         .add(element);
   }
   ContainerUtil.sort(startMatches, BY_PRESENTATION_COMPARATOR);
   ContainerUtil.sort(middleMatches, BY_PRESENTATION_COMPARATOR);
   startMatches.addAll(middleMatches);
   return startMatches;
 }
  private List<LookupElement> fillModelByRelevance(
      LookupImpl lookup,
      List<LookupElement> items,
      MultiMap<CompletionSorterImpl, LookupElement> inputBySorter,
      @Nullable LookupElement relevantSelection) {
    Iterator<LookupElement> byRelevance = sortByRelevance(inputBySorter).iterator();

    final LinkedHashSet<LookupElement> model = new LinkedHashSet<LookupElement>();

    addPrefixItems(model);
    addFrozenItems(items, model);
    addSomeItems(
        model,
        byRelevance,
        new Condition<LookupElement>() {
          @Override
          public boolean value(LookupElement lastAdded) {
            return model.size() >= MAX_PREFERRED_COUNT;
          }
        });
    addCurrentlySelectedItemToTop(lookup, items, model);

    freezeTopItems(lookup, model);

    ensureItemAdded(items, model, byRelevance, lookup.getCurrentItem());
    ensureItemAdded(items, model, byRelevance, relevantSelection);
    ensureEverythingVisibleAdded(lookup, model, byRelevance);

    ArrayList<LookupElement> result = new ArrayList<LookupElement>(model);
    if (result.size() > 1) {
      LookupElement first = result.get(0);
      if (isLiveTemplate(first) && isPrefixItem(lookup, first, true)) {
        ContainerUtil.swapElements(result, 0, 1);
      }
    }

    return result;
  }