View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.util.designer;
5   
6   import javax.swing.JTextPane;
7   
8   import net.sourceforge.pmd.lang.ast.Node;
9   
10  public class CodeEditorTextPane extends JTextPane implements LineGetter {
11      
12      private String[] getLines() {
13  	// Support files with line separators from various platforms
14          return getText().split("\r\n|\r|\n");
15      }
16  
17      public String getLine(int number) {
18  	String[] lines= getLines();
19  	if (number < lines.length) {
20  	    return lines[number];
21  	}
22          throw new RuntimeException("Line number " + number + " not found");
23      }
24  
25      private int getPosition(String[] lines, int line, int column) {
26          int pos = 0;
27          for (int count = 0; count < lines.length;) {
28              String tok = lines[count++];
29              if (count == line) {
30                  int linePos = 0;
31                  int i;
32                  for (i = 0; linePos < column && linePos < tok.length(); i++) {
33                      linePos++;
34                      if (tok.charAt(i) == '\t') {
35                          linePos--;
36                          linePos += 8 - (linePos & 07);
37                      }
38                  }
39  
40                  return pos + i - 1;
41              }
42              pos += tok.length() + 1;
43          }
44          throw new RuntimeException("Line " + line + " not found");
45      }
46  
47      public void select(Node node) {
48          String[] lines = getLines();
49          if (node.getBeginLine() >= 0) {
50  	    setSelectionStart(getPosition(lines, node.getBeginLine(), node.getBeginColumn()));
51  	    setSelectionEnd(getPosition(lines, node.getEndLine(), node.getEndColumn()) + 1);
52  	}
53          requestFocus();
54      }
55  }