1 /*
   2  * Copyright (c) 2002-2016, the original author or authors.
   3  *
   4  * This software is distributable under the BSD license. See the terms of the
   5  * BSD license in the documentation provided with this software.
   6  *
   7  * http://www.opensource.org/licenses/bsd-license.php
   8  */
   9 package jdk.internal.jline.console.completer;
  10 
  11 import java.util.Arrays;
  12 import java.util.Collection;
  13 import java.util.List;
  14 import java.util.Map;
  15 import java.util.SortedMap;
  16 import java.util.TreeMap;
  17 
  18 import jdk.internal.jline.internal.Ansi;
  19 
  20 import static jdk.internal.jline.internal.Preconditions.checkNotNull;
  21 
  22 /**
  23  * Completer for a set of strings.
  24  *
  25  * @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
  26  * @since 2.3
  27  */
  28 public class AnsiStringsCompleter
  29     implements Completer
  30 {
  31     private final SortedMap<String, String> strings = new TreeMap<String, String>();
  32 
  33     public AnsiStringsCompleter() {
  34         // empty
  35     }
  36 
  37     public AnsiStringsCompleter(final Collection<String> strings) {
  38         checkNotNull(strings);
  39         for (String str : strings) {
  40             this.strings.put(Ansi.stripAnsi(str), str);
  41         }
  42     }
  43 
  44     public AnsiStringsCompleter(final String... strings) {
  45         this(Arrays.asList(strings));
  46     }
  47 
  48     public Collection<String> getStrings() {
  49         return strings.values();
  50     }
  51 
  52     public int complete(String buffer, final int cursor, final List<CharSequence> candidates) {
  53         // buffer could be null
  54         checkNotNull(candidates);
  55 
  56         if (buffer == null) {
  57             candidates.addAll(strings.values());
  58         }
  59         else {
  60             buffer = Ansi.stripAnsi(buffer);
  61             for (Map.Entry<String, String> match : strings.tailMap(buffer).entrySet()) {
  62                 if (!match.getKey().startsWith(buffer)) {
  63                     break;
  64                 }
  65 
  66                 candidates.add(match.getValue());
  67             }
  68         }
  69 
  70         return candidates.isEmpty() ? -1 : 0;
  71     }
  72 }