01: /*
02: * TextIndenter.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.gui.editor;
13:
14: import javax.swing.text.BadLocationException;
15: import workbench.log.LogMgr;
16:
17: /**
18: *
19: * @author support@sql-workbench.net
20: */
21: public class TextIndenter {
22: private JEditTextArea editor;
23:
24: public TextIndenter(JEditTextArea client) {
25: this .editor = client;
26: }
27:
28: public void indentSelection() {
29: this .shiftSelection(true);
30: }
31:
32: public void unIndentSelection() {
33: this .shiftSelection(false);
34: }
35:
36: private void shiftSelection(boolean indent) {
37: int startline = editor.getSelectionStartLine();
38: int realEndline = editor.getSelectionEndLine();
39: int endline = realEndline;
40: int tabSize = editor.getTabSize();
41: StringBuilder buff = new StringBuilder(tabSize);
42: for (int i = 0; i < tabSize; i++)
43: buff.append(' ');
44: String spacer = buff.toString();
45:
46: int pos = editor.getSelectionEnd(endline)
47: - editor.getLineStartOffset(endline);
48: if (pos == 0)
49: endline--;
50: SyntaxDocument document = editor.getDocument();
51:
52: try {
53: document.beginCompoundEdit();
54: for (int line = startline; line <= endline; line++) {
55: String text = editor.getLineText(line);
56: if (text == null || text.trim().length() == 0)
57: continue;
58: int lineStart = editor.getLineStartOffset(line);
59: if (indent) {
60: document.insertString(lineStart, spacer, null);
61: } else {
62: char c = text.charAt(0);
63: if (c == '\t') {
64: document.remove(lineStart, 1);
65: } else {
66: int numChars = 0;
67: while (Character.isWhitespace(text
68: .charAt(numChars))
69: && numChars < tabSize)
70: numChars++;
71: document.remove(lineStart, numChars);
72: }
73: }
74: }
75: } catch (BadLocationException e) {
76: LogMgr.logError("TextIndenter.shiftSelection()",
77: "Error when shifting selection", e);
78: } finally {
79: document.endCompoundEdit();
80: }
81: }
82:
83: }
|