1 21 22 package org.armedbear.j; 23 24 import java.util.ArrayList ; 25 import java.util.Collections ; 26 import java.util.Comparator ; 27 import javax.swing.undo.CompoundEdit ; 28 29 public final class Sort 30 { 31 public static void sortLines() 32 { 33 final Editor editor = Editor.currentEditor(); 34 if (editor.getMark() == null) 35 return; 36 final Region region = new Region(editor); 37 if (region.getEndLineNumber() - region.getBeginLineNumber() < 2) 38 return; 39 if (!editor.checkReadOnly()) 40 return; 41 final Buffer buffer = editor.getBuffer(); 42 try { 43 buffer.lockWrite(); 44 } 45 catch (InterruptedException e) { 46 Log.error(e); 47 return; 48 } 49 try { 50 sortLinesInternal(editor, buffer, region); 51 } 52 finally { 53 buffer.unlockWrite(); 54 } 55 } 56 57 private static void sortLinesInternal(Editor editor, Buffer buffer, Region region) 58 { 59 ArrayList arrayList = new ArrayList (); 60 for (Line line = region.getBeginLine(); line != region.getEndLine(); line = line.next()) 61 arrayList.add(line.getText()); 62 Collections.sort(arrayList, new SortLinesComparator()); 63 CompoundEdit compoundEdit = null; 64 int i = 0; 65 for (Line line = region.getBeginLine(); line != region.getEndLine(); line = line.next(), i++) { 66 String newText = (String ) arrayList.get(i); 67 if (!newText.equals(line.getText())) { 68 if (compoundEdit == null) { 69 compoundEdit = new CompoundEdit (); 70 compoundEdit.addEdit(new UndoMove(editor)); 71 } 72 compoundEdit.addEdit(new UndoLineEdit(buffer, line)); 73 line.setText(newText); 74 } 75 } 76 if (compoundEdit != null) { 77 compoundEdit.end(); 78 buffer.addEdit(compoundEdit); 79 buffer.modified(); 80 } 81 buffer.setNeedsParsing(true); 82 buffer.getFormatter().parseBuffer(); 83 buffer.repaint(); 84 } 85 86 private static class SortLinesComparator implements Comparator 87 { 88 SortLinesComparator() {} 89 90 public final int compare(Object o1, Object o2) 91 { 92 return ((String )o1).compareTo((String )o2); 93 } 94 } 95 } 96 | Popular Tags |