1 18 package org.codehaus.groovy.antlr; 19 20 import java.util.List ; 21 import java.util.ArrayList ; 22 23 30 public class SourceBuffer { 31 private List lines; 32 private StringBuffer current; 33 34 public SourceBuffer() { 35 lines = new ArrayList (); 36 38 current = new StringBuffer (); 39 lines.add(current); 40 } 41 42 48 public String getSnippet(LineColumn start, LineColumn end) { 49 if (start == null || end == null) { return null; } if (start.equals(end)) { return null; } if (lines.size() == 1 && current.length() == 0) { return null; } 54 int startLine = start.getLine(); 56 int startColumn = start.getColumn(); 57 int endLine = end.getLine(); 58 int endColumn = end.getColumn(); 59 60 if (startLine < 1) { startLine = 1;} 62 if (endLine < 1) { endLine = 1;} 63 if (startColumn < 1) { startColumn = 1;} 64 if (endColumn < 1) { endColumn = 1;} 65 if (startLine > lines.size()) { startLine = lines.size(); } 66 if (endLine > lines.size()) { endLine = lines.size(); } 67 68 StringBuffer snippet = new StringBuffer (); 70 for (int i = startLine - 1; i < endLine;i++) { 71 String line = ((StringBuffer )lines.get(i)).toString(); 72 if (startLine == endLine) { 73 if (startColumn > line.length()) { startColumn = line.length();} 75 if (startColumn < 1) { startColumn = 1;} 76 if (endColumn > line.length()) { endColumn = line.length() + 1;} 77 if (endColumn < 1) { endColumn = 1;} 78 79 line = line.substring(startColumn - 1, endColumn - 1); 80 } else { 81 if (i == startLine - 1) { 82 if (startColumn - 1 < line.length()) { 83 line = line.substring(startColumn - 1); 84 } 85 } 86 if (i == endLine - 1) { 87 if (endColumn - 1 < line.length()) { 88 line = line.substring(0,endColumn - 1); 89 } 90 } 91 } 92 snippet.append(line); 93 } 94 return snippet.toString(); 95 } 96 97 101 public void write(int c) { 102 if (c != -1) { 103 current.append((char)c); 104 } 105 if (c == '\n') { 106 current = new StringBuffer (); 107 lines.add(current); 108 } 109 } 110 } 111 | Popular Tags |