01: /*
02: * Sort.java
03: *
04: * Copyright (C) 2002-2004 Peter Graves
05: * $Id: Sort.java,v 1.2 2004/06/06 04:38:27 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
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: public static void sortLines() {
31: final Editor editor = Editor.currentEditor();
32: if (editor.getMark() == null)
33: return;
34: final Region region = new Region(editor);
35: if (region.getEndLineNumber() - region.getBeginLineNumber() < 2)
36: return;
37: if (!editor.checkReadOnly())
38: return;
39: final Buffer buffer = editor.getBuffer();
40: try {
41: buffer.lockWrite();
42: } catch (InterruptedException e) {
43: Log.error(e);
44: return;
45: }
46: try {
47: sortLinesInternal(editor, buffer, region);
48: } finally {
49: buffer.unlockWrite();
50: }
51: }
52:
53: private static void sortLinesInternal(Editor editor, Buffer buffer,
54: Region region) {
55: ArrayList arrayList = new ArrayList();
56: for (Line line = region.getBeginLine(); line != region
57: .getEndLine(); line = line.next())
58: arrayList.add(line.getText());
59: Collections.sort(arrayList, new SortLinesComparator());
60: CompoundEdit compoundEdit = null;
61: int i = 0;
62: for (Line line = region.getBeginLine(); line != region
63: .getEndLine(); line = line.next(), i++) {
64: String newText = (String) arrayList.get(i);
65: if (!newText.equals(line.getText())) {
66: if (compoundEdit == null) {
67: compoundEdit = new CompoundEdit();
68: compoundEdit.addEdit(new UndoMove(editor));
69: }
70: compoundEdit.addEdit(new UndoLineEdit(buffer, line));
71: line.setText(newText);
72: }
73: }
74: if (compoundEdit != null) {
75: compoundEdit.end();
76: buffer.addEdit(compoundEdit);
77: buffer.modified();
78: }
79: buffer.setNeedsParsing(true);
80: buffer.getFormatter().parseBuffer();
81: buffer.repaint();
82: }
83:
84: private static class SortLinesComparator implements Comparator {
85: SortLinesComparator() {
86: }
87:
88: public final int compare(Object o1, Object o2) {
89: return ((String) o1).compareTo((String) o2);
90: }
91: }
92: }
|