rlm@10
|
1 /**
|
rlm@10
|
2 * Copyright (c) Rich Hickey. All rights reserved.
|
rlm@10
|
3 * The use and distribution terms for this software are covered by the
|
rlm@10
|
4 * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
|
rlm@10
|
5 * which can be found in the file epl-v10.html at the root of this distribution.
|
rlm@10
|
6 * By using this software in any fashion, you are agreeing to be bound by
|
rlm@10
|
7 * the terms of this license.
|
rlm@10
|
8 * You must not remove this notice, or any other, from this software.
|
rlm@10
|
9 */
|
rlm@10
|
10
|
rlm@10
|
11 package clojure.lang;
|
rlm@10
|
12
|
rlm@10
|
13 import java.io.PushbackReader;
|
rlm@10
|
14 import java.io.Reader;
|
rlm@10
|
15 import java.io.LineNumberReader;
|
rlm@10
|
16 import java.io.IOException;
|
rlm@10
|
17
|
rlm@10
|
18
|
rlm@10
|
19 public class LineNumberingPushbackReader extends PushbackReader{
|
rlm@10
|
20
|
rlm@10
|
21 // This class is a PushbackReader that wraps a LineNumberReader. The code
|
rlm@10
|
22 // here to handle line terminators only mentions '\n' because
|
rlm@10
|
23 // LineNumberReader collapses all occurrences of CR, LF, and CRLF into a
|
rlm@10
|
24 // single '\n'.
|
rlm@10
|
25
|
rlm@10
|
26 private static final int newline = (int) '\n';
|
rlm@10
|
27
|
rlm@10
|
28 private boolean _atLineStart = true;
|
rlm@10
|
29 private boolean _prev;
|
rlm@10
|
30
|
rlm@10
|
31 public LineNumberingPushbackReader(Reader r){
|
rlm@10
|
32 super(new LineNumberReader(r));
|
rlm@10
|
33 }
|
rlm@10
|
34
|
rlm@10
|
35 public int getLineNumber(){
|
rlm@10
|
36 return ((LineNumberReader) in).getLineNumber() + 1;
|
rlm@10
|
37 }
|
rlm@10
|
38
|
rlm@10
|
39 public int read() throws IOException{
|
rlm@10
|
40 int c = super.read();
|
rlm@10
|
41 _prev = _atLineStart;
|
rlm@10
|
42 _atLineStart = (c == newline) || (c == -1);
|
rlm@10
|
43 return c;
|
rlm@10
|
44 }
|
rlm@10
|
45
|
rlm@10
|
46 public void unread(int c) throws IOException{
|
rlm@10
|
47 super.unread(c);
|
rlm@10
|
48 _atLineStart = _prev;
|
rlm@10
|
49 }
|
rlm@10
|
50
|
rlm@10
|
51 public String readLine() throws IOException{
|
rlm@10
|
52 int c = read();
|
rlm@10
|
53 String line;
|
rlm@10
|
54 switch (c) {
|
rlm@10
|
55 case -1:
|
rlm@10
|
56 line = null;
|
rlm@10
|
57 break;
|
rlm@10
|
58 case newline:
|
rlm@10
|
59 line = "";
|
rlm@10
|
60 break;
|
rlm@10
|
61 default:
|
rlm@10
|
62 String first = String.valueOf((char) c);
|
rlm@10
|
63 String rest = ((LineNumberReader)in).readLine();
|
rlm@10
|
64 line = (rest == null) ? first : first + rest;
|
rlm@10
|
65 _prev = false;
|
rlm@10
|
66 _atLineStart = true;
|
rlm@10
|
67 break;
|
rlm@10
|
68 }
|
rlm@10
|
69 return line;
|
rlm@10
|
70 }
|
rlm@10
|
71
|
rlm@10
|
72 public boolean atLineStart(){
|
rlm@10
|
73 return _atLineStart;
|
rlm@10
|
74 }
|
rlm@10
|
75 }
|