| 1 31 32 33 package org.antlr.works.ate.swing; 34 35 import org.antlr.works.ate.ATEPanel; 36 37 import javax.swing.*; 38 import javax.swing.text.BadLocationException ; 39 import javax.swing.text.Document ; 40 41 public class ATEAutoIndentation implements Runnable { 42 43 protected int offset; 44 protected int length; 45 protected boolean enabled = true; 46 47 protected ATEPanel textEditor; 48 49 public ATEAutoIndentation(ATEPanel textEditor) { 50 this.textEditor = textEditor; 51 } 52 53 public void setEnabled(boolean enable) { 54 this.enabled = enable; 55 } 56 57 public boolean enabled() { 58 return enabled; 59 } 60 61 public void indent(int offset, int length) { 62 this.offset = offset; 63 this.length = length; 64 if(enabled()) 65 SwingUtilities.invokeLater(this); 66 } 67 68 public Document getDocument() { 69 return textEditor.getTextPane().getDocument(); 70 } 71 72 public boolean autoIndentAfterReturn() throws BadLocationException { 73 String s = getDocument().getText(offset-1, length+1); 74 if(s.length() == 0) 75 return false; 76 77 if(s.length() == 1 || (s.charAt(0) != '\n' && s.charAt(1) == '\n')) { 78 String t = getDocument().getText(0, offset); 80 for(int i = offset - 2; i >= 0; i--) { 81 if(t.charAt(i) == '\n' || i == 0) { 83 if(i > 0) { 85 i++; 87 } 88 int start = i; 91 while((i < offset - 1) && (t.charAt(i) == ' ' || t.charAt(i) == '\t')) { 92 i++; 93 } 94 95 if(i == offset - 1 && (t.charAt(i) == ' ' || t.charAt(i) == '\t')) { 99 i++; 100 } 101 getDocument().insertString(offset+1, t.substring(start, i), null); 102 return true; 103 } 104 } 105 } 106 return false; 107 } 108 109 110 public void run() { 111 try { 112 if(!autoIndentAfterReturn()) { 113 textEditor.ateAutoIndent(offset, length); 114 } 115 } catch (BadLocationException e) { 116 } 118 } 119 120 } 121 | Popular Tags |