IndentingPrintWriter.java revision cbad976b2a36a0895ca94510d5208a86f66cf596
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.util;
18
19import java.io.PrintWriter;
20import java.io.Writer;
21
22/**
23 * Lightweight wrapper around {@link PrintWriter} that automatically indents
24 * newlines based on internal state. Delays writing indent until first actual
25 * write on a newline, enabling indent modification after newline.
26 */
27public class IndentingPrintWriter extends PrintWriter {
28    private final String mIndent;
29
30    private StringBuilder mBuilder = new StringBuilder();
31    private char[] mCurrent;
32    private boolean mEmptyLine = true;
33
34    public IndentingPrintWriter(Writer writer, String indent) {
35        super(writer);
36        mIndent = indent;
37    }
38
39    public void increaseIndent() {
40        mBuilder.append(mIndent);
41        mCurrent = null;
42    }
43
44    public void decreaseIndent() {
45        mBuilder.delete(0, mIndent.length());
46        mCurrent = null;
47    }
48
49    public void printPair(String key, Object value) {
50        print(key + "=" + String.valueOf(value) + " ");
51    }
52
53    @Override
54    public void write(char[] buf, int offset, int count) {
55        final int bufferEnd = offset + count;
56        int lineStart = offset;
57        int lineEnd = offset;
58        while (lineEnd < bufferEnd) {
59            char ch = buf[lineEnd++];
60            if (ch == '\n') {
61                writeIndent();
62                super.write(buf, lineStart, lineEnd - lineStart);
63                lineStart = lineEnd;
64                mEmptyLine = true;
65            }
66        }
67
68        if (lineStart != lineEnd) {
69            writeIndent();
70            super.write(buf, lineStart, lineEnd - lineStart);
71        }
72    }
73
74    private void writeIndent() {
75        if (mEmptyLine) {
76            mEmptyLine = false;
77            if (mBuilder.length() != 0) {
78                if (mCurrent == null) {
79                    mCurrent = mBuilder.toString().toCharArray();
80                }
81                super.write(mCurrent, 0, mCurrent.length);
82            }
83        }
84    }
85}
86