1 19 package jline; 20 21 import java.io.*; 22 import java.util.*; 23 24 25 50 public class FileNameCompletor 51 implements Completor 52 { 53 public int complete (String buffer, int cursor, List candidates) 54 { 55 if (buffer == null) 56 buffer = ""; 57 58 String translated = buffer; 59 60 if (translated.startsWith ("~" + File.separator)) 62 { 63 translated = System.getProperty ("user.home") 64 + translated.substring (1); 65 } 66 else if (translated.startsWith ("~")) 67 { 68 translated = new File (System.getProperty ("user.home")) 69 .getParentFile ().getAbsolutePath (); 70 } 71 else if (!(translated.startsWith (File.separator))) 72 { 73 translated = new File ("").getAbsolutePath () 74 + File.separator + translated; 75 } 76 77 File f = new File (translated); 78 79 final File dir; 80 81 if (translated.endsWith (File.separator)) 82 dir = f; 83 else 84 dir = f.getParentFile (); 85 86 final File [] entries = dir == null ? new File [0] : dir.listFiles (); 87 88 try 89 { 90 return matchFiles (buffer, translated, entries, candidates); 91 } 92 finally 93 { 94 sortFileNames (candidates); 96 } 97 } 98 99 100 protected void sortFileNames (List fileNames) 101 { 102 Collections.sort (fileNames); 103 } 104 105 106 119 public int matchFiles (String buffer, String translated, 120 File [] entries, List candidates) 121 { 122 if (entries == null) 123 return -1; 124 125 int matches = 0; 126 127 for (int i = 0; i < entries.length; i++) 129 { 130 if (entries [i].getAbsolutePath ().startsWith (translated)) 131 { 132 matches++; 133 } 134 } 135 136 for (int i = 0; i < entries.length; i++) 141 { 142 if (entries [i].getAbsolutePath ().startsWith (translated)) 143 { 144 String name = entries [i].getName () 145 + (matches == 1 && entries [i].isDirectory () 146 ? File.separator : " "); 147 148 154 155 candidates.add (name); 156 } 157 } 158 159 160 final int index = buffer.lastIndexOf (File.separator); 161 return index + File.separator.length (); 162 } 163 } 164 165 | Popular Tags |