1 21 22 package org.armedbear.j; 23 24 import gnu.regexp.RE; 25 import gnu.regexp.REException; 26 import gnu.regexp.REMatch; 27 import javax.swing.undo.CompoundEdit ; 28 29 public final class AlignStrings 30 { 31 public static void alignStrings() 32 { 33 final Editor editor = Editor.currentEditor(); 34 InputDialog d = 35 new InputDialog(editor, "Regular Expression:", "Align Strings", 36 null); 37 d.setHistory(new History("alignStrings")); 38 editor.centerDialog(d); 39 d.show(); 40 String input = d.getInput(); 41 if (input != null) 42 alignStrings(input); 43 } 44 45 public static void alignStrings(String s) 46 { 47 final Editor editor = Editor.currentEditor(); 48 if (!editor.checkReadOnly()) 49 return; 50 if (editor.getMark() == null) 51 return; 52 final Region region = new Region(editor); 53 if (region.getEndLineNumber() - region.getBeginLineNumber() < 2) 54 return; 55 s = unquote(s); 56 RE re; 57 try { 58 re = new RE(s); 59 } 60 catch (REException e) { 61 MessageDialog.showMessageDialog(editor, e.getMessage(), "Error"); 62 return; 63 } 64 final Buffer buffer = editor.getBuffer(); 65 try { 66 buffer.lockWrite(); 67 } 68 catch (InterruptedException e) { 69 Log.error(e); 70 return; 71 } 72 try { 73 _alignStrings(editor, buffer, region, re); 74 } 75 finally { 76 buffer.unlockWrite(); 77 } 78 } 79 80 private static void _alignStrings(Editor editor, Buffer buffer, 81 Region region, RE re) 82 { 83 int maxCol = -1; 84 for (Line line = region.getBeginLine(); line != region.getEndLine(); 85 line = line.next()) { 86 String text = line.getText(); 87 if (text != null) { 88 REMatch match = re.getMatch(text); 89 if (match != null) { 90 int offset = match.getStartIndex(); 91 int col = buffer.getCol(line, offset); 92 if (col > maxCol) 93 maxCol = col; 94 } 95 } 96 } 97 if (maxCol < 0) 98 return; 99 Position savedDot = new Position(editor.getDot()); 100 CompoundEdit compoundEdit = buffer.beginCompoundEdit(); 101 for (Line line = region.getBeginLine(); line != region.getEndLine(); 102 line = line.next()) { 103 String text = line.getText(); 104 if (text != null) { 105 REMatch match = re.getMatch(text); 106 if (match != null) { 107 int offset = match.getStartIndex(); 108 int col = buffer.getCol(line, offset); 109 if (col < maxCol) { 110 editor.addUndo(SimpleEdit.MOVE); 111 editor.getDot().moveTo(line, offset); 112 editor.addUndo(SimpleEdit.LINE_EDIT); 113 buffer.insertChars(editor.getDot(), 114 Utilities.spaces(maxCol - col)); 115 Editor.updateInAllEditors(buffer, line); 116 } 117 } 118 } 119 } 120 editor.getDot().moveTo(savedDot); 121 editor.moveCaretToDotCol(); 122 buffer.endCompoundEdit(compoundEdit); 123 } 124 125 private static String unquote(String s) 126 { 127 int length = s.length(); 128 if (length >= 2) { 129 char c = s.charAt(0); 130 if (c == '"' || c == '\'') { 131 if (s.charAt(length-1) == c) 132 return s.substring(1, length-1); 133 } 134 } 135 return s; 136 } 137 } 138 | Popular Tags |