1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.doxia.module.markdown;
20
21 import java.io.IOException;
22 import java.io.Writer;
23
24 import org.apache.maven.doxia.util.DoxiaStringUtils;
25
26
27
28
29
30
31 public class LastTwoLinesAwareWriter extends Writer {
32
33 private final Writer out;
34 private String previousLine;
35 private StringBuilder currentLine;
36 private final String lineSeparator;
37
38 public LastTwoLinesAwareWriter(Writer out) {
39
40 this(out, System.getProperty("line.separator"));
41 }
42
43 LastTwoLinesAwareWriter(Writer out, String lineSeparator) {
44 super();
45 this.out = out;
46 this.previousLine = "";
47 this.currentLine = new StringBuilder();
48 this.lineSeparator = lineSeparator;
49 }
50
51 public boolean isWriterAtStartOfNewLine() {
52 return currentLine.length() == 0;
53 }
54
55 public boolean isWriterAfterBlankLine() {
56 return DoxiaStringUtils.isBlank(currentLine.toString()) && DoxiaStringUtils.isBlank(previousLine);
57 }
58
59 public boolean isInBlankLine() {
60 return DoxiaStringUtils.isBlank(currentLine.toString());
61 }
62
63 @Override
64 public void write(char[] cbuf, int off, int len) throws IOException {
65 int offsetWrittenInLineBuffer = off;
66 int index = 0;
67 while (index < len) {
68
69 if (cbuf[off + index] == '\r' || cbuf[off + index] == '\n') {
70 int lenToWrite = index + 1 - (offsetWrittenInLineBuffer - off);
71 flushLine(cbuf, offsetWrittenInLineBuffer, lenToWrite);
72 offsetWrittenInLineBuffer += lenToWrite;
73 }
74 index++;
75 }
76 flushLine(cbuf, offsetWrittenInLineBuffer, index - (offsetWrittenInLineBuffer - off));
77 out.write(cbuf, off, len);
78 }
79
80 private void flushLine(char[] cbuf, int off, int len) {
81 this.currentLine.append(cbuf, off, len);
82
83 if (currentLine.toString().endsWith(lineSeparator)) {
84 previousLine = currentLine.toString();
85 currentLine.setLength(0);
86 }
87 }
88
89 @Override
90 public void flush() throws IOException {
91 out.flush();
92 }
93
94 @Override
95 public void close() throws IOException {
96 out.close();
97 }
98
99 public boolean isAfterDigit() {
100 return currentLine.length() > 1 && Character.isDigit(currentLine.charAt(currentLine.length() - 1));
101 }
102 }