001: /*
002: * This is free software, licensed under the Gnu Public License (GPL)
003: * get a copy from <http://www.gnu.org/licenses/gpl.html>
004: * $Id: HistoryWriter.java,v 1.3 2005/11/27 16:20:27 hzeller Exp $
005: * author: Henner Zeller <H.Zeller@acm.org>
006: */
007: package henplus;
008:
009: import java.io.BufferedReader;
010: import java.io.IOException;
011: import java.io.InputStream;
012: import java.io.InputStreamReader;
013: import java.io.OutputStream;
014: import java.io.OutputStreamWriter;
015: import java.io.PrintWriter;
016: import java.io.Reader;
017:
018: import org.gnu.readline.Readline;
019:
020: /**
021: * A utility class that writes the history. This especially handles
022: * multiline elements. This should be some Reader/Writer, that handles
023: * reading/writing of escaped lines. For now, it is just a collection
024: * of static methods. Quick hack to make storing of multiline statements
025: * work..
026: */
027: public class HistoryWriter {
028:
029: public static void writeReadlineHistory(OutputStream out)
030: throws IOException {
031: PrintWriter w = new PrintWriter(new OutputStreamWriter(out,
032: "UTF-8"));
033: int len = Readline.getHistorySize();
034: for (int i = 0; i < len; ++i) {
035: String line = Readline.getHistoryLine(i);
036: if (line == null)
037: continue;
038: line = escape(line);
039: w.println(line);
040: }
041: w.close();
042: }
043:
044: public static void readReadlineHistory(InputStream in)
045: throws IOException {
046: // todo: check first utf-8, then default-encoding to be
047: // backward-compatible.
048: readReadlineHistory(new InputStreamReader(in, "UTF-8"));
049: }
050:
051: private static void readReadlineHistory(Reader in)
052: throws IOException {
053: final Reader r = new BufferedReader(in);
054: StringBuffer line = new StringBuffer();
055: int c;
056: do {
057: while ((c = r.read()) >= 0 && c != '\n') {
058: char ch = (char) c;
059: if (ch == '\\') {
060: line.append((char) r.read());
061: } else {
062: line.append(ch);
063: }
064: }
065: if (line.length() > 0) {
066: Readline.addToHistory(line.toString());
067: line.setLength(0);
068: }
069: } while (c >= 0);
070: r.close();
071: }
072:
073: private static String escape(String s) {
074: if (s.indexOf('\\') >= 0 || s.indexOf('\n') >= 0) {
075: StringBuffer out = new StringBuffer();
076: for (int i = 0; i < s.length(); ++i) {
077: char c = s.charAt(i);
078: switch (c) {
079: case '\\':
080: out.append("\\\\");
081: break;
082: case '\n':
083: out.append("\\\n");
084: break;
085: default:
086: out.append(c);
087: }
088: }
089: return out.toString();
090: } else {
091: return s;
092: }
093: }
094: }
095:
096: /*
097: * Local variables:
098: * c-basic-offset: 4
099: * compile-command: "ant -emacs -find build.xml"
100: * End:
101: */
|