01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10: package org.mmbase.util.transformers;
11:
12: import java.io.Reader;
13: import java.io.Writer;
14:
15: import org.mmbase.util.logging.*;
16:
17: /**
18: * Replace every tab by n spaces.
19: *
20: * @author Michiel Meeuwissen
21: * @since MMBase-1.7
22: */
23:
24: public class TabToSpacesTransformer extends ReaderTransformer implements
25: CharTransformer {
26:
27: private static final Logger log = Logging
28: .getLoggerInstance(TabToSpacesTransformer.class);
29:
30: private int spaceNum;
31: private String tab;
32:
33: public TabToSpacesTransformer() {
34: this (3);
35: }
36:
37: public TabToSpacesTransformer(int spaces) {
38: spaceNum = spaces;
39: {
40: StringBuilder buf = new StringBuilder();
41: for (int i = 0; i < spaceNum; i++) {
42: buf.append(' ');
43: }
44: tab = buf.toString();
45: }
46: }
47:
48: public Writer transform(Reader r, Writer w) {
49: try {
50: while (true) {
51: int c = r.read();
52: if (c == -1)
53: break;
54: if (c == '\t') {
55: w.write(tab);
56: continue;
57: }
58: w.write(c);
59: }
60: } catch (java.io.IOException e) {
61: log.error(e.toString());
62: }
63: return w;
64: }
65:
66: public Writer transformBack(Reader r, Writer w) {
67: int spaces = 1;
68: try {
69: while (true) {
70: int c = r.read();
71: if (c == -1)
72: break;
73: if (c == ' ') {
74: if (spaces == spaceNum) {
75: w.write('\t');
76: spaces = 1;
77: } else {
78: spaces++;
79: }
80: } else {
81: while (spaces > 1) {
82: --spaces;
83: w.write(' ');
84: }
85: w.write(c);
86: }
87:
88: }
89: } catch (java.io.IOException e) {
90: log.error(e.toString());
91: }
92: return w;
93:
94: }
95:
96: public String toString() {
97: return "tab2spacestransformer";
98: }
99: }
|