1 /* 2 * Copyright (c) 2002-2012, 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.SortedSet; 15 import java.util.TreeSet; 16 17 import static jdk.internal.jline.internal.Preconditions.checkNotNull; 18 19 /** 20 * Completer for a set of strings. 21 * 22 * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> 23 * @since 2.3 24 */ 25 public class StringsCompleter 26 implements Completer 27 { 28 private final SortedSet<String> strings = new TreeSet<String>(); 29 30 public StringsCompleter() { 31 // empty 32 } 33 34 public StringsCompleter(final Collection<String> strings) { 35 checkNotNull(strings); 36 getStrings().addAll(strings); 37 } 38 39 public StringsCompleter(final String... strings) { 40 this(Arrays.asList(strings)); 41 } 42 43 public Collection<String> getStrings() { 44 return strings; 45 } 46 47 public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) { 48 // buffer could be null 49 checkNotNull(candidates); 50 51 if (buffer == null) { 52 candidates.addAll(strings); 53 } 54 else { 55 for (String match : strings.tailSet(buffer)) { 56 if (!match.startsWith(buffer)) { 57 break; 58 } 59 60 candidates.add(match); 61 } 62 } 63 64 if (candidates.size() == 1) { 65 candidates.set(0, candidates.get(0) + " "); 66 } 67 68 return candidates.isEmpty() ? -1 : 0; 69 } 70 }