1 19 20 package org.netbeans.modules.tasklist.core.util; 21 22 import java.io.BufferedReader ; 23 import java.io.StringReader ; 24 import java.util.ArrayList ; 25 import java.util.Arrays ; 26 import java.util.List ; 27 28 31 public class TextPositionsMapper { 32 private String text; 33 private int[] offsets; 34 35 40 public TextPositionsMapper(String text) { 41 this.text = text; 42 43 BufferedReader br = new BufferedReader (new StringReader (text)); 44 List offsets = new ArrayList (); 45 offsets.add(new Integer (0)); 46 47 for (int i = 0; i < text.length(); i++) { 48 char c = text.charAt(i); 49 if (c == '\r') { 50 if (i + 1 < text.length() && text.charAt(i + 1) == '\n') { 51 i++; 52 offsets.add(new Integer (i + 1)); 53 } else { 54 offsets.add(new Integer (i + 1)); 55 } 56 } else if (c == '\n') { 57 offsets.add(new Integer (i + 1)); 58 } 59 } 60 61 this.offsets = new int[offsets.size()]; 62 for (int i = 0; i < this.offsets.length; i++) { 63 this.offsets[i] = ((Integer ) offsets.get(i)).intValue(); 64 } 65 } 66 67 73 public void findPosition(int offset, int[] position) { 74 assert offset >= 0 : "offset couldn't be negative"; 76 int index = Arrays.binarySearch(offsets, offset); 77 if (index >= 0) { 78 position[0] = index; 79 position[1] = 0; 80 } else { 81 index = -(index + 1); 82 assert index != 0 : "offset couldn't be negative"; position[0] = index - 1; 84 position[1] = offset - offsets[index - 1]; 85 } 86 } 87 88 93 public String getText() { 94 return text; 95 } 96 97 104 public String getLine(int line) { 105 int offset = offsets[line]; 106 int offset2; 107 if (offsets.length > line + 1) { 108 offset2 = offsets[line + 1]; 109 } else { 110 offset2 = text.length(); 111 } 112 return text.substring(offset, offset2); 113 } 114 } 115 | Popular Tags |