01: /*
02: * This is free software, licensed under the Gnu Public License (GPL)
03: * get a copy from <http://www.gnu.org/licenses/gpl.html>
04: * $Id: FileCompletionIterator.java,v 1.5 2004/05/31 10:48:22 hzeller Exp $
05: * author: Henner Zeller <H.Zeller@acm.org>
06: */
07: package henplus.commands;
08:
09: import java.util.Iterator;
10: import java.io.File;
11: import java.io.IOException;
12:
13: /**
14: * fixme. first simple implementation..
15: */
16: public class FileCompletionIterator implements Iterator {
17: private String dirList[];
18: private String matchName;
19: private String nextFileName;
20: private String completePrefix;
21: private int index;
22:
23: public FileCompletionIterator(String partialCommand, String lastWord) {
24: String startFile;
25: int lastPos = partialCommand.lastIndexOf(' ');
26: startFile = ((lastPos >= 0) ? partialCommand
27: .substring(lastPos + 1) : "");
28: //startFile = prefix + startFile;
29: //System.err.println("f: " + startFile);
30:
31: try {
32: int lastDirectory = startFile.lastIndexOf(File.separator);
33: String dirName = ".";
34: completePrefix = "";
35: if (lastDirectory > 0) {
36: dirName = startFile.substring(0, lastDirectory);
37: startFile = startFile.substring(lastDirectory + 1);
38: completePrefix = dirName + File.separator;
39: }
40: File f = (new File(dirName)).getCanonicalFile();
41: boolean isDir = f.isDirectory();
42: dirList = (isDir) ? f.list() : f.getParentFile().list();
43: matchName = startFile;
44: } catch (IOException e) {
45: dirList = null;
46: matchName = null;
47: }
48: index = 0;
49: }
50:
51: // this iterator _requires_, that hasNext() is called before next().
52:
53: public boolean hasNext() {
54: if (dirList == null)
55: return false;
56: while (index < dirList.length) {
57: nextFileName = dirList[index++];
58: if (nextFileName.startsWith(matchName)) {
59: File f = new File(completePrefix + nextFileName);
60: if (f.isDirectory()) {
61: nextFileName += File.separator;
62: }
63: return true;
64: }
65: }
66: return false;
67: }
68:
69: public Object next() {
70: return completePrefix + nextFileName;
71: }
72:
73: public void remove() {
74: }
75: }
76:
77: /*
78: * Local variables:
79: * c-basic-offset: 4
80: * compile-command: "ant -emacs -find build.xml"
81: * End:
82: */
|