diff --git a/src/me/ByteEdit/edit/Assembler.java b/src/me/ByteEdit/edit/Assembler.java index 92ef725..7b3aea2 100644 --- a/src/me/ByteEdit/edit/Assembler.java +++ b/src/me/ByteEdit/edit/Assembler.java @@ -49,7 +49,7 @@ import me.ByteEdit.utils.SwitchIntContainer; import me.ByteEdit.utils.UnicodeUtils; public class Assembler { - + public static ClassNode assemble(String input) { Main.txtByteEditView.removeAllLineHighlights(); CustomBufferedReader read = null; @@ -79,9 +79,9 @@ public class Assembler { clazz.innerClasses = new ArrayList<>(); } else { String split[] = s.split(" "); - clazz.innerClasses.add(new InnerClassNode(UnicodeUtils.unescape(split[1]), - split[2].equals("null") ? null : UnicodeUtils.unescape(split[2]), - split[3].equals("null") ? null : UnicodeUtils.unescape(split[3]), Integer.parseInt(split[4].substring(2), 16))); + clazz.innerClasses + .add(new InnerClassNode(UnicodeUtils.unescape(split[1]), split[2].equals("null") ? null : UnicodeUtils.unescape(split[2]), + split[3].equals("null") ? null : UnicodeUtils.unescape(split[3]), Integer.parseInt(split[4].substring(2), 16))); } } { @@ -297,9 +297,8 @@ public class Assembler { _end = new LabelNode(entry.getKey()); } } - node.localVariables - .add(new LocalVariableNode(sp[0], UnicodeUtils.unescape(sp[1].substring(1, sp[1].length() - 2)), signat, - _start, _end, Integer.parseInt(sp[2].substring(0, sp[2].length() - 2)))); + node.localVariables.add(new LocalVariableNode(sp[0], UnicodeUtils.unescape(sp[1].substring(1, sp[1].length() - 2)), + signat, _start, _end, Integer.parseInt(sp[2].substring(0, sp[2].length() - 2)))); } for (String st : tryCatchBlocksToParse) { String[] sp = st.split(" "); @@ -320,8 +319,8 @@ public class Assembler { _handler = new LabelNode(entry.getKey()); } } - node.tryCatchBlocks.add(new TryCatchBlockNode(_start, _end, _handler, - sp[0].equals("null") ? null : UnicodeUtils.unescape(sp[0]))); + node.tryCatchBlocks + .add(new TryCatchBlockNode(_start, _end, _handler, sp[0].equals("null") ? null : UnicodeUtils.unescape(sp[0]))); } clazz.methods.add(node); // signature = null; @@ -432,7 +431,7 @@ public class Assembler { } catch (Exception e) {} } } - + private static AnnotationNode parseAnnotation(String s) { s = s.substring(1); String[] split = s.split(" "); @@ -482,7 +481,7 @@ public class Assembler { } return node; } - + private static String consolidateStrings(String[] args, int start) { if (args.length == 0) { return null; @@ -495,7 +494,7 @@ public class Assembler { } return ret; } - + private static String consolidateStrings(String[] args, int start, int end) { if (end == 0) { return null; @@ -508,7 +507,7 @@ public class Assembler { } return ret; } - + private static Object getValue(String s, String to) { if (s == null) { return null; @@ -537,7 +536,7 @@ public class Assembler { } } } - + private static AbstractInsnNode getNode(String s, HashMap labels) throws Exception { if (s.startsWith("// label ")) { int labelNr = Integer.parseInt(s.substring(9)); @@ -643,8 +642,8 @@ public class Assembler { } } } - return new FrameNode(Integer.parseInt(str1.split(" ")[0]), local != null ? local.length : 0, local, - stack != null ? stack.length : 0, stack); + return new FrameNode(Integer.parseInt(str1.split(" ")[0]), local != null ? local.length : 0, local, stack != null ? stack.length : 0, + stack); } else { String[] split = s.split(" "); String command = split[0]; @@ -694,12 +693,12 @@ public class Assembler { if (str.startsWith("Type: ")) { str = str.substring(8, str.length() - 2); String[] split2 = str.split("\n\t"); - Constructor constr = Type.class.getDeclaredConstructor(int.class, char[].class, int.class, int.class); + Constructor constr = Type.class.getDeclaredConstructor(int.class, String.class, int.class, int.class); constr.setAccessible(true); String type = split2[0].substring(7); - val = constr.newInstance(new Object[] { ClassUtil.getIDFromClassNameForType(type), - split2[3].substring(6, split2[3].length() - 1).toCharArray(), Integer.parseInt(split2[1].substring(5)), - Integer.parseInt(split2[2].substring(5)) }); + val = constr.newInstance( + new Object[] { ClassUtil.getIDFromClassNameForType(type), split2[3].substring(6, split2[3].length() - 1), + Integer.parseInt(split2[1].substring(7)), Integer.parseInt(split2[2].substring(5)) }); } else if (str.startsWith("\"") && str.endsWith("\"")) { val = UnicodeUtils.unescape(str.substring(1, str.length() - 1)); } else if (str.endsWith("l")) { @@ -1193,7 +1192,7 @@ public class Assembler { labelIDs.put(BigInteger.valueOf(dfltLabelNr), dflt); } labelMap.replaceAll(new BiFunction() { - + @Override public LabelNode apply(SwitchIntContainer t, LabelNode u) { if (entry.getValue().intValue() == t.getId()) { @@ -1201,7 +1200,7 @@ public class Assembler { } return u; } - + }); } if (dflt == null) { @@ -1226,8 +1225,7 @@ public class Assembler { arr[counter] = ln; counter++; } - return new TableSwitchInsnNode(Integer.parseInt(split2[0].substring(5)), Integer.parseInt(split2[1].substring(5)), dflt, - arr); + return new TableSwitchInsnNode(Integer.parseInt(split2[0].substring(5)), Integer.parseInt(split2[1].substring(5)), dflt, arr); } case "lookupswitch": { String str = s.substring(15, s.length() - 2).replace("\t", ""); @@ -1260,7 +1258,7 @@ public class Assembler { labelIDs.put(BigInteger.valueOf(labelNr), dflt); } labelMap.replaceAll(new BiFunction() { - + @Override public LabelNode apply(SwitchIntContainer t, LabelNode u) { if (entry.getValue().intValue() == t.getId()) { @@ -1268,7 +1266,7 @@ public class Assembler { } return u; } - + }); } if (dflt == null) { @@ -1375,19 +1373,18 @@ public class Assembler { if (st.equals("]")) { if (stage == 1) { try { - Constructor constr = Type.class.getDeclaredConstructor(int.class, char[].class, int.class, - int.class); + Constructor constr = Type.class.getDeclaredConstructor(int.class, String.class, int.class, int.class); constr.setAccessible(true); args.add(constr.newInstance(new Object[] { Integer.parseInt(vals.get(0).substring(6)), - UnicodeUtils.unescape(vals.get(3).substring(6, vals.get(3).length() - 1)).toCharArray(), - Integer.parseInt(vals.get(1).substring(5)), Integer.parseInt(vals.get(2).substring(5)) })); + UnicodeUtils.unescape(vals.get(3).substring(6, vals.get(3).length() - 1)), + Integer.parseInt(vals.get(1).substring(7)), Integer.parseInt(vals.get(2).substring(5)) })); } catch (Exception e) { throw e; } } else if (stage == 2) { - args.add(new Handle(Integer.parseInt(vals.get(4).substring(5)), - UnicodeUtils.unescape(vals.get(1).substring(7)), UnicodeUtils.unescape(vals.get(0).substring(6)), - UnicodeUtils.unescape(vals.get(2).substring(6)), Boolean.parseBoolean(vals.get(3).substring(13)))); + args.add(new Handle(Integer.parseInt(vals.get(4).substring(5)), UnicodeUtils.unescape(vals.get(1).substring(7)), + UnicodeUtils.unescape(vals.get(0).substring(6)), UnicodeUtils.unescape(vals.get(2).substring(6)), + Boolean.parseBoolean(vals.get(3).substring(13)))); vals.clear(); } stage = 0; diff --git a/src/me/ByteEdit/edit/Disassembler.java b/src/me/ByteEdit/edit/Disassembler.java index 5219d35..bc5e43d 100644 --- a/src/me/ByteEdit/edit/Disassembler.java +++ b/src/me/ByteEdit/edit/Disassembler.java @@ -40,36 +40,36 @@ import me.ByteEdit.utils.OpcodesReverse; import me.ByteEdit.utils.UnicodeUtils; public class Disassembler { - + public static String disassemble(ClassNode classNode) { return disassemble(classNode, null).getDisassembly(); } - + public static class DisassembleTuple { - + private final String dis; private final int line; - + public DisassembleTuple(String dis) { this.dis = dis; this.line = -1; } - + public DisassembleTuple(String dis, int line) { this.dis = dis; this.line = line; } - + public String getDisassembly() { return dis; } - + public int getLine() { return line; } - + } - + public static DisassembleTuple disassemble(ClassNode classNode, MethodNode methodToFind) { if (classNode == null) { return new DisassembleTuple("ClassNode is null! This is not a valid java class file!"); @@ -139,8 +139,10 @@ public class Disassembler { } s += "// #Class v:" + classNode.version + "\n"; s += "// #Signature: " + UnicodeUtils.escapeWithSpaces(classNode.signature) + "\n"; - s += "// #OuterMethod: " + (classNode.outerMethod == null ? "null" : (UnicodeUtils.escapeWithSpaces(classNode.outerMethod) + " " - + UnicodeUtils.escapeWithSpaces(classNode.outerMethodDesc))) + "\n"; + s += "// #OuterMethod: " + + (classNode.outerMethod == null ? "null" + : (UnicodeUtils.escapeWithSpaces(classNode.outerMethod) + " " + UnicodeUtils.escapeWithSpaces(classNode.outerMethodDesc))) + + "\n"; s += "// #OuterClass: " + UnicodeUtils.escapeWithSpaces(classNode.outerClass) + "\n"; s += "// #InnerClasses:\n"; if (classNode.innerClasses != null) { @@ -163,8 +165,7 @@ public class Disassembler { if (!interfaceStr.isEmpty()) s += "implements " + interfaceStr + " "; } - s += "{\n// #SourceFile: " + (classNode.sourceFile == null ? "null" : UnicodeUtils.escape(classNode.sourceFile)) - + "\n\n// #Fields\n"; + s += "{\n// #SourceFile: " + (classNode.sourceFile == null ? "null" : UnicodeUtils.escape(classNode.sourceFile)) + "\n\n// #Fields\n"; for (FieldNode fn : classNode.fields) { if (fn.signature != null) s += "\t// #Signature: " + UnicodeUtils.escapeWithSpaces(fn.signature) + "\n"; @@ -227,8 +228,8 @@ public class Disassembler { s += "\n"; } } - s += "\t" + ClassUtil.getAccessFlagsFull(fn.access).replace("varargs", "transient") + UnicodeUtils.escapeWithSpaces(fn.desc) - + " " + UnicodeUtils.escapeWithSpaces(fn.name); + s += "\t" + ClassUtil.getAccessFlagsFull(fn.access).replace("varargs", "transient") + UnicodeUtils.escapeWithSpaces(fn.desc) + " " + + UnicodeUtils.escapeWithSpaces(fn.name); if (fn.value != null) { s += " = " + ClassUtil.getDecompiledValue(fn.value, fn.desc, true); } @@ -323,8 +324,8 @@ public class Disassembler { s += dis[0]; s += "\t}\n\n"; } catch (Exception e) { - s += "\t\t// Method couldn't be disassembled:\n\t\t// " + e.getClass().getName() + ": " + e.getMessage() + "\n" + Arrays - .toString(e.getStackTrace()).replace(", ", "\n\t\t// \tat ").replace("[", "\t\t// \tat ").replace("]", "") + s += "\t\t// Method couldn't be disassembled:\n\t\t// " + e.getClass().getName() + ": " + e.getMessage() + "\n" + + Arrays.toString(e.getStackTrace()).replace(", ", "\n\t\t// \tat ").replace("[", "\t\t// \tat ").replace("]", "") + "\n\t}\n\n"; } } @@ -335,7 +336,7 @@ public class Disassembler { + Arrays.toString(e.getStackTrace()).replace(", ", "\n\tat ").replace("[", "\tat ").replace("]", "") + "\n"); } } - + private static String[] disassembleMethod(String className, MethodNode mn) { HashMap labels = new HashMap(); String s = ""; @@ -364,7 +365,7 @@ public class Disassembler { } return new String[] { s, localVarTable, tryCatchTable }; } - + public static String disassembleInstruction(AbstractInsnNode n, HashMap labels) { switch (n.getClass().getSimpleName()) { case "FieldInsnNode": { @@ -427,38 +428,36 @@ public class Disassembler { } case "InvokeDynamicInsnNode": { InvokeDynamicInsnNode node = (InvokeDynamicInsnNode) n; - String s = "\t\t" + OpcodesReverse.reverseOpcode(node.getOpcode()) + " [\n\t\t\tname: " - + UnicodeUtils.escapeWithSpaces(node.name) + "\n\t\t\tdesc: " + UnicodeUtils.escapeWithSpaces(node.desc) - + "\n\t\t\tHandle: [\n\t\t\t\tname: " + UnicodeUtils.escapeWithSpaces(node.bsm.getName()) + "\n\t\t\t\towner: " - + UnicodeUtils.escapeWithSpaces(node.bsm.getOwner()) + "\n\t\t\t\tdesc: " - + UnicodeUtils.escapeWithSpaces(node.bsm.getDesc()) + "\n\t\t\t\tisInterface: " + node.bsm.isInterface() + String s = "\t\t" + OpcodesReverse.reverseOpcode(node.getOpcode()) + " [\n\t\t\tname: " + UnicodeUtils.escapeWithSpaces(node.name) + + "\n\t\t\tdesc: " + UnicodeUtils.escapeWithSpaces(node.desc) + "\n\t\t\tHandle: [\n\t\t\t\tname: " + + UnicodeUtils.escapeWithSpaces(node.bsm.getName()) + "\n\t\t\t\towner: " + UnicodeUtils.escapeWithSpaces(node.bsm.getOwner()) + + "\n\t\t\t\tdesc: " + UnicodeUtils.escapeWithSpaces(node.bsm.getDesc()) + "\n\t\t\t\tisInterface: " + node.bsm.isInterface() + "\n\t\t\t\ttag: " + node.bsm.getTag() + "\n\t\t\t]\n\t\t\targs: [\n"; for (Object l : node.bsmArgs) { if (l.getClass().getName().equals("org.objectweb.asm.Type")) { Type type = (Type) l; - int off = 0; - int len = 0; - char[] buf = null; + int valueBegin = 0; + int valueEnd = 0; + String buf = null; try { - Field f_off = Type.class.getDeclaredField("off"); + Field f_off = Type.class.getDeclaredField("valueBegin"); f_off.setAccessible(true); - off = f_off.getInt(type); - Field f_len = Type.class.getDeclaredField("len"); + valueBegin = f_off.getInt(type); + Field f_len = Type.class.getDeclaredField("valueEnd"); f_len.setAccessible(true); - len = f_len.getInt(type); - Field f_buf = Type.class.getDeclaredField("buf"); + valueEnd = f_len.getInt(type); + Field f_buf = Type.class.getDeclaredField("valueBuffer"); f_buf.setAccessible(true); - buf = (char[]) f_buf.get(type); + buf = (String) f_buf.get(type); } catch (Exception e) {} - s += "\t\t\t\tType: [\n\t\t\t\t\ttype: " + ClassUtil.getClassNameFromType(type) + "\n\t\t\t\t\toff: " + off - + "\n\t\t\t\t\tlen: " + len + "\n\t\t\t\t\tbuf: " + ClassUtil.getDecompiledValue(new String(buf), ""); + s += "\t\t\t\tType: [\n\t\t\t\t\ttype: " + ClassUtil.getClassNameFromType(type) + "\n\t\t\t\t\tstart: " + valueBegin + + "\n\t\t\t\t\tend: " + valueEnd + "\n\t\t\t\t\tbuf: " + ClassUtil.getDecompiledValue(buf, ""); s += "\n\t\t\t\t]\n"; } else if (l.getClass().getName().equals("org.objectweb.asm.Handle")) { Handle h = (Handle) l; s += "\t\t\t\tHandle: [\n\t\t\t\t\tname: " + UnicodeUtils.escapeWithSpaces(h.getName()) + "\n\t\t\t\t\towner: " - + UnicodeUtils.escapeWithSpaces(h.getOwner()) + "\n\t\t\t\t\tdesc: " - + UnicodeUtils.escapeWithSpaces(h.getDesc()) + "\n\t\t\t\t\tisInterface: " + h.isInterface() - + "\n\t\t\t\t\ttag: " + h.getTag(); + + UnicodeUtils.escapeWithSpaces(h.getOwner()) + "\n\t\t\t\t\tdesc: " + UnicodeUtils.escapeWithSpaces(h.getDesc()) + + "\n\t\t\t\t\tisInterface: " + h.isInterface() + "\n\t\t\t\t\ttag: " + h.getTag(); s += "\n\t\t\t\t]\n"; } else { s += "\t\t\t\t" + ClassUtil.getDecompiledValue(l, "") + "\n"; @@ -478,8 +477,8 @@ public class Disassembler { } case "MultiANewArrayInsnNode": { MultiANewArrayInsnNode node = (MultiANewArrayInsnNode) n; - return "\t\t" + OpcodesReverse.reverseOpcode(node.getOpcode()) + " " + UnicodeUtils.escapeWithSpaces(node.desc) + " " - + node.dims + "\n"; + return "\t\t" + OpcodesReverse.reverseOpcode(node.getOpcode()) + " " + UnicodeUtils.escapeWithSpaces(node.desc) + " " + node.dims + + "\n"; } case "LdcInsnNode": { LdcInsnNode node = (LdcInsnNode) n; @@ -489,28 +488,27 @@ public class Disassembler { case "Integer": case "Float": case "Long": { - return "\t\t" + OpcodesReverse.reverseOpcode(node.getOpcode()) + " " + ClassUtil.getDecompiledValue(node.cst, "") - + "\n"; + return "\t\t" + OpcodesReverse.reverseOpcode(node.getOpcode()) + " " + ClassUtil.getDecompiledValue(node.cst, "") + "\n"; } case "Type": { Type type = (Type) node.cst; - int off = 0; - int len = 0; - char[] buf = null; + int valueBegin = 0; + int valueEnd = 0; + String buf = null; try { - Field f_off = Type.class.getDeclaredField("off"); + Field f_off = Type.class.getDeclaredField("valueBegin"); f_off.setAccessible(true); - off = f_off.getInt(type); - Field f_len = Type.class.getDeclaredField("len"); + valueBegin = f_off.getInt(type); + Field f_len = Type.class.getDeclaredField("valueEnd"); f_len.setAccessible(true); - len = f_len.getInt(type); - Field f_buf = Type.class.getDeclaredField("buf"); + valueEnd = f_len.getInt(type); + Field f_buf = Type.class.getDeclaredField("valueBuffer"); f_buf.setAccessible(true); - buf = (char[]) f_buf.get(type); + buf = (String) f_buf.get(type); } catch (Exception e) {} String s = "\t\t" + OpcodesReverse.reverseOpcode(n.getOpcode()) + " Type: [\n\t\t\ttype: " - + ClassUtil.getClassNameFromType(type) + "\n\t\t\toff: " + off + "\n\t\t\tlen: " + len + "\n\t\t\tbuf: " - + ClassUtil.getDecompiledValue(new String(buf), ""); + + ClassUtil.getClassNameFromType(type) + "\n\t\t\tstart: " + valueBegin + "\n\t\t\tend: " + valueEnd + "\n\t\t\tbuf: " + + ClassUtil.getDecompiledValue(buf, ""); s += "\n\t\t]\n"; return s; } @@ -572,5 +570,5 @@ public class Disassembler { return "\t\tNOT HANDLED! " + OpcodesReverse.reverseOpcode(n.getOpcode()) + " " + n.getClass().getSimpleName() + "\n"; } } - + } diff --git a/src/me/ByteEdit/main/Main.java b/src/me/ByteEdit/main/Main.java index 65b395b..a810219 100644 --- a/src/me/ByteEdit/main/Main.java +++ b/src/me/ByteEdit/main/Main.java @@ -81,7 +81,7 @@ import me.ByteEdit.utils.OpcodesReverse; import me.ByteEdit.utils.UnicodeUtils; public class Main extends JFrame { - + public static Main INSTANCE; private JPanel contentPane; private boolean isChangingFile; @@ -97,13 +97,13 @@ public class Main extends JFrame { public static JTree tree; public static RTextScrollPane scrollPane_ByteEdit; public static Theme theme; - + /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { - + public void run() { try { Main frame = new Main(); @@ -114,7 +114,7 @@ public class Main extends JFrame { } }); } - + /** * Create a simple provider that adds some Java-related completions. */ @@ -159,7 +159,7 @@ public class Main extends JFrame { "method
Creates an example method")); return provider; } - + /** * Create the frame. */ @@ -200,7 +200,7 @@ public class Main extends JFrame { } tree = new JTree(new DefaultTreeModel(null)); tree.addKeyListener(new KeyAdapter() { - + @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == 116 && jarFile != null) { @@ -230,7 +230,7 @@ public class Main extends JFrame { } scrollPane.setViewportView(tree); tree.addTreeSelectionListener(new TreeSelectionListener() { - + public void valueChanged(TreeSelectionEvent e) { if (!isChangingFile) { String s = ""; @@ -248,7 +248,7 @@ public class Main extends JFrame { } }); new DropTarget(tree, new DropTargetListener() { - + @Override public void drop(DropTargetDropEvent dtde) { try { @@ -279,25 +279,25 @@ public class Main extends JFrame { } dtde.rejectDrop(); } - + @Override public void dragEnter(DropTargetDragEvent dtde) {} - + @Override public void dragOver(DropTargetDragEvent dtde) {} - + @Override public void dropActionChanged(DropTargetDragEvent dtde) {} - + @Override public void dragExit(DropTargetEvent dte) {} }); - + txtByteEditView = new RSyntaxTextArea(); ac.install(txtByteEditView); txtByteEditView.setCodeFoldingEnabled(true); txtByteEditView.addKeyListener(new KeyAdapter() { - + @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == 116 && currentNodeName != null) { @@ -328,7 +328,7 @@ public class Main extends JFrame { KeyStroke ctrlU = KeyStroke.getKeyStroke(KeyEvent.VK_U, KeyEvent.CTRL_DOWN_MASK); // global txtByteEditView.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { searchBox.setVisible(true); @@ -337,7 +337,7 @@ public class Main extends JFrame { } }, ctrlF, JComponent.WHEN_IN_FOCUSED_WINDOW); txtByteEditView.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { typeOpenBox.setVisible(true); @@ -346,14 +346,14 @@ public class Main extends JFrame { } }, ctrlT, JComponent.WHEN_IN_FOCUSED_WINDOW); txtByteEditView.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { optionBox.setVisible(true); } }, ctrlO, JComponent.WHEN_IN_FOCUSED_WINDOW); txtByteEditView.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { unicodeBox.setVisible(true); @@ -361,21 +361,21 @@ public class Main extends JFrame { }, ctrlU, JComponent.WHEN_IN_FOCUSED_WINDOW); // specific tree.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { save(); } }, ctrlS, JComponent.WHEN_FOCUSED); txtByteEditView.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { saveCurrentClassNode(); } }, ctrlS, JComponent.WHEN_FOCUSED); txtByteEditView.registerKeyboardAction(new ActionListener() { - + @Override public void actionPerformed(ActionEvent e) { try { @@ -395,7 +395,7 @@ public class Main extends JFrame { } catch (IOException e2) { e2.printStackTrace(); } - + splitPane.setRightComponent(scrollPane_ByteEdit); txtByteEditView.setBackground(Color.LIGHT_GRAY); scrollPane_ByteEdit.setViewportView(txtByteEditView); @@ -403,9 +403,9 @@ public class Main extends JFrame { scrollPane_ByteEdit.setFoldIndicatorEnabled(true); scrollPane_ByteEdit.getGutter().setBackground(Color.LIGHT_GRAY); } - + private final Pattern jumpableInstructionPattern = Pattern.compile("^\t\t(?!//|\t+).+ .+"); - + public void goToSelected() throws BadLocationException { int lineStart = txtByteEditView.getLineStartOffsetOfCurrentLine(); int lineEnd = txtByteEditView.getLineEndOffsetOfCurrentLine() - 1; @@ -447,7 +447,7 @@ public class Main extends JFrame { selectFile(className + ".class"); } } - + private void saveCurrentClassNode() { String txt = txtByteEditView.getText(); for (String s : txt.split("\\/\\/ #Annotations\n")) { @@ -462,7 +462,7 @@ public class Main extends JFrame { } } } - + public static int selectFileWithSearch(String s, MethodNode methodToFind) { if (s.endsWith(".class")) { currentNodeName = s; @@ -493,16 +493,16 @@ public class Main extends JFrame { } return -1; } - + public static int selectFile(String s) { return selectFileWithSearch(s, null); } - + public static File saveFolder = null; - + public void save() { final JFileChooser fileChooser = new JFileChooser(saveFolder) { - + @Override protected JDialog createDialog(final Component parent) throws HeadlessException { final JDialog dialog = super.createDialog(parent); @@ -529,7 +529,7 @@ public class Main extends JFrame { } } } - + public void save(File jar, Collection classes) { try { final JarOutputStream output = new JarOutputStream(new FileOutputStream(jar)); @@ -586,7 +586,7 @@ public class Main extends JFrame { showError(e); } } - + public static void showError(Throwable e) { String s = e.toString() + "\n"; StackTraceElement[] stackTrace = e.getStackTrace(); @@ -596,19 +596,16 @@ public class Main extends JFrame { s += "\tat " + ste + "\n"; } } - + public static void showError(String s) { JOptionPane.showMessageDialog(INSTANCE, s, "Error!", JOptionPane.ERROR_MESSAGE); } - + class ArchiveTreeModel extends DefaultTreeModel { - + public ArchiveTreeModel(JarFile jar) { - super(new DefaultMutableTreeNode( - jar.getName() - .split(File.separator.equals("\\") ? "\\\\" - : File.separator)[jar.getName().split(File.separator.equals("\\") ? "\\\\" : File.separator).length - - 1])); + super(new DefaultMutableTreeNode(jar.getName().split(File.separator.equals("\\") ? "\\\\" + : File.separator)[jar.getName().split(File.separator.equals("\\") ? "\\\\" : File.separator).length - 1])); try { ArrayList paths = new ArrayList<>(); classNodes.clear(); @@ -662,7 +659,7 @@ public class Main extends JFrame { showError(e); } } - + private DefaultMutableTreeNode findNode(DefaultMutableTreeNode parent, String name) { Enumeration e = parent.children(); while (e.hasMoreElements()) { diff --git a/src/org/fife/io/UnicodeReader.java b/src/org/fife/io/UnicodeReader.java index 8ff183e..fba3da0 100644 --- a/src/org/fife/io/UnicodeReader.java +++ b/src/org/fife/io/UnicodeReader.java @@ -25,8 +25,8 @@ import java.io.Reader; *
  • UTF-32LE *
  • UTF-32BE * - * If the stream is not found to be any of the above, then a default encoding - * is used for reading. The user can specify this default encoding, or a system + * If the stream is not found to be any of the above, then a default encoding is + * used for reading. The user can specify this default encoding, or a system * default will be used. *

    * @@ -40,121 +40,101 @@ import java.io.Reader; * @author Robert Futrell * @version 0.9 */ -@SuppressWarnings({ "checkstyle:magicnumber" }) public class UnicodeReader extends Reader { - + /** * The input stream from which we're really reading. */ private InputStreamReader internalIn = null; /** - * The encoding being used. We keep our own instead of using the string - * returned by java.io.InputStreamReader since that class - * does not return user-friendly names. + * The encoding being used. We keep our own instead of using the string returned + * by java.io.InputStreamReader since that class does not return + * user-friendly names. */ private String encoding; /** * The size of a BOM. */ private static final int BOM_SIZE = 4; - + /** * This utility constructor is here because you will usually use a * UnicodeReader on files. *

    - * Creates a reader using the encoding specified by the BOM in the file; - * if there is no recognized BOM, then a system default encoding is used. + * Creates a reader using the encoding specified by the BOM in the file; if + * there is no recognized BOM, then a system default encoding is used. * - * @param file - * The file from which you want to read. - * @throws IOException - * If an error occurs when checking for/reading the - * BOM. - * @throws SecurityException - * If a security manager exists and its - * checkRead method denies read access to the file. + * @param file The file from which you want to read. + * @throws IOException If an error occurs when checking for/reading the + * BOM. + * @throws SecurityException If a security manager exists and its checkRead + * method denies read access to the file. */ public UnicodeReader(String file) throws IOException { this(new File(file)); } - + /** * This utility constructor is here because you will usually use a * UnicodeReader on files. *

    - * Creates a reader using the encoding specified by the BOM in the file; - * if there is no recognized BOM, then a system default encoding is used. + * Creates a reader using the encoding specified by the BOM in the file; if + * there is no recognized BOM, then a system default encoding is used. * - * @param file - * The file from which you want to read. - * @throws IOException - * If an error occurs when checking for/reading the - * BOM. - * @throws SecurityException - * If a security manager exists and its - * checkRead method denies read access to the file. + * @param file The file from which you want to read. + * @throws IOException If an error occurs when checking for/reading the + * BOM. + * @throws SecurityException If a security manager exists and its checkRead + * method denies read access to the file. */ public UnicodeReader(File file) throws IOException { this(new FileInputStream(file)); } - + /** * This utility constructor is here because you will usually use a * UnicodeReader on files. *

    - * Creates a reader using the encoding specified by the BOM in the file; - * if there is no recognized BOM, then a specified default encoding is - * used. + * Creates a reader using the encoding specified by the BOM in the file; if + * there is no recognized BOM, then a specified default encoding is used. * - * @param file - * The file from which you want to read. - * @param defaultEncoding - * The encoding to use if no BOM is found. If - * this value is null, a system default is used. - * @throws IOException - * If an error occurs when checking for/reading the - * BOM. - * @throws SecurityException - * If a security manager exists and its - * checkRead method denies read access to the file. + * @param file The file from which you want to read. + * @param defaultEncoding The encoding to use if no BOM is found. If this value + * is null, a system default is used. + * @throws IOException If an error occurs when checking for/reading the + * BOM. + * @throws SecurityException If a security manager exists and its checkRead + * method denies read access to the file. */ public UnicodeReader(File file, String defaultEncoding) throws IOException { this(new FileInputStream(file), defaultEncoding); } - + /** - * Creates a reader using the encoding specified by the BOM in the file; - * if there is no recognized BOM, then a system default encoding is used. + * Creates a reader using the encoding specified by the BOM in the file; if + * there is no recognized BOM, then a system default encoding is used. * - * @param in - * The input stream from which to read. - * @throws IOException - * If an error occurs when checking for/reading the - * BOM. + * @param in The input stream from which to read. + * @throws IOException If an error occurs when checking for/reading the BOM. */ public UnicodeReader(InputStream in) throws IOException { this(in, null); } - + /** - * Creates a reader using the encoding specified by the BOM in the file; - * if there is no recognized BOM, then defaultEncoding is - * used. + * Creates a reader using the encoding specified by the BOM in the file; if + * there is no recognized BOM, then defaultEncoding is used. * - * @param in - * The input stream from which to read. - * @param defaultEncoding - * The encoding to use if no recognized BOM is - * found. If this value is null, a system default - * is used. - * @throws IOException - * If an error occurs when checking for/reading the - * BOM. + * @param in The input stream from which to read. + * @param defaultEncoding The encoding to use if no recognized BOM is found. If + * this value is null, a system default is + * used. + * @throws IOException If an error occurs when checking for/reading the BOM. */ public UnicodeReader(InputStream in, String defaultEncoding) throws IOException { init(in, defaultEncoding); } - + /** * Closes this reader. */ @@ -162,29 +142,27 @@ public class UnicodeReader extends Reader { public void close() throws IOException { internalIn.close(); } - + /** - * Returns the encoding being used to read this input stream (i.e., the - * encoding of the file). If a BOM was recognized, then the specific - * Unicode type is returned; otherwise, either the default encoding passed - * into the constructor or the system default is returned. + * Returns the encoding being used to read this input stream (i.e., the encoding + * of the file). If a BOM was recognized, then the specific Unicode type is + * returned; otherwise, either the default encoding passed into the constructor + * or the system default is returned. * * @return The encoding of the stream. */ public String getEncoding() { return encoding; } - + /** - * Read-ahead four bytes and check for BOM marks. Extra bytes are - * unread back to the stream, only BOM bytes are skipped. + * Read-ahead four bytes and check for BOM marks. Extra bytes are unread back to + * the stream, only BOM bytes are skipped. * - * @param defaultEncoding - * The encoding to use if no BOM was recognized. If - * this value is null, then a system default is - * used. - * @throws IOException - * If an error occurs when trying to read a BOM. + * @param defaultEncoding The encoding to use if no BOM was recognized. If this + * value is null, then a system default is + * used. + * @throws IOException If an error occurs when trying to read a BOM. */ protected void init(InputStream in, String defaultEncoding) throws IOException { PushbackInputStream tempIn = new PushbackInputStream(in, BOM_SIZE); @@ -196,7 +174,8 @@ public class UnicodeReader extends Reader { unread = n - 4; } else if (n == BOM_SIZE && // Last 2 bytes are 0; could be an empty // UTF-16 - (bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) { + (bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00) + && (bom[3] == (byte) 0x00)) { encoding = "UTF-32LE"; unread = n - 4; } else if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) { @@ -226,21 +205,17 @@ public class UnicodeReader extends Reader { internalIn = new InputStreamReader(tempIn, encoding); } } - + /** - * Read characters into a portion of an array. This method will block until - * some input is available, an I/O error occurs, or the end of the stream - * is reached. + * Read characters into a portion of an array. This method will block until some + * input is available, an I/O error occurs, or the end of the stream is reached. * - * @param cbuf - * The buffer into which to read. - * @param off - * The offset at which to start storing characters. - * @param len - * The maximum number of characters to read. + * @param cbuf The buffer into which to read. + * @param off The offset at which to start storing characters. + * @param len The maximum number of characters to read. * - * @return The number of characters read, or -1 if the end - * of the stream has been reached. + * @return The number of characters read, or -1 if the end of the + * stream has been reached. */ @Override public int read(char[] cbuf, int off, int len) throws IOException { diff --git a/src/org/fife/ui/autocomplete/AbstractCompletionProvider.java b/src/org/fife/ui/autocomplete/AbstractCompletionProvider.java index eb51750..90190df 100644 --- a/src/org/fife/ui/autocomplete/AbstractCompletionProvider.java +++ b/src/org/fife/ui/autocomplete/AbstractCompletionProvider.java @@ -15,26 +15,26 @@ import java.util.List; import javax.swing.text.JTextComponent; /** - * A base class for completion providers. {@link Completion}s are kept in - * a sorted list. To get the list of completions that match a given input, - * a binary search is done to find the first matching completion, then all + * A base class for completion providers. {@link Completion}s are kept in a + * sorted list. To get the list of completions that match a given input, a + * binary search is done to find the first matching completion, then all * succeeding completions that also match are also returned. * * @author Robert Futrell * @version 1.0 */ public abstract class AbstractCompletionProvider extends CompletionProviderBase { - + /** - * The completions this provider is aware of. Subclasses should ensure - * that this list is sorted alphabetically (case-insensitively). + * The completions this provider is aware of. Subclasses should ensure that this + * list is sorted alphabetically (case-insensitively). */ protected List completions; /** * Compares a {@link Completion} against a String. */ protected CaseInsensitiveComparator comparator; - + /** * Constructor. */ @@ -43,17 +43,15 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase clearParameterizedCompletionParams(); completions = new ArrayList(); } - + /** * Adds a single completion to this provider. If you are adding multiple - * completions to this provider, for efficiency reasons please consider - * using {@link #addCompletions(List)} instead. + * completions to this provider, for efficiency reasons please consider using + * {@link #addCompletions(List)} instead. * - * @param c - * The completion to add. - * @throws IllegalArgumentException - * If the completion's provider isn't - * this CompletionProvider. + * @param c The completion to add. + * @throws IllegalArgumentException If the completion's provider isn't this + * CompletionProvider. * @see #addCompletions(List) * @see #removeCompletion(Completion) * @see #clear() @@ -62,16 +60,13 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase checkProviderAndAdd(c); Collections.sort(completions); } - + /** * Adds {@link Completion}s to this provider. * - * @param completions - * The completions to add. This cannot be - * null. - * @throws IllegalArgumentException - * If a completion's provider isn't - * this CompletionProvider. + * @param completions The completions to add. This cannot be null. + * @throws IllegalArgumentException If a completion's provider isn't this + * CompletionProvider. * @see #addCompletion(Completion) * @see #removeCompletion(Completion) * @see #clear() @@ -83,12 +78,11 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase } Collections.sort(this.completions); } - + /** * Adds simple completions for a list of words. * - * @param words - * The words. + * @param words The words. * @see BasicCompletion */ protected void addWordCompletions(String[] words) { @@ -98,17 +92,17 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase } Collections.sort(completions); } - + protected void checkProviderAndAdd(Completion c) { if (c.getProvider() != this) { throw new IllegalArgumentException("Invalid CompletionProvider"); } completions.add(c); } - + /** - * Removes all completions from this provider. This does not affect - * the parent CompletionProvider, if there is one. + * Removes all completions from this provider. This does not affect the parent + * CompletionProvider, if there is one. * * @see #addCompletion(Completion) * @see #addCompletions(List) @@ -117,17 +111,15 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase public void clear() { completions.clear(); } - + /** - * Returns a list of Completions in this provider with the - * specified input text. + * Returns a list of Completions in this provider with the specified + * input text. * - * @param inputText - * The input text to search for. - * @return A list of {@link Completion}s, or null if there - * are no matching Completions. + * @param inputText The input text to search for. + * @return A list of {@link Completion}s, or null if there are no + * matching Completions. */ - @SuppressWarnings("unchecked") public List getCompletionByInputText(String inputText) { // Find any entry that matches this input text (there may be > 1). int end = Collections.binarySearch(completions, inputText, comparator); @@ -140,15 +132,15 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase start--; } int count = completions.size(); - while (++end < count && comparator.compare(completions.get(end), inputText) == 0); + while (++end < count && comparator.compare(completions.get(end), inputText) == 0) + ; return completions.subList(start, end); // (inclusive, exclusive) } - + /** * {@inheritDoc} */ @Override - @SuppressWarnings("unchecked") protected List getCompletionsImpl(JTextComponent comp) { List retVal = new ArrayList(); String text = getAlreadyEnteredText(comp); @@ -188,13 +180,12 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase } return retVal; } - + /** - * Removes the specified completion from this provider. This method - * will not remove completions from the parent provider, if there is one. + * Removes the specified completion from this provider. This method will not + * remove completions from the parent provider, if there is one. * - * @param c - * The completion to remove. + * @param c The completion to remove. * @return true if this provider contained the specified * completion. * @see #clear() @@ -210,14 +201,13 @@ public abstract class AbstractCompletionProvider extends CompletionProviderBase completions.remove(index); return true; } - + /** - * A comparator that compares the input text of a {@link Completion} - * against a String lexicographically, ignoring case. + * A comparator that compares the input text of a {@link Completion} against a + * String lexicographically, ignoring case. */ - @SuppressWarnings("rawtypes") public static class CaseInsensitiveComparator implements Comparator, Serializable { - + @Override public int compare(Object o1, Object o2) { String s1 = o1 instanceof String ? (String) o1 : ((Completion) o1).getInputText(); diff --git a/src/org/fife/ui/rsyntaxtextarea/CodeTemplateManager.java b/src/org/fife/ui/rsyntaxtextarea/CodeTemplateManager.java index 896162f..269cad6 100644 --- a/src/org/fife/ui/rsyntaxtextarea/CodeTemplateManager.java +++ b/src/org/fife/ui/rsyntaxtextarea/CodeTemplateManager.java @@ -32,31 +32,30 @@ import org.fife.ui.rsyntaxtextarea.templates.CodeTemplate; * Manages "code templates." *

    * - * All methods in this class are synchronized for thread safety, but as a - * best practice, you should probably only modify the templates known to a + * All methods in this class are synchronized for thread safety, but as a best + * practice, you should probably only modify the templates known to a * CodeTemplateManager on the EDT. Modifying a * CodeTemplate retrieved from a CodeTemplateManager * while not on the EDT could cause problems. *

    * - * For more flexible boilerplate code insertion, consider using the - * * TemplateCompletion class in the - * AutoComplete - * add-on library. + * AutoComplete add-on + * library. * * @author Robert Futrell * @version 1.0 */ public class CodeTemplateManager { - + private int maxTemplateIDLength; private List templates; private Segment s; private TemplateComparator comparator; private File directory; - + /** * Constructor. */ @@ -65,15 +64,13 @@ public class CodeTemplateManager { comparator = new TemplateComparator(); templates = new ArrayList(); } - + /** * Registers the specified template with this template manager. * - * @param template - * The template to register. - * @throws IllegalArgumentException - * If template is - * null. + * @param template The template to register. + * @throws IllegalArgumentException If template is + * null. * @see #removeTemplate(CodeTemplate) * @see #removeTemplate(String) */ @@ -84,13 +81,12 @@ public class CodeTemplateManager { templates.add(template); sortTemplates(); } - + /** - * Returns the template that should be inserted at the current caret - * position, assuming the trigger character was pressed. + * Returns the template that should be inserted at the current caret position, + * assuming the trigger character was pressed. * - * @param textArea - * The text area that's getting text inserted into it. + * @param textArea The text area that's getting text inserted into it. * @return A template that should be inserted, if appropriate, or * null if no template should be inserted. */ @@ -100,7 +96,6 @@ public class CodeTemplateManager { try { Document doc = textArea.getDocument(); doc.getText(caretPos - charsToGet, charsToGet, s); - @SuppressWarnings("unchecked") int index = Collections.binarySearch(templates, s, comparator); return index >= 0 ? (CodeTemplate) templates.get(index) : null; } catch (BadLocationException ble) { @@ -108,7 +103,7 @@ public class CodeTemplateManager { throw new InternalError("Error in CodeTemplateManager"); } } - + /** * Returns the number of templates this manager knows about. * @@ -117,7 +112,7 @@ public class CodeTemplateManager { public synchronized int getTemplateCount() { return templates.size(); } - + /** * Returns the templates currently available. * @@ -127,29 +122,26 @@ public class CodeTemplateManager { CodeTemplate[] temp = new CodeTemplate[templates.size()]; return templates.toArray(temp); } - + /** * Returns whether the specified character is a valid character for a * CodeTemplate id. * - * @param ch - * The character to check. + * @param ch The character to check. * @return Whether the character is a valid template character. */ public static final boolean isValidChar(char ch) { return RSyntaxUtilities.isLetterOrDigit(ch) || ch == '_'; } - + /** * Returns the specified code template. * - * @param template - * The template to remove. - * @return true if the template was removed, false - * if the template was not in this template manager. - * @throws IllegalArgumentException - * If template is - * null. + * @param template The template to remove. + * @return true if the template was removed, false if + * the template was not in this template manager. + * @throws IllegalArgumentException If template is + * null. * @see #removeTemplate(String) * @see #addTemplate(CodeTemplate) */ @@ -160,16 +152,14 @@ public class CodeTemplateManager { // TODO: Do a binary search return templates.remove(template); } - + /** * Returns the code template with the specified id. * - * @param id - * The id to check for. - * @return The code template that was removed, or null if - * there was no template with the specified ID. - * @throws IllegalArgumentException - * If id is null. + * @param id The id to check for. + * @return The code template that was removed, or null if there was + * no template with the specified ID. + * @throws IllegalArgumentException If id is null. * @see #removeTemplate(CodeTemplate) * @see #addTemplate(CodeTemplate) */ @@ -187,14 +177,12 @@ public class CodeTemplateManager { } return null; } - + /** - * Replaces the current set of available templates with the ones - * specified. + * Replaces the current set of available templates with the ones specified. * - * @param newTemplates - * The new set of templates. Note that we will - * be taking a shallow copy of these and sorting them. + * @param newTemplates The new set of templates. Note that we will be taking a + * shallow copy of these and sorting them. */ public synchronized void replaceTemplates(CodeTemplate[] newTemplates) { templates.clear(); @@ -205,7 +193,7 @@ public class CodeTemplateManager { } sortTemplates(); // Also recomputes maxTemplateIDLength. } - + /** * Saves all templates as XML files in the current template directory. * @@ -243,14 +231,13 @@ public class CodeTemplateManager { } return wasSuccessful; } - + /** - * Sets the directory in which to look for templates. Calling this - * method adds any new templates found in the specified directory to - * the templates already registered. + * Sets the directory in which to look for templates. Calling this method adds + * any new templates found in the specified directory to the templates already + * registered. * - * @param dir - * The new directory in which to look for templates. + * @param dir The new directory in which to look for templates. * @return The new number of templates in this template manager, or * -1 if the specified directory does not exist. */ @@ -285,11 +272,10 @@ public class CodeTemplateManager { } return -1; } - + /** - * Removes any null entries in the current set of templates (if - * any), sorts the remaining templates, and computes the new - * maximum template ID length. + * Removes any null entries in the current set of templates (if any), sorts the + * remaining templates, and computes the new maximum template ID length. */ private synchronized void sortTemplates() { // Get the maximum length of a template ID. @@ -307,15 +293,14 @@ public class CodeTemplateManager { } Collections.sort(templates); } - + /** - * A comparator that takes a CodeTemplate as its first - * parameter and a Segment as its second, and knows - * to compare the template's ID to the segment's text. + * A comparator that takes a CodeTemplate as its first parameter + * and a Segment as its second, and knows to compare the template's + * ID to the segment's text. */ - @SuppressWarnings("rawtypes") private static class TemplateComparator implements Comparator, Serializable { - + @Override public int compare(Object template, Object segment) { // Get template start index (0) and length. @@ -345,12 +330,12 @@ public class CodeTemplateManager { return len1 - len2; } } - + /** * A file filter that accepts only XML files. */ private static class XMLFileFilter implements FileFilter { - + @Override public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".xml"); diff --git a/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaDefaultInputMap.java b/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaDefaultInputMap.java index ead25fd..722d204 100644 --- a/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaDefaultInputMap.java +++ b/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaDefaultInputMap.java @@ -15,19 +15,18 @@ import javax.swing.KeyStroke; import org.fife.ui.rtextarea.RTADefaultInputMap; /** - * The default input map for an RSyntaxTextArea. - * Currently, the new key bindings include: + * The default input map for an RSyntaxTextArea. Currently, the new + * key bindings include: *

      - *
    • Shift+Tab indents the current line or currently selected lines - * to the left. + *
    • Shift+Tab indents the current line or currently selected lines to the + * left. *
    * * @author Robert Futrell * @version 1.0 */ -@SuppressWarnings({ "checkstyle:linelength" }) public class RSyntaxTextAreaDefaultInputMap extends RTADefaultInputMap { - + /** * Constructs the default input map for an RSyntaxTextArea. */ @@ -60,18 +59,23 @@ public class RSyntaxTextAreaDefaultInputMap extends RTADefaultInputMap { // (unfortunately) don't have a ToggleCommentAction for *nix // out-of-the-box. // Applications can add one easily enough if they want one. - put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, defaultMod), RSyntaxTextAreaEditorKit.rstaToggleCommentAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, defaultMod), + RSyntaxTextAreaEditorKit.rstaToggleCommentAction); } - put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultMod), RSyntaxTextAreaEditorKit.rstaGoToMatchingBracketAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultMod), + RSyntaxTextAreaEditorKit.rstaGoToMatchingBracketAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, defaultMod), RSyntaxTextAreaEditorKit.rstaCollapseFoldAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, defaultMod), RSyntaxTextAreaEditorKit.rstaExpandFoldAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultMod), RSyntaxTextAreaEditorKit.rstaCollapseAllFoldsAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY, defaultMod), RSyntaxTextAreaEditorKit.rstaExpandAllFoldsAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultMod), + RSyntaxTextAreaEditorKit.rstaCollapseAllFoldsAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY, defaultMod), + RSyntaxTextAreaEditorKit.rstaExpandAllFoldsAction); // NOTE: no modifiers => mapped to keyTyped. If we had "0" as a second // second parameter, we'd get the template action (keyPressed) AND the // default space action (keyTyped). // put(KeyStroke.getKeyStroke(' '), // RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, defaultShift), RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, defaultShift), + RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction); } } diff --git a/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaEditorKit.java b/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaEditorKit.java index aae9908..fc1f43a 100644 --- a/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaEditorKit.java +++ b/src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaEditorKit.java @@ -63,9 +63,8 @@ import org.fife.ui.rtextarea.RecordableTextAction; * @author Robert Futrell * @version 0.5 */ -@SuppressWarnings({ "checkstyle:constantname" }) public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { - + private static final long serialVersionUID = 1L; public static final String rstaCloseCurlyBraceAction = "RSTA.CloseCurlyBraceAction"; public static final String rstaCloseMarkupTagAction = "RSTA.CloseMarkupTagAction"; @@ -88,22 +87,26 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { */ private static final Action[] defaultActions = { new CloseCurlyBraceAction(), new CloseMarkupTagAction(), new BeginWordAction(beginWordAction, false), new BeginWordAction(selectionBeginWordAction, true), - new ChangeFoldStateAction(rstaCollapseFoldAction, true), new ChangeFoldStateAction(rstaExpandFoldAction, false), - new CollapseAllFoldsAction(), new CopyAsRtfAction(), + new ChangeFoldStateAction(rstaCollapseFoldAction, true), + new ChangeFoldStateAction(rstaExpandFoldAction, false), new CollapseAllFoldsAction(), new CopyAsRtfAction(), // new DecreaseFontSizeAction(), - new DecreaseIndentAction(), new DeletePrevWordAction(), new DumbCompleteWordAction(), new EndAction(endAction, false), - new EndAction(selectionEndAction, true), new EndWordAction(endWordAction, false), new EndWordAction(endWordAction, true), - new ExpandAllFoldsAction(), new GoToMatchingBracketAction(), new InsertBreakAction(), + new DecreaseIndentAction(), new DeletePrevWordAction(), new DumbCompleteWordAction(), + new EndAction(endAction, false), new EndAction(selectionEndAction, true), + new EndWordAction(endWordAction, false), new EndWordAction(endWordAction, true), new ExpandAllFoldsAction(), + new GoToMatchingBracketAction(), new InsertBreakAction(), // new IncreaseFontSizeAction(), - new InsertTabAction(), new NextWordAction(nextWordAction, false), new NextWordAction(selectionNextWordAction, true), - new PossiblyInsertTemplateAction(), new PreviousWordAction(previousWordAction, false), - new PreviousWordAction(selectionPreviousWordAction, true), new SelectWordAction(), new ToggleCommentAction(), }; - + new InsertTabAction(), new NextWordAction(nextWordAction, false), + new NextWordAction(selectionNextWordAction, true), new PossiblyInsertTemplateAction(), + new PreviousWordAction(previousWordAction, false), + new PreviousWordAction(selectionPreviousWordAction, true), new SelectWordAction(), + new ToggleCommentAction(), }; + /** * Constructor. */ - public RSyntaxTextAreaEditorKit() {} - + public RSyntaxTextAreaEditorKit() { + } + /** * Returns the default document used by RSyntaxTextAreas. * @@ -113,23 +116,21 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { public Document createDefaultDocument() { return new RSyntaxDocument(SyntaxConstants.SYNTAX_STYLE_NONE); } - + /** * Overridden to return a row header that is aware of folding. * - * @param textArea - * The text area. + * @param textArea The text area. * @return The icon row header. */ @Override public IconRowHeader createIconRowHeader(RTextArea textArea) { return new FoldingAwareIconRowHeader((RSyntaxTextArea) textArea); } - + /** - * Fetches the set of commands that can be used - * on a text component that is using a model and - * view produced by this kit. + * Fetches the set of commands that can be used on a text component that is + * using a model and view produced by this kit. * * @return the command list */ @@ -137,33 +138,31 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { public Action[] getActions() { return TextAction.augmentList(super.getActions(), RSyntaxTextAreaEditorKit.defaultActions); } - + /** - * Returns localized text for an action. There's definitely a better place - * for this functionality. + * Returns localized text for an action. There's definitely a better place for + * this functionality. * - * @param key - * The key into the action resource bundle. + * @param key The key into the action resource bundle. * @return The localized text. */ public static String getString(String key) { return msg.getString(key); } - + /** - * Positions the caret at the beginning of the word. This class is here - * to better handle finding the "beginning of the word" for programming - * languages. + * Positions the caret at the beginning of the word. This class is here to + * better handle finding the "beginning of the word" for programming languages. */ protected static class BeginWordAction extends RTextAreaEditorKit.BeginWordAction { - + private Segment seg; - + protected BeginWordAction(String name, boolean select) { super(name, select); seg = new Segment(); } - + @Override protected int getWordStart(RTextArea textArea, int offs) throws BadLocationException { if (offs == 0) { @@ -217,23 +216,23 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return offs; } } - + /** * Expands or collapses the nearest fold. */ public static class ChangeFoldStateAction extends FoldRelatedAction { - + private boolean collapse; - + public ChangeFoldStateAction(String name, boolean collapse) { super(name); this.collapse = collapse; } - + public ChangeFoldStateAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -247,28 +246,28 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(rsta); } } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action that (optionally) aligns a closing curly brace with the line * containing its matching opening curly brace. */ public static class CloseCurlyBraceAction extends RecordableTextAction { - + private static final long serialVersionUID = 1L; private Point bracketInfo; private Segment seg; - + public CloseCurlyBraceAction() { super(rstaCloseCurlyBraceAction); seg = new Segment(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -327,24 +326,24 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + @Override public final String getMacroID() { return rstaCloseCurlyBraceAction; } } - + /** * (Optionally) completes a closing markup tag. */ public static class CloseMarkupTagAction extends RecordableTextAction { - + private static final long serialVersionUID = 1L; - + public CloseMarkupTagAction() { super(rstaCloseMarkupTagAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -358,7 +357,8 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { rsta.replaceSelection("/"); // Don't automatically complete a tag if there was a selection int dot = c.getDot(); - if (doc.getLanguageIsMarkup() && doc.getCompleteMarkupCloseTags() && !selection && rsta.getCloseMarkupTags() && dot > 1) { + if (doc.getLanguageIsMarkup() && doc.getCompleteMarkupCloseTags() && !selection && rsta.getCloseMarkupTags() + && dot > 1) { try { // Check actual char before token type, since it's quicker char ch = doc.charAt(dot - 2); @@ -379,20 +379,17 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + /** - * Discovers the name of the tag being closed. Assumes standard - * SGML-style markup tags. + * Discovers the name of the tag being closed. Assumes standard SGML-style + * markup tags. * - * @param doc - * The document to parse. - * @param dot - * The location of the caret. This should be right after - * the start of a closing tag token (e.g. - * "</" - * or "[" in the case of BBCode). - * @return The name of the tag to close, or null if it - * could not be determined. + * @param doc The document to parse. + * @param dot The location of the caret. This should be right after the start of + * a closing tag token (e.g. "</" or "[" + * in the case of BBCode). + * @return The name of the tag to close, or null if it could not be + * determined. */ private String discoverTagName(RSyntaxDocument doc, int dot) { Stack stack = new Stack(); @@ -416,11 +413,13 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } t = t.getNextToken(); } - } else if (t.length() == 2 && t.charAt(0) == '/' && (t.charAt(1) == '>' || t.charAt(1) == ']')) { + } else if (t.length() == 2 && t.charAt(0) == '/' + && (t.charAt(1) == '>' || t.charAt(1) == ']')) { if (!stack.isEmpty()) { // Always true for valid XML stack.pop(); } - } else if (t.length() == 2 && (t.charAt(0) == '<' || t.charAt(0) == '[') && t.charAt(1) == '/') { + } else if (t.length() == 2 && (t.charAt(0) == '<' || t.charAt(0) == '[') + && t.charAt(1) == '/') { String tagName = null; if (!stack.isEmpty()) { // Always true for valid XML tagName = stack.pop(); @@ -435,29 +434,30 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return null; // Should never happen } - + @Override public String getMacroID() { return getName(); } } - + /** * Collapses all comment folds. */ public static class CollapseAllCommentFoldsAction extends FoldRelatedAction { - + private static final long serialVersionUID = 1L; - + public CollapseAllCommentFoldsAction() { super(rstaCollapseAllCommentFoldsAction); setProperties(msg, "Action.CollapseCommentFolds"); } - - public CollapseAllCommentFoldsAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { + + public CollapseAllCommentFoldsAction(String name, Icon icon, String desc, Integer mnemonic, + KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -469,41 +469,41 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(rsta); } } - + @Override public final String getMacroID() { return rstaCollapseAllCommentFoldsAction; } } - + /** * Collapses all folds. */ public static class CollapseAllFoldsAction extends FoldRelatedAction { - + private static final long serialVersionUID = 1L; - + public CollapseAllFoldsAction() { this(false); } - + public CollapseAllFoldsAction(boolean localizedName) { super(rstaCollapseAllFoldsAction); if (localizedName) { setProperties(msg, "Action.CollapseAllFolds"); } } - + public CollapseAllFoldsAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; if (rsta.isCodeFoldingEnabled()) { FoldCollapser collapser = new FoldCollapser() { - + @Override public boolean getShouldCollapse(Fold fold) { return true; @@ -515,55 +515,55 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(rsta); } } - + @Override public final String getMacroID() { return rstaCollapseAllFoldsAction; } } - + /** * Action for copying text as RTF. */ public static class CopyAsRtfAction extends RecordableTextAction { - + private static final long serialVersionUID = 1L; - + public CopyAsRtfAction() { super(rstaCopyAsRtfAction); } - + public CopyAsRtfAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { ((RSyntaxTextArea) textArea).copyAsRtf(); textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action for decreasing the font size of all fonts in the text area. */ public static class DecreaseFontSizeAction extends RTextAreaEditorKit.DecreaseFontSizeAction { - + private static final long serialVersionUID = 1L; - + public DecreaseFontSizeAction() { super(); } - + public DecreaseFontSizeAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -633,25 +633,25 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + /** * Action for when un-indenting lines (either the current line if there is * selection, or all selected lines if there is one). */ public static class DecreaseIndentAction extends RecordableTextAction { - + private static final long serialVersionUID = 1L; private Segment s; - + public DecreaseIndentAction() { this(rstaDecreaseIndentAction); } - + public DecreaseIndentAction(String name) { super(name); s = new Segment(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -705,28 +705,24 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + @Override public final String getMacroID() { return rstaDecreaseIndentAction; } - + /** - * Actually does the "de-indentation." This method finds where the - * given element's leading whitespace ends, then, if there is indeed - * leading whitespace, removes either the last char in it (if it is a - * tab), or removes up to the number of spaces equal to a tab in the - * specified document (i.e., if the tab size was 5 and there were 3 - * spaces at the end of the leading whitespace, the three will be - * removed; if there were 8 spaces, only the first 5 would be - * removed). + * Actually does the "de-indentation." This method finds where the given + * element's leading whitespace ends, then, if there is indeed leading + * whitespace, removes either the last char in it (if it is a tab), or removes + * up to the number of spaces equal to a tab in the specified document (i.e., if + * the tab size was 5 and there were 3 spaces at the end of the leading + * whitespace, the three will be removed; if there were 8 spaces, only the first + * 5 would be removed). * - * @param elem - * The element to "de-indent." - * @param doc - * The document containing the specified element. - * @param tabSize - * The size of a tab, in spaces. + * @param elem The element to "de-indent." + * @param doc The document containing the specified element. + * @param tabSize The size of a tab, in spaces. */ private void handleDecreaseIndent(Element elem, Document doc, int tabSize) throws BadLocationException { int start = elem.getStartOffset(); @@ -754,15 +750,15 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + /** - * Deletes the previous word, but differentiates symbols from "words" to - * match the behavior of code editors. + * Deletes the previous word, but differentiates symbols from "words" to match + * the behavior of code editors. */ public static class DeletePrevWordAction extends RTextAreaEditorKit.DeletePrevWordAction { - + private Segment seg = new Segment(); - + @Override protected int getPreviousWordStart(RTextArea textArea, int offs) throws BadLocationException { if (offs == 0) { @@ -812,13 +808,13 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return offs; } } - + /** - * Overridden to use the programming language RSTA is displaying when - * computing words to complete. + * Overridden to use the programming language RSTA is displaying when computing + * words to complete. */ public static class DumbCompleteWordAction extends RTextAreaEditorKit.DumbCompleteWordAction { - + @Override protected int getPreviousWord(RTextArea textArea, int offs) throws BadLocationException { RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument(); @@ -848,8 +844,9 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return prevWordStart; } - - private int getPreviousWordStartInLine(RSyntaxDocument doc, Element elem, int offs) throws BadLocationException { + + private int getPreviousWordStartInLine(RSyntaxDocument doc, Element elem, int offs) + throws BadLocationException { int start = elem.getStartOffset(); int cur = offs; // Skip any whitespace or non-word chars @@ -866,7 +863,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return getWordStartImpl(doc, elem, cur); } - + @Override protected int getWordEnd(RTextArea textArea, int offs) throws BadLocationException { RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument(); @@ -883,7 +880,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return wordEnd; } - + @Override protected int getWordStart(RTextArea textArea, int offs) throws BadLocationException { RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument(); @@ -892,7 +889,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { Element elem = root.getElement(line); return getWordStartImpl(doc, elem, offs); } - + private static int getWordStartImpl(RSyntaxDocument doc, Element elem, int offs) throws BadLocationException { int start = elem.getStartOffset(); int wordStart = offs; @@ -906,27 +903,25 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return wordStart == offs ? offs : wordStart + 1; } - + /** - * Overridden to not suggest word completions if the text right before - * the caret contains non-word characters, such as '/' or '%'. + * Overridden to not suggest word completions if the text right before the caret + * contains non-word characters, such as '/' or '%'. * - * @param prefix - * The prefix characters before the caret. - * @return Whether the prefix could be part of a "word" in the context - * of the text area's current content. + * @param prefix The prefix characters before the caret. + * @return Whether the prefix could be part of a "word" in the context of the + * text area's current content. */ @Override protected boolean isAcceptablePrefix(String prefix) { return prefix.length() > 0 && isIdentifierChar(prefix.charAt(prefix.length() - 1)); } - + /** - * Returns whether the specified character should be considered part - * of an identifier. + * Returns whether the specified character should be considered part of an + * identifier. * - * @param ch - * The character. + * @param ch The character. * @return Whether the character is part of an identifier. */ private static boolean isIdentifierChar(char ch) { @@ -934,20 +929,20 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return Character.isLetterOrDigit(ch) || ch == '_' || ch == '$'; } } - + /** - * Positions the caret at the end of the word. This class is here to - * better handle finding the "end of the word" in programming languages. + * Positions the caret at the end of the word. This class is here to better + * handle finding the "end of the word" in programming languages. */ protected static class EndWordAction extends RTextAreaEditorKit.EndWordAction { - + private Segment seg; - + protected EndWordAction(String name, boolean select) { super(name, select); seg = new Segment(); } - + @Override protected int getWordEnd(RTextArea textArea, int offs) throws BadLocationException { RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument(); @@ -985,29 +980,29 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return offs; } } - + /** * Expands all folds. */ public static class ExpandAllFoldsAction extends FoldRelatedAction { - + private static final long serialVersionUID = 1L; - + public ExpandAllFoldsAction() { this(false); } - + public ExpandAllFoldsAction(boolean localizedName) { super(rstaExpandAllFoldsAction); if (localizedName) { setProperties(msg, "Action.ExpandAllFolds"); } } - + public ExpandAllFoldsAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -1021,33 +1016,33 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(rsta); } } - + private void expand(Fold fold) { fold.setCollapsed(false); for (int i = 0; i < fold.getChildCount(); i++) { expand(fold.getChild(i)); } } - + @Override public final String getMacroID() { return rstaExpandAllFoldsAction; } } - + /** * Base class for folding-related actions. */ abstract static class FoldRelatedAction extends RecordableTextAction { - + FoldRelatedAction(String name) { super(name); } - + FoldRelatedAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + protected Fold getClosestFold(RSyntaxTextArea textArea) { int offs = textArea.getCaretPosition(); int line = textArea.getCaretLineNumber(); @@ -1059,41 +1054,40 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return fold; } } - + /** - * Action for moving the caret to the "matching bracket" of the bracket - * at the caret position (either before or after). + * Action for moving the caret to the "matching bracket" of the bracket at the + * caret position (either before or after). */ public static class GoToMatchingBracketAction extends RecordableTextAction { - + /** - * Moves the caret to the end of the document, taking into account code - * folding. + * Moves the caret to the end of the document, taking into account code folding. */ public static class EndAction extends RTextAreaEditorKit.EndAction { - + public EndAction(String name, boolean select) { super(name, select); } - + @Override protected int getVisibleEnd(RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; return rsta.getLastVisibleOffset(); } } - + private static final long serialVersionUID = 1L; private Point bracketInfo; - + public GoToMatchingBracketAction() { super(rstaGoToMatchingBracketAction); } - + public GoToMatchingBracketAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -1106,28 +1100,28 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(rsta); } } - + @Override public final String getMacroID() { return rstaGoToMatchingBracketAction; } } - + /** * Action for increasing the font size of all fonts in the text area. */ public static class IncreaseFontSizeAction extends RTextAreaEditorKit.IncreaseFontSizeAction { - + private static final long serialVersionUID = 1L; - + public IncreaseFontSizeAction() { super(); } - + public IncreaseFontSizeAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -1197,15 +1191,15 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + /** - * Action for when the user presses the Enter key. This is here so we can - * be smart and "auto-indent" for programming languages. + * Action for when the user presses the Enter key. This is here so we can be + * smart and "auto-indent" for programming languages. */ public static class InsertBreakAction extends RTextAreaEditorKit.InsertBreakAction { - + private static final long serialVersionUID = 1L; - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1226,12 +1220,11 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { handleInsertBreak(sta, noSelection); } } - + /** - * @return The first location in the string past pos that - * is NOT a whitespace char, or -1 if only - * whitespace chars follow pos (or it is the end - * position in the string). + * @return The first location in the string past pos that is NOT a + * whitespace char, or -1 if only whitespace chars follow + * pos (or it is the end position in the string). */ private static int atEndOfLine(int pos, String s, int sLen) { for (int i = pos; i < sLen; i++) { @@ -1241,7 +1234,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return -1; } - + private static int getOpenBraceCount(RSyntaxDocument doc, int languageIndex) { int openCount = 0; for (Token t : doc) { @@ -1256,15 +1249,14 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return openCount; } - + /** - * Actually inserts the newline into the document, and auto-indents - * if appropriate. This method can be called by token makers who - * implement a custom action for inserting newlines. + * Actually inserts the newline into the document, and auto-indents if + * appropriate. This method can be called by token makers who implement a custom + * action for inserting newlines. * * @param textArea - * @param noSelection - * Whether there is no selection. + * @param noSelection Whether there is no selection. */ protected void handleInsertBreak(RSyntaxTextArea textArea, boolean noSelection) { // If we're auto-indenting... @@ -1277,7 +1269,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + private void insertNewlineWithAutoIndent(RSyntaxTextArea sta) { try { int caretPos = sta.getCaretPosition(); @@ -1328,7 +1320,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { ble.printStackTrace(); } } - + private void possiblyCloseCurlyBrace(RSyntaxTextArea textArea, String leadingWS) { RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument(); if (textArea.getCloseCurlyBraces()) { @@ -1337,7 +1329,8 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { t = t.getLastNonCommentNonWhitespaceToken(); if (t != null && t.isLeftCurly()) { int languageIndex = t.getLanguageIndex(); - if (doc.getCurlyBracesDenoteCodeBlocks(languageIndex) && getOpenBraceCount(doc, languageIndex) > 0) { + if (doc.getCurlyBracesDenoteCodeBlocks(languageIndex) + && getOpenBraceCount(doc, languageIndex) > 0) { StringBuilder sb = new StringBuilder(); if (line == textArea.getLineCount() - 1) { sb.append('\n'); @@ -1359,23 +1352,23 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + /** - * Action for inserting tabs. This is extended to "block indent" a - * group of contiguous lines if they are selected. + * Action for inserting tabs. This is extended to "block indent" a group of + * contiguous lines if they are selected. */ public static class InsertTabAction extends RecordableTextAction { - + private static final long serialVersionUID = 1L; - + public InsertTabAction() { super(insertTabAction); } - + public InsertTabAction(String name) { super(name); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1433,27 +1426,27 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { textArea.replaceSelection("\t"); } } - + @Override public final String getMacroID() { return insertTabAction; } } - + /** - * Action to move the selection and/or caret. Constructor indicates - * direction to use. This class overrides the behavior defined in - * {@link RTextAreaEditorKit} to better skip "words" in source code. + * Action to move the selection and/or caret. Constructor indicates direction to + * use. This class overrides the behavior defined in {@link RTextAreaEditorKit} + * to better skip "words" in source code. */ public static class NextWordAction extends RTextAreaEditorKit.NextWordAction { - + private Segment seg; - + public NextWordAction(String nm, boolean select) { super(nm, select); seg = new Segment(); } - + /** * Overridden to do better with skipping "words" in code. */ @@ -1471,7 +1464,8 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { if (rsta.isCodeFoldingEnabled()) { // Start of next visible line FoldManager fm = rsta.getFoldManager(); int lineCount = root.getElementCount(); - while (++line < lineCount && fm.isLineHidden(line)); + while (++line < lineCount && fm.isLineHidden(line)) + ; if (line < lineCount) { // Found a lower visible line offs = root.getElement(line).getStartOffset(); } @@ -1497,7 +1491,8 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { else if (!Character.isWhitespace(ch)) { do { ch = seg.next(); - } while (ch != Segment.DONE && !(doc.isIdentifierChar(languageIndex, ch) || Character.isWhitespace(ch))); + } while (ch != Segment.DONE + && !(doc.isIdentifierChar(languageIndex, ch) || Character.isWhitespace(ch))); } // Skip any trailing whitespace while (Character.isWhitespace(ch)) { @@ -1507,20 +1502,20 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return offs; } } - + /** - * Action for when the user tries to insert a template (that is, - * they've typed a template ID and pressed the trigger character - * (a space) in an attempt to do the substitution). + * Action for when the user tries to insert a template (that is, they've typed a + * template ID and pressed the trigger character (a space) in an attempt to do + * the substitution). */ public static class PossiblyInsertTemplateAction extends RecordableTextAction { - + private static final long serialVersionUID = 1L; - + public PossiblyInsertTemplateAction() { super(rstaPossiblyInsertTemplateAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1552,7 +1547,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { doDefaultInsert(rsta); } } - + private void doDefaultInsert(RTextArea textArea) { // FIXME: We need a way to get the "trigger string" (i.e., // the text that was just typed); however, the text area's @@ -1570,27 +1565,27 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { // } textArea.replaceSelection(" "); } - + @Override public final String getMacroID() { return rstaPossiblyInsertTemplateAction; } } - + /** - * Action to move the selection and/or caret. Constructor indicates - * direction to use. This class overrides the behavior defined in - * {@link RTextAreaEditorKit} to better skip "words" in source code. + * Action to move the selection and/or caret. Constructor indicates direction to + * use. This class overrides the behavior defined in {@link RTextAreaEditorKit} + * to better skip "words" in source code. */ public static class PreviousWordAction extends RTextAreaEditorKit.PreviousWordAction { - + private Segment seg; - + public PreviousWordAction(String nm, boolean select) { super(nm, select); seg = new Segment(); } - + /** * Overridden to do better with skipping "words" in code. */ @@ -1607,7 +1602,8 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; if (rsta.isCodeFoldingEnabled()) { // End of next visible line FoldManager fm = rsta.getFoldManager(); - while (--line >= 0 && fm.isLineHidden(line)); + while (--line >= 0 && fm.isLineHidden(line)) + ; if (line >= 0) { // Found an earlier visible line offs = root.getElement(line).getEndOffset() - 1; } @@ -1636,7 +1632,8 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { else if (!Character.isWhitespace(ch)) { do { ch = seg.previous(); - } while (ch != Segment.DONE && !(doc.isIdentifierChar(languageIndex, ch) || Character.isWhitespace(ch))); + } while (ch != Segment.DONE + && !(doc.isIdentifierChar(languageIndex, ch) || Character.isWhitespace(ch))); } offs -= seg.getEndIndex() - seg.getIndex(); if (ch != Segment.DONE) { @@ -1645,30 +1642,29 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { return offs; } } - + /** - * Selects the word around the caret. This class is here to better - * handle selecting "words" in programming languages. + * Selects the word around the caret. This class is here to better handle + * selecting "words" in programming languages. */ public static class SelectWordAction extends RTextAreaEditorKit.SelectWordAction { - + @Override protected void createActions() { start = new BeginWordAction("pigdog", false); end = new EndWordAction("pigdog", true); } } - + /** - * Action that toggles whether the currently selected lines are - * commented. + * Action that toggles whether the currently selected lines are commented. */ public static class ToggleCommentAction extends RecordableTextAction { - + public ToggleCommentAction() { super(rstaToggleCommentAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1713,8 +1709,9 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { textArea.endAtomicEdit(); } } - - private boolean getDoAdd(Document doc, Element map, int startLine, int endLine, String[] startEnd) throws BadLocationException { + + private boolean getDoAdd(Document doc, Element map, int startLine, int endLine, String[] startEnd) + throws BadLocationException { boolean doAdd = false; for (int i = startLine; i <= endLine; i++) { Element elem = map.getElement(i); @@ -1727,8 +1724,9 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } return doAdd; } - - private void handleToggleComment(Element elem, Document doc, String[] startEnd, boolean add) throws BadLocationException { + + private void handleToggleComment(Element elem, Document doc, String[] startEnd, boolean add) + throws BadLocationException { int start = elem.getStartOffset(); int end = elem.getEndOffset() - 1; if (add) { @@ -1744,29 +1742,29 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { } } } - + @Override public final String getMacroID() { return rstaToggleCommentAction; } } - + /** * Toggles the fold at the current caret position or line. */ public static class ToggleCurrentFoldAction extends FoldRelatedAction { - + private static final long serialVersionUID = 1L; - + public ToggleCurrentFoldAction() { super(rstaToggleCurrentFoldAction); setProperties(msg, "Action.ToggleCurrentFold"); } - + public ToggleCurrentFoldAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RSyntaxTextArea rsta = (RSyntaxTextArea) textArea; @@ -1780,7 +1778,7 @@ public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(rsta); } } - + @Override public final String getMacroID() { return rstaToggleCurrentFoldAction; diff --git a/src/org/fife/ui/rsyntaxtextarea/Style.java b/src/org/fife/ui/rsyntaxtextarea/Style.java index 88c0031..420f259 100644 --- a/src/org/fife/ui/rsyntaxtextarea/Style.java +++ b/src/org/fife/ui/rsyntaxtextarea/Style.java @@ -28,9 +28,8 @@ import javax.swing.JPanel; * @author Robert Futrell * @version 0.6 */ -@SuppressWarnings({ "checkstyle:visibilitymodifier" }) public class Style implements Cloneable { - + public static final Color DEFAULT_FOREGROUND = Color.BLACK; public static final Color DEFAULT_BACKGROUND = null; public static final Font DEFAULT_FONT = null; @@ -39,62 +38,52 @@ public class Style implements Cloneable { public boolean underline; public Font font; public FontMetrics fontMetrics; - + /** - * Creates a new style defaulting to black foreground, no - * background, and no styling. + * Creates a new style defaulting to black foreground, no background, and no + * styling. */ public Style() { this(DEFAULT_FOREGROUND); } - + /** * Creates a new style with the specified foreground and no styling. * - * @param fg - * The foreground color to use. + * @param fg The foreground color to use. */ public Style(Color fg) { this(fg, DEFAULT_BACKGROUND); } - + /** * Creates a new style with the specified colors and no styling. * - * @param fg - * The foreground color to use. - * @param bg - * The background color to use. + * @param fg The foreground color to use. + * @param bg The background color to use. */ public Style(Color fg, Color bg) { this(fg, bg, DEFAULT_FONT); } - + /** * Creates a new style. * - * @param fg - * The foreground color to use. - * @param bg - * The background color to use. - * @param font - * The font for this syntax scheme. + * @param fg The foreground color to use. + * @param bg The background color to use. + * @param font The font for this syntax scheme. */ public Style(Color fg, Color bg, Font font) { this(fg, bg, font, false); } - + /** * Creates a new style. * - * @param fg - * The foreground color to use. - * @param bg - * The background color to use. - * @param font - * The font for this syntax scheme. - * @param underline - * Whether or not to underline tokens with this style. + * @param fg The foreground color to use. + * @param bg The background color to use. + * @param font The font for this syntax scheme. + * @param underline Whether or not to underline tokens with this style. */ public Style(Color fg, Color bg, Font font, boolean underline) { foreground = fg; @@ -106,15 +95,14 @@ public class Style implements Cloneable { // rendering // hints! } - + /** - * Returns whether or not two (possibly null) objects are - * equal. + * Returns whether or not two (possibly null) objects are equal. */ private boolean areEqual(Object o1, Object o2) { return (o1 == null && o2 == null) || (o1 != null && o1.equals(o2)); } - + /** * Returns a deep copy of this object. * @@ -136,34 +124,32 @@ public class Style implements Cloneable { clone.fontMetrics = fontMetrics; return clone; } - + /** * Returns whether or not two syntax schemes are equal. * - * @param o2 - * The object with which to compare this syntax scheme. - * @return Whether or not these two syntax schemes represent the same - * scheme. + * @param o2 The object with which to compare this syntax scheme. + * @return Whether or not these two syntax schemes represent the same scheme. */ @Override public boolean equals(Object o2) { if (o2 instanceof Style) { Style ss2 = (Style) o2; - if (this.underline == ss2.underline && areEqual(foreground, ss2.foreground) && areEqual(background, ss2.background) - && areEqual(font, ss2.font) && areEqual(fontMetrics, ss2.fontMetrics)) { + if (this.underline == ss2.underline && areEqual(foreground, ss2.foreground) + && areEqual(background, ss2.background) && areEqual(font, ss2.font) + && areEqual(fontMetrics, ss2.fontMetrics)) { return true; } } return false; } - + /** - * Computes the hash code to use when adding this syntax scheme to - * hash tables. + * Computes the hash code to use when adding this syntax scheme to hash tables. *

    * - * This method is implemented, since {@link #equals(Object)} is implemented, - * to keep FindBugs happy. + * This method is implemented, since {@link #equals(Object)} is implemented, to + * keep FindBugs happy. * * @return The hash code. */ @@ -178,7 +164,7 @@ public class Style implements Cloneable { } return hashCode; } - + /** * Returns a string representation of this style. * @@ -186,6 +172,7 @@ public class Style implements Cloneable { */ @Override public String toString() { - return "[Style: foreground: " + foreground + ", background: " + background + ", underline: " + underline + ", font: " + font + "]"; + return "[Style: foreground: " + foreground + ", background: " + background + ", underline: " + underline + + ", font: " + font + "]"; } } diff --git a/src/org/fife/ui/rsyntaxtextarea/SyntaxScheme.java b/src/org/fife/ui/rsyntaxtextarea/SyntaxScheme.java index ae1070f..e2734d1 100644 --- a/src/org/fife/ui/rsyntaxtextarea/SyntaxScheme.java +++ b/src/org/fife/ui/rsyntaxtextarea/SyntaxScheme.java @@ -24,8 +24,8 @@ import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** - * The set of colors and styles used by an RSyntaxTextArea to - * color tokens. + * The set of colors and styles used by an RSyntaxTextArea to color + * tokens. *

    * You can use this class to programmatically set the fonts and colors used in * an RSyntaxTextArea, but for more powerful, externalized control, consider @@ -35,20 +35,18 @@ import org.xml.sax.helpers.XMLReaderFactory; * @version 1.0 * @see Theme */ -@SuppressWarnings({ "checkstyle:magicnumber" }) public class SyntaxScheme implements Cloneable, TokenTypes { - + private Style[] styles; private static final String VERSION = "*ver1"; - + /** - * Creates a color scheme that either has all color values set to - * a default value or set to null. + * Creates a color scheme that either has all color values set to a default + * value or set to null. * - * @param useDefaults - * If true, all color values will - * be set to default colors; if false, all colors - * will be initially null. + * @param useDefaults If true, all color values will be set to + * default colors; if false, all colors will be + * initially null. */ public SyntaxScheme(boolean useDefaults) { styles = new Style[DEFAULT_NUM_TOKEN_TYPES]; @@ -56,50 +54,43 @@ public class SyntaxScheme implements Cloneable, TokenTypes { restoreDefaults(null); } } - + /** * Creates a default color scheme. * - * @param baseFont - * The base font to use. Keywords will be a bold version - * of this font, and comments will be an italicized version of - * this - * font. + * @param baseFont The base font to use. Keywords will be a bold version of this + * font, and comments will be an italicized version of this + * font. */ public SyntaxScheme(Font baseFont) { this(baseFont, true); } - + /** * Creates a default color scheme. * - * @param baseFont - * The base font to use. Keywords will be a bold version - * of this font, and comments will be an italicized version of - * this - * font. - * @param fontStyles - * Whether bold and italic should be used in the scheme - * (vs. all tokens using a plain font). + * @param baseFont The base font to use. Keywords will be a bold version of + * this font, and comments will be an italicized version of + * this font. + * @param fontStyles Whether bold and italic should be used in the scheme (vs. + * all tokens using a plain font). */ public SyntaxScheme(Font baseFont, boolean fontStyles) { styles = new Style[DEFAULT_NUM_TOKEN_TYPES]; restoreDefaults(baseFont, fontStyles); } - + /** * Changes the "base font" for this syntax scheme. This is called by * RSyntaxTextArea when its font changes via - * setFont(). This looks for tokens that use a derivative of - * the text area's old font (but bolded and/or italicized) and make them - * use the new font with those stylings instead. This is desirable because - * most programmers prefer a single font to be used in their text editor, - * but might want bold (say for keywords) or italics. + * setFont(). This looks for tokens that use a derivative of the + * text area's old font (but bolded and/or italicized) and make them use the new + * font with those stylings instead. This is desirable because most programmers + * prefer a single font to be used in their text editor, but might want bold + * (say for keywords) or italics. * - * @param old - * The old font of the text area. - * @param font - * The new font of the text area. + * @param old The old font of the text area. + * @param font The new font of the text area. */ void changeBaseFont(Font old, Font font) { for (int i = 0; i < styles.length; i++) { @@ -113,7 +104,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } } } - + /** * Returns a deep copy of this color scheme. * @@ -137,15 +128,13 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } return shcs; } - + /** * Tests whether this color scheme is the same as another color scheme. * - * @param otherScheme - * The color scheme to compare to. - * @return true if this color scheme and - * otherScheme are the same scheme; - * false otherwise. + * @param otherScheme The color scheme to compare to. + * @return true if this color scheme and otherScheme + * are the same scheme; false otherwise. */ @Override public boolean equals(Object otherScheme) { @@ -167,24 +156,22 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } return true; } - + /** * Returns a hex string representing an RGB color, of the form * "$rrggbb". * - * @param c - * The color. + * @param c The color. * @return The string representation of the color. */ private static String getHexString(Color c) { return "$" + Integer.toHexString((c.getRGB() & 0xffffff) + 0x1000000).substring(1); } - + /** * Returns the specified style. * - * @param index - * The index of the style. + * @param index The index of the style. * @return The style. * @see #setStyle(int, Style) * @see #getStyleCount() @@ -192,7 +179,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes { public Style getStyle(int index) { return styles[index]; } - + /** * Returns the number of styles. * @@ -202,14 +189,14 @@ public class SyntaxScheme implements Cloneable, TokenTypes { public int getStyleCount() { return styles.length; } - + /** - * Used by third party implementors e.g. SquirreL SQL. Most applications do - * not need to call this method. + * Used by third party implementors e.g. SquirreL SQL. Most applications do not + * need to call this method. *

    * Note that the returned array is not a copy of the style data; editing the - * array will modify the styles used by any RSyntaxTextArea - * using this scheme. + * array will modify the styles used by any RSyntaxTextArea using + * this scheme. * * @return The style array. * @see #setStyles(Style[]) @@ -217,10 +204,10 @@ public class SyntaxScheme implements Cloneable, TokenTypes { public Style[] getStyles() { return styles; } - + /** - * This is implemented to be consistent with {@link #equals(Object)}. - * This is a requirement to keep FindBugs happy. + * This is implemented to be consistent with {@link #equals(Object)}. This is a + * requirement to keep FindBugs happy. * * @return The hash code for this object. */ @@ -238,24 +225,20 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } return hashCode; } - + /** * Loads a syntax scheme from an input stream. *

    * - * Consider using the {@link Theme} class for saving and loading RSTA - * styles rather than using this API. + * Consider using the {@link Theme} class for saving and loading RSTA styles + * rather than using this API. * - * @param baseFont - * The font to use as the "base" for the syntax scheme. - * If this is null, a default monospaced font is - * used. - * @param in - * The stream to load from. It is up to the caller to close this - * stream when they are done. + * @param baseFont The font to use as the "base" for the syntax scheme. If this + * is null, a default monospaced font is used. + * @param in The stream to load from. It is up to the caller to close this + * stream when they are done. * @return The syntax scheme. - * @throws IOException - * If an IO error occurs. + * @throws IOException If an IO error occurs. */ public static SyntaxScheme load(Font baseFont, InputStream in) throws IOException { if (baseFont == null) { @@ -263,42 +246,40 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } return SyntaxSchemeLoader.load(baseFont, in); } - + /** * Loads a syntax highlighting color scheme from a string created from - * toCommaSeparatedString. This method is useful for saving - * and restoring color schemes. + * toCommaSeparatedString. This method is useful for saving and + * restoring color schemes. *

    * - * Consider using the {@link Theme} class for saving and loading RSTA - * styles rather than using this API. + * Consider using the {@link Theme} class for saving and loading RSTA styles + * rather than using this API. * - * @param string - * A string generated from {@link #toCommaSeparatedString()}. + * @param string A string generated from {@link #toCommaSeparatedString()}. * @return A color scheme. * @see #toCommaSeparatedString() */ public static SyntaxScheme loadFromString(String string) { return loadFromString(string, DEFAULT_NUM_TOKEN_TYPES); } - + /** * Loads a syntax highlighting color scheme from a string created from - * toCommaSeparatedString. This method is useful for saving - * and restoring color schemes. + * toCommaSeparatedString. This method is useful for saving and + * restoring color schemes. *

    * - * Consider using the {@link Theme} class for saving and loading RSTA - * styles rather than using this API. + * Consider using the {@link Theme} class for saving and loading RSTA styles + * rather than using this API. * - * @param string - * A string generated from {@link #toCommaSeparatedString()}. - * @param tokenTypeCount - * The number of token types saved in this string. - * This should be the number of token types saved by your custom - * SyntaxScheme subclass, - * or {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES} if you used the - * standard implementation (which most people will). + * @param string A string generated from + * {@link #toCommaSeparatedString()}. + * @param tokenTypeCount The number of token types saved in this string. This + * should be the number of token types saved by your + * custom SyntaxScheme subclass, or + * {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES} if you used + * the standard implementation (which most people will). * @return A color scheme. * @see #loadFromString(String) * @see #toCommaSeparatedString() @@ -314,7 +295,8 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } int tokenCount = tokenTypeCount * 7 + 1; // Version string if (tokens.length != tokenCount) { - throw new Exception("Not enough tokens in packed color scheme: expected " + tokenCount + ", found " + tokens.length); + throw new Exception("Not enough tokens in packed color scheme: expected " + tokenCount + ", found " + + tokens.length); } // Use StyleContext to create fonts to get composite fonts for // Asian glyphs. @@ -359,7 +341,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } return scheme; } - + void refreshFontMetrics(Graphics2D g2d) { // It is assumed that any rendering hints are already applied to g2d. for (int i = 0; i < styles.length; i++) { @@ -369,29 +351,24 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } } } - + /** * Restores all colors and fonts to their default values. * - * @param baseFont - * The base font to use when creating this scheme. If - * this is null, then a default monospaced font is - * used. + * @param baseFont The base font to use when creating this scheme. If this is + * null, then a default monospaced font is used. */ public void restoreDefaults(Font baseFont) { restoreDefaults(baseFont, true); } - + /** * Restores all colors and fonts to their default values. * - * @param baseFont - * The base font to use when creating this scheme. If - * this is null, then a default monospaced font is - * used. - * @param fontStyles - * Whether bold and italic should be used in the scheme - * (vs. all tokens using a plain font). + * @param baseFont The base font to use when creating this scheme. If this is + * null, then a default monospaced font is used. + * @param fontStyles Whether bold and italic should be used in the scheme (vs. + * all tokens using a plain font). */ public void restoreDefaults(Font baseFont, boolean fontStyles) { // Colors used by tokens. @@ -469,40 +446,36 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } } } - + /** * Sets a style to use when rendering a token type. * - * @param type - * The token type. - * @param style - * The style for the token type. + * @param type The token type. + * @param style The style for the token type. * @see #getStyle(int) */ public void setStyle(int type, Style style) { styles[type] = style; } - + /** - * Used by third party implementors e.g. SquirreL SQL. Most applications do - * not need to call this method; individual styles can be set via + * Used by third party implementors e.g. SquirreL SQL. Most applications do not + * need to call this method; individual styles can be set via * {@link #setStyle(int, Style)}. * - * @param styles - * The new array of styles to use. Note that this should - * have length of at least - * {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES}. + * @param styles The new array of styles to use. Note that this should have + * length of at least {@link TokenTypes#DEFAULT_NUM_TOKEN_TYPES}. * @see #setStyle(int, Style) * @see #getStyles() */ public void setStyles(Style[] styles) { this.styles = styles; } - + /** - * Returns the color represented by a string. If the first char in the - * string is '$', it is assumed to be in hex, otherwise it is - * assumed to be decimal. So, for example, both of these: + * Returns the color represented by a string. If the first char in the string is + * '$', it is assumed to be in hex, otherwise it is assumed to be + * decimal. So, for example, both of these: * *

     	 * "$00ff00"
    @@ -511,8 +484,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
     	 * 
     	 * will return new Color(0, 255, 0).
     	 *
    -	 * @param s
    -	 *            The string to evaluate.
    +	 * @param s The string to evaluate.
     	 * @return The color.
     	 */
     	private static Color stringToColor(String s) {
    @@ -521,28 +493,26 @@ public class SyntaxScheme implements Cloneable, TokenTypes {
     		char ch = s.charAt(0);
     		return new Color((ch == '$' || ch == '#') ? Integer.parseInt(s.substring(1), 16) : Integer.parseInt(s));
     	}
    -	
    +
     	/**
    -	 * Returns this syntax highlighting scheme as a comma-separated list of
    -	 * values as follows:
    +	 * Returns this syntax highlighting scheme as a comma-separated list of values
    +	 * as follows:
     	 * 
      - *
    • If a color is non-null, it is added as a 24-bit integer - * of the form ((r<*lt;16) | (g<*lt;8) | (b)); if - * it is null, it is added as "-,". + *
    • If a color is non-null, it is added as a 24-bit integer of the form + * ((r<*lt;16) | (g<*lt;8) | (b)); if it is + * null, it is added as "-,". *
    • The font and style (bold/italic) is added as an integer like so: * "family, style, size". - *
    • The entire syntax highlighting scheme is thus one long string of - * color schemes of the format "i,[fg],[bg],uline,[style], - * where: + *
    • The entire syntax highlighting scheme is thus one long string of color + * schemes of the format "i,[fg],[bg],uline,[style], where: *
        *
      • i is the index of the syntax scheme. - *
      • fg and bg are the foreground and background - * colors for the scheme, and may be null (represented by - * -). - *
      • uline is whether or not the font should be - * underlined, and is either t or f. - *
      • style is the family,style,size - * triplet described above. + *
      • fg and bg are the foreground and background colors for the + * scheme, and may be null (represented by -). + *
      • uline is whether or not the font should be underlined, and + * is either t or f. + *
      • style is the family,style,size triplet + * described above. *
      *
    * @@ -566,26 +536,27 @@ public class SyntaxScheme implements Cloneable, TokenTypes { sb.append(ss.underline ? "t," : "f,"); Font font = ss.font; if (font != null) { - sb.append(font.getFamily()).append(',').append(font.getStyle()).append(',').append(font.getSize()).append(','); + sb.append(font.getFamily()).append(',').append(font.getStyle()).append(',').append(font.getSize()) + .append(','); } else { sb.append("-,,,"); } } return sb.substring(0, sb.length() - 1); // Take off final ','. } - + /** * Loads a SyntaxScheme from an XML file. */ private static class SyntaxSchemeLoader extends DefaultHandler { - + private Font baseFont; private SyntaxScheme scheme; - + SyntaxSchemeLoader(Font baseFont) { scheme = new SyntaxScheme(baseFont); } - + public static SyntaxScheme load(Font baseFont, InputStream in) throws IOException { SyntaxSchemeLoader parser = null; try { @@ -601,7 +572,7 @@ public class SyntaxScheme implements Cloneable, TokenTypes { } return parser.scheme; } - + @Override public void startElement(String uri, String localName, String qName, Attributes attrs) { if ("style".equals(qName)) { diff --git a/src/org/fife/ui/rsyntaxtextarea/Theme.java b/src/org/fife/ui/rsyntaxtextarea/Theme.java index 7f2f720..219cf3d 100644 --- a/src/org/fife/ui/rsyntaxtextarea/Theme.java +++ b/src/org/fife/ui/rsyntaxtextarea/Theme.java @@ -62,17 +62,16 @@ import org.xml.sax.helpers.DefaultHandler; * for various tasks. *

    * - * Note that to save a Theme via {@link #save(OutputStream)}, - * you must currently create a Theme from a text area wrapped in - * an RTextScrollPane, so that the color information for the - * gutter can be retrieved. + * Note that to save a Theme via {@link #save(OutputStream)}, you + * must currently create a Theme from a text area wrapped in an + * RTextScrollPane, so that the color information for the gutter + * can be retrieved. * * @author Robert Futrell * @version 1.0 */ -@SuppressWarnings({ "checkstyle:visibilitymodifier" }) public class Theme { - + public Font baseFont; public Color bgColor; public Color caretColor; @@ -103,14 +102,13 @@ public class Theme { public Color foldIndicatorFG; public Color foldBG; public Color armedFoldBG; - + /** * Private constructor, used when loading from a stream. * - * @param baseFont - * The default font to use for any "base font" properties - * not specified in the theme XML. If this is null, - * a default monospaced font will be used. + * @param baseFont The default font to use for any "base font" properties not + * specified in the theme XML. If this is null, a + * default monospaced font will be used. */ private Theme(Font baseFont) { // Optional fields that require a default value. @@ -118,13 +116,12 @@ public class Theme { secondaryLanguages = new Color[3]; activeLineRangeColor = Gutter.DEFAULT_ACTIVE_LINE_RANGE_COLOR; } - + /** - * Creates a theme from an RSyntaxTextArea. It should be contained in - * an RTextScrollPane to get all gutter color information. + * Creates a theme from an RSyntaxTextArea. It should be contained in an + * RTextScrollPane to get all gutter color information. * - * @param textArea - * The text area. + * @param textArea The text area. */ public Theme(RSyntaxTextArea textArea) { baseFont = textArea.getFont(); @@ -165,12 +162,11 @@ public class Theme { armedFoldBG = gutter.getArmedFoldBackground(); } } - + /** * Applies this theme to a text area. * - * @param textArea - * The text area to apply this theme to. + * @param textArea The text area to apply this theme to. */ public void apply(RSyntaxTextArea textArea) { textArea.setFont(baseFont); @@ -212,7 +208,7 @@ public class Theme { gutter.setArmedFoldBackground(armedFoldBG); } } - + private static String colorToString(Color c) { int color = c.getRGB() & 0xffffff; StringBuilder stringBuilder = new StringBuilder(Integer.toHexString(color)); @@ -221,7 +217,7 @@ public class Theme { } return stringBuilder.toString(); } - + /** * Returns the default selection background color to use if "default" is * specified in a theme. @@ -243,7 +239,7 @@ public class Theme { } return c; } - + /** * Returns the default selection background color to use if "default" is * specified in a theme. @@ -264,10 +260,10 @@ public class Theme { } return c; } - + /** - * Returns the default "selected text" color to use if "default" is - * specified in a theme. + * Returns the default "selected text" color to use if "default" is specified in + * a theme. * * @return The default selection foreground color to use. * @see #getDefaultSelectionBG() @@ -285,16 +281,13 @@ public class Theme { } return c; } - + /** * Returns the specified font. * - * @param family - * The font family. - * @param style - * The style of font. - * @param size - * The size of the font. + * @param family The font family. + * @param style The style of font. + * @param size The size of the font. * @return The font. */ private static Font getFont(String family, int style, int size) { @@ -302,35 +295,30 @@ public class Theme { StyleContext sc = StyleContext.getDefaultStyleContext(); return sc.getFont(family, style, size); } - + /** * Loads a theme. * - * @param in - * The input stream to read from. This will be closed when this - * method returns. + * @param in The input stream to read from. This will be closed when this method + * returns. * @return The theme. - * @throws IOException - * If an IO error occurs. + * @throws IOException If an IO error occurs. * @see #save(OutputStream) */ public static Theme load(InputStream in) throws IOException { return load(in, null); } - + /** * Loads a theme. * - * @param in - * The input stream to read from. This will be closed when this - * method returns. - * @param baseFont - * The default font to use for any "base font" properties - * not specified in the theme XML. If this is null, - * a default monospaced font will be used. + * @param in The input stream to read from. This will be closed when this + * method returns. + * @param baseFont The default font to use for any "base font" properties not + * specified in the theme XML. If this is null, a + * default monospaced font will be used. * @return The theme. - * @throws IOException - * If an IO error occurs. + * @throws IOException If an IO error occurs. * @see #save(OutputStream) */ public static Theme load(InputStream in, Font baseFont) throws IOException { @@ -343,14 +331,12 @@ public class Theme { } return theme; } - + /** * Saves this theme to an output stream. * - * @param out - * The output stream to write to. - * @throws IOException - * If an IO error occurs. + * @param out The output stream to write to. + * @throws IOException If an IO error occurs. * @see #load(InputStream) */ public void save(OutputStream out) throws IOException { @@ -495,11 +481,11 @@ public class Theme { bout.close(); } } - + /** - * Returns the color represented by a string. The input is expected to - * be a 6-digit hex string, optionally prefixed by a '$'. For example, - * either of the following: + * Returns the color represented by a string. The input is expected to be a + * 6-digit hex string, optionally prefixed by a '$'. For example, either of the + * following: * *

     	 * "$00ff00"
    @@ -508,18 +494,17 @@ public class Theme {
     	 * 
     	 * will return new Color(0, 255, 0).
     	 *
    -	 * @param s
    -	 *            The string to evaluate.
    +	 * @param s The string to evaluate.
     	 * @return The color.
     	 */
     	private static Color stringToColor(String s) {
     		return stringToColor(s, null);
     	}
    -	
    +
     	/**
    -	 * Returns the color represented by a string. The input is expected to
    -	 * be a 6-digit hex string, optionally prefixed by a '$'. For example,
    -	 * either of the following:
    +	 * Returns the color represented by a string. The input is expected to be a
    +	 * 6-digit hex string, optionally prefixed by a '$'. For example, either of the
    +	 * following:
     	 * 
     	 * 
     	 * "$00ff00"
    @@ -528,11 +513,9 @@ public class Theme {
     	 * 
     	 * will return new Color(0, 255, 0).
     	 *
    -	 * @param s
    -	 *            The string to evaluate.
    -	 * @param defaultVal
    -	 *            The color to use if s is
    -	 *            "default".
    +	 * @param s          The string to evaluate.
    +	 * @param defaultVal The color to use if s is
    +	 *                   "default".
     	 * @return The color.
     	 */
     	private static Color stringToColor(String s, Color defaultVal) {
    @@ -547,24 +530,24 @@ public class Theme {
     		}
     		return null;
     	}
    -	
    +
     	/**
     	 * Loads a SyntaxScheme from an XML file.
     	 */
     	private static class XmlHandler extends DefaultHandler {
    -		
    +
     		private Theme theme;
    -		
    +
     		@Override
     		public void error(SAXParseException e) throws SAXException {
     			throw e;
     		}
    -		
    +
     		@Override
     		public void fatalError(SAXParseException e) throws SAXException {
     			throw e;
     		}
    -		
    +
     		public static void load(Theme theme, InputStream in) throws IOException {
     			SAXParserFactory spf = SAXParserFactory.newInstance();
     			spf.setValidating(true);
    @@ -584,7 +567,7 @@ public class Theme {
     				throw new IOException(se.toString());
     			}
     		}
    -		
    +
     		private static int parseInt(Attributes attrs, String attr, int def) {
     			int value = def;
     			String temp = attrs.getValue(attr);
    @@ -597,12 +580,12 @@ public class Theme {
     			}
     			return value;
     		}
    -		
    +
     		@Override
     		public InputSource resolveEntity(String publicID, String systemID) throws SAXException {
     			return new InputSource(getClass().getResourceAsStream("themes/theme.dtd"));
     		}
    -		
    +
     		@Override
     		public void startElement(String uri, String localName, String qName, Attributes attrs) {
     			if ("background".equals(qName)) {
    @@ -787,7 +770,7 @@ public class Theme {
     				}
     			}
     		}
    -		
    +
     		@Override
     		public void warning(SAXParseException e) throws SAXException {
     			throw e;
    diff --git a/src/org/fife/ui/rsyntaxtextarea/TokenImpl.java b/src/org/fife/ui/rsyntaxtextarea/TokenImpl.java
    index 0833da4..779baab 100644
    --- a/src/org/fife/ui/rsyntaxtextarea/TokenImpl.java
    +++ b/src/org/fife/ui/rsyntaxtextarea/TokenImpl.java
    @@ -22,19 +22,18 @@ import javax.swing.text.Utilities;
      * Note: The instances of Token returned by
      * {@link RSyntaxDocument}s are pooled and should always be treated as
      * immutable. They should not be cast to TokenImpl and modified.
    - * Modifying tokens you did not create yourself can and will result in
    - * rendering issues and/or runtime exceptions. You have been warned!
    + * Modifying tokens you did not create yourself can and will result in rendering
    + * issues and/or runtime exceptions. You have been warned!
      *
      * @author Robert Futrell
      * @version 0.3
      */
    -@SuppressWarnings({ "checkstyle:visibilitymodifier" })
     public class TokenImpl implements Token {
    -	
    +
     	/**
    -	 * The text this token represents. This is implemented as a segment so we
    -	 * can point directly to the text in the document without having to make a
    -	 * copy of it.
    +	 * The text this token represents. This is implemented as a segment so we can
    +	 * point directly to the text in the document without having to make a copy of
    +	 * it.
     	 */
     	public char[] text;
     	public int textOffset;
    @@ -59,11 +58,11 @@ public class TokenImpl implements Token {
     	 * The language this token is in, >= 0.
     	 */
     	private int languageIndex;
    -	
    +
     	/**
    -	 * Creates a "null" token. The token itself is not null; rather, it
    -	 * signifies that it is the last token in a linked list of tokens and
    -	 * that it is not part of a "multi-line token."
    +	 * Creates a "null" token. The token itself is not null; rather, it signifies
    +	 * that it is the last token in a linked list of tokens and that it is not part
    +	 * of a "multi-line token."
     	 */
     	public TokenImpl() {
     		this.text = null;
    @@ -74,69 +73,55 @@ public class TokenImpl implements Token {
     		hyperlink = false;
     		nextToken = null;
     	}
    -	
    +
     	/**
     	 * Constructor.
     	 *
    -	 * @param line
    -	 *            The segment from which to get the token.
    -	 * @param beg
    -	 *            The first character's position in line.
    -	 * @param end
    -	 *            The last character's position in line.
    -	 * @param startOffset
    -	 *            The offset into the document at which this
    -	 *            token begins.
    -	 * @param type
    -	 *            A token type listed as "generic" above.
    -	 * @param languageIndex
    -	 *            The language index for this token.
    +	 * @param line          The segment from which to get the token.
    +	 * @param beg           The first character's position in line.
    +	 * @param end           The last character's position in line.
    +	 * @param startOffset   The offset into the document at which this token begins.
    +	 * @param type          A token type listed as "generic" above.
    +	 * @param languageIndex The language index for this token.
     	 */
     	public TokenImpl(Segment line, int beg, int end, int startOffset, int type, int languageIndex) {
     		this(line.array, beg, end, startOffset, type, languageIndex);
     	}
    -	
    +
     	/**
     	 * Constructor.
     	 *
    -	 * @param line
    -	 *            The segment from which to get the token.
    -	 * @param beg
    -	 *            The first character's position in line.
    -	 * @param end
    -	 *            The last character's position in line.
    -	 * @param startOffset
    -	 *            The offset into the document at which this
    -	 *            token begins.
    -	 * @param type
    -	 *            A token type listed as "generic" above.
    -	 * @param languageIndex
    -	 *            The language index for this token.
    +	 * @param line          The segment from which to get the token.
    +	 * @param beg           The first character's position in line.
    +	 * @param end           The last character's position in line.
    +	 * @param startOffset   The offset into the document at which this token begins.
    +	 * @param type          A token type listed as "generic" above.
    +	 * @param languageIndex The language index for this token.
     	 */
     	public TokenImpl(char[] line, int beg, int end, int startOffset, int type, int languageIndex) {
     		this();
     		set(line, beg, end, startOffset, type);
     		setLanguageIndex(languageIndex);
     	}
    -	
    +
     	/**
     	 * Creates this token as a copy of the passed-in token.
     	 *
    -	 * @param t2
    -	 *            The token from which to make a copy.
    +	 * @param t2 The token from which to make a copy.
     	 */
     	public TokenImpl(Token t2) {
     		this();
     		copyFrom(t2);
     	}
    -	
    +
     	@Override
     	public StringBuilder appendHTMLRepresentation(StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily) {
     		return appendHTMLRepresentation(sb, textArea, fontFamily, false);
     	}
    -	
    +
     	@Override
    -	public StringBuilder appendHTMLRepresentation(StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily, boolean tabsToSpaces) {
    +	public StringBuilder appendHTMLRepresentation(StringBuilder sb, RSyntaxTextArea textArea, boolean fontFamily,
    +			boolean tabsToSpaces) {
     		SyntaxScheme colorScheme = textArea.getSyntaxScheme();
     		Style scheme = colorScheme.getStyle(getType());
     		Font font = textArea.getFontForTokenType(getType());// scheme.font;
    @@ -177,18 +162,15 @@ public class TokenImpl implements Token {
     		}
     		return sb;
     	}
    -	
    +
     	/**
    -	 * Appends an HTML version of the lexeme of this token (i.e. no style
    -	 * HTML, but replacing chars such as \t, <
    -	 * and > with their escapes).
    +	 * Appends an HTML version of the lexeme of this token (i.e. no style HTML, but
    +	 * replacing chars such as \t, < and
    +	 * > with their escapes).
     	 *
    -	 * @param textArea
    -	 *            The text area.
    -	 * @param sb
    -	 *            The buffer to append to.
    -	 * @param tabsToSpaces
    -	 *            Whether to convert tabs into spaces.
    +	 * @param textArea     The text area.
    +	 * @param sb           The buffer to append to.
    +	 * @param tabsToSpaces Whether to convert tabs into spaces.
     	 * @return The same buffer.
     	 */
     	private StringBuilder appendHtmlLexeme(RSyntaxTextArea textArea, StringBuilder sb, boolean tabsToSpaces) {
    @@ -199,64 +181,64 @@ public class TokenImpl implements Token {
     		while (i < textOffset + textCount) {
     			char ch = text[i];
     			switch (ch) {
    -				case ' ':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append(lastWasSpace ? " " : " ");
    -					lastWasSpace = true;
    -					break;
    -				case '\t':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					if (tabsToSpaces && tabStr == null) {
    -						StringBuilder stringBuilder = new StringBuilder();
    -						for (int j = 0; j < textArea.getTabSize(); j++) {
    -							stringBuilder.append(" ");
    -						}
    -						tabStr = stringBuilder.toString();
    +			case ' ':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append(lastWasSpace ? " " : " ");
    +				lastWasSpace = true;
    +				break;
    +			case '\t':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				if (tabsToSpaces && tabStr == null) {
    +					StringBuilder stringBuilder = new StringBuilder();
    +					for (int j = 0; j < textArea.getTabSize(); j++) {
    +						stringBuilder.append(" ");
     					}
    -					sb.append(tabsToSpaces ? tabStr : "	");
    -					lastWasSpace = false;
    -					break;
    -				case '&':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append("&");
    -					lastWasSpace = false;
    -					break;
    -				case '<':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append("<");
    -					lastWasSpace = false;
    -					break;
    -				case '>':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append(">");
    -					lastWasSpace = false;
    -					break;
    -				case '\'':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append("'");
    -					lastWasSpace = false;
    -					break;
    -				case '"':
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append(""");
    -					lastWasSpace = false;
    -					break;
    -				case '/': // OWASP-recommended to escape even though unnecessary
    -					sb.append(text, lastI, i - lastI);
    -					lastI = i + 1;
    -					sb.append("/");
    -					lastWasSpace = false;
    -					break;
    -				default:
    -					lastWasSpace = false;
    -					break;
    +					tabStr = stringBuilder.toString();
    +				}
    +				sb.append(tabsToSpaces ? tabStr : "	");
    +				lastWasSpace = false;
    +				break;
    +			case '&':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append("&");
    +				lastWasSpace = false;
    +				break;
    +			case '<':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append("<");
    +				lastWasSpace = false;
    +				break;
    +			case '>':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append(">");
    +				lastWasSpace = false;
    +				break;
    +			case '\'':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append("'");
    +				lastWasSpace = false;
    +				break;
    +			case '"':
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append(""");
    +				lastWasSpace = false;
    +				break;
    +			case '/': // OWASP-recommended to escape even though unnecessary
    +				sb.append(text, lastI, i - lastI);
    +				lastI = i + 1;
    +				sb.append("/");
    +				lastWasSpace = false;
    +				break;
    +			default:
    +				lastWasSpace = false;
    +				break;
     			}
     			i++;
     		}
    @@ -265,23 +247,22 @@ public class TokenImpl implements Token {
     		}
     		return sb;
     	}
    -	
    +
     	@Override
     	public char charAt(int index) {
     		return text[textOffset + index];
     	}
    -	
    +
     	@Override
     	public boolean containsPosition(int pos) {
     		return pos >= getOffset() && pos < getOffset() + textCount;
     	}
    -	
    +
     	/**
    -	 * Makes one token point to the same text segment, and have the same value
    -	 * as another token.
    +	 * Makes one token point to the same text segment, and have the same value as
    +	 * another token.
     	 *
    -	 * @param t2
    -	 *            The token from which to copy.
    +	 * @param t2 The token from which to copy.
     	 */
     	public void copyFrom(Token t2) {
     		text = t2.getTextArray();
    @@ -293,12 +274,12 @@ public class TokenImpl implements Token {
     		languageIndex = t2.getLanguageIndex();
     		nextToken = t2.getNextToken();
     	}
    -	
    +
     	@Override
     	public int documentToToken(int pos) {
     		return pos + (textOffset - getOffset());
     	}
    -	
    +
     	@Override
     	public boolean endsWith(char[] ch) {
     		if (ch == null || ch.length > textCount) {
    @@ -312,7 +293,7 @@ public class TokenImpl implements Token {
     		}
     		return true;
     	}
    -	
    +
     	@Override
     	public boolean equals(Object obj) {
     		if (obj == this) {
    @@ -322,21 +303,21 @@ public class TokenImpl implements Token {
     			return false;
     		}
     		Token t2 = (Token) obj;
    -		return offset == t2.getOffset() && type == t2.getType() && languageIndex == t2.getLanguageIndex() && hyperlink == t2.isHyperlink()
    -				&& ((getLexeme() == null && t2.getLexeme() == null) || (getLexeme() != null && getLexeme().equals(t2.getLexeme())));
    +		return offset == t2.getOffset() && type == t2.getType() && languageIndex == t2.getLanguageIndex()
    +				&& hyperlink == t2.isHyperlink() && ((getLexeme() == null && t2.getLexeme() == null)
    +						|| (getLexeme() != null && getLexeme().equals(t2.getLexeme())));
     	}
    -	
    +
     	@Override
     	public int getEndOffset() {
     		return offset + textCount;
     	}
    -	
    +
     	/**
    -	 * Returns a String of the form "#xxxxxx" good for use
    -	 * in HTML, representing the given color.
    +	 * Returns a String of the form "#xxxxxx" good for use in HTML,
    +	 * representing the given color.
     	 *
    -	 * @param color
    -	 *            The color to get a string for.
    +	 * @param color The color to get a string for.
     	 * @return The HTML form of the color. If color is
     	 *         null, #000000 is returned.
     	 */
    @@ -358,39 +339,39 @@ public class TokenImpl implements Token {
     		}
     		return "#" + hexRed + hexGreen + hexBlue;
     	}
    -	
    +
     	@Override
     	public String getHTMLRepresentation(RSyntaxTextArea textArea) {
     		StringBuilder buf = new StringBuilder();
     		appendHTMLRepresentation(buf, textArea, true);
     		return buf.toString();
     	}
    -	
    +
     	@Override
     	public int getLanguageIndex() {
     		return languageIndex;
     	}
    -	
    +
     	@Override
     	public Token getLastNonCommentNonWhitespaceToken() {
     		Token last = null;
     		for (Token t = this; t != null && t.isPaintable(); t = t.getNextToken()) {
     			switch (t.getType()) {
    -				case COMMENT_DOCUMENTATION:
    -				case COMMENT_EOL:
    -				case COMMENT_MULTILINE:
    -				case COMMENT_KEYWORD:
    -				case COMMENT_MARKUP:
    -				case WHITESPACE:
    -					break;
    -				default:
    -					last = t;
    -					break;
    +			case COMMENT_DOCUMENTATION:
    +			case COMMENT_EOL:
    +			case COMMENT_MULTILINE:
    +			case COMMENT_KEYWORD:
    +			case COMMENT_MARKUP:
    +			case WHITESPACE:
    +				break;
    +			default:
    +				last = t;
    +				break;
     			}
     		}
     		return last;
     	}
    -	
    +
     	@Override
     	public Token getLastPaintableToken() {
     		Token t = this;
    @@ -403,12 +384,12 @@ public class TokenImpl implements Token {
     		}
     		return null;
     	}
    -	
    +
     	@Override
     	public String getLexeme() {
     		return text == null ? null : new String(text, textOffset, textCount);
     	}
    -	
    +
     	@Override
     	public int getListOffset(RSyntaxTextArea textArea, TabExpander e, float x0, float x) {
     		// If the coordinate in question is before this line's start, quit.
    @@ -449,17 +430,17 @@ public class TokenImpl implements Token {
     		// If we didn't find anything, return the end position of the text.
     		return last;
     	}
    -	
    +
     	@Override
     	public Token getNextToken() {
     		return nextToken;
     	}
    -	
    +
     	@Override
     	public int getOffset() {
     		return offset;
     	}
    -	
    +
     	@Override
     	public int getOffsetBeforeX(RSyntaxTextArea textArea, TabExpander e, float startX, float endBeforeX) {
     		FontMetrics fm = textArea.getFontMetricsForTokenType(getType());
    @@ -484,27 +465,27 @@ public class TokenImpl implements Token {
     		// If we got here, the whole token fit in (endBeforeX-startX) pixels.
     		return getOffset() + textCount - 1;
     	}
    -	
    +
     	@Override
     	public char[] getTextArray() {
     		return text;
     	}
    -	
    +
     	@Override
     	public int getTextOffset() {
     		return textOffset;
     	}
    -	
    +
     	@Override
     	public int getType() {
     		return type;
     	}
    -	
    +
     	@Override
     	public float getWidth(RSyntaxTextArea textArea, TabExpander e, float x0) {
     		return getWidthUpTo(textCount, textArea, e, x0);
     	}
    -	
    +
     	@Override
     	public float getWidthUpTo(int numChars, RSyntaxTextArea textArea, TabExpander e, float x0) {
     		float width = x0;
    @@ -535,12 +516,12 @@ public class TokenImpl implements Token {
     		}
     		return width - x0;
     	}
    -	
    +
     	@Override
     	public int hashCode() {
     		return offset + (getLexeme() == null ? 0 : getLexeme().hashCode());
     	}
    -	
    +
     	@Override
     	public boolean is(char[] lexeme) {
     		if (textCount == lexeme.length) {
    @@ -553,7 +534,7 @@ public class TokenImpl implements Token {
     		}
     		return false;
     	}
    -	
    +
     	@Override
     	public boolean is(int type, char[] lexeme) {
     		if (this.getType() == type && textCount == lexeme.length) {
    @@ -566,67 +547,67 @@ public class TokenImpl implements Token {
     		}
     		return false;
     	}
    -	
    +
     	@Override
     	public boolean is(int type, String lexeme) {
     		return this.getType() == type && textCount == lexeme.length() && lexeme.equals(getLexeme());
     	}
    -	
    +
     	@Override
     	public boolean isComment() {
     		return getType() >= Token.COMMENT_EOL && getType() <= Token.COMMENT_MARKUP;
     	}
    -	
    +
     	@Override
     	public boolean isCommentOrWhitespace() {
     		return isComment() || isWhitespace();
     	}
    -	
    +
     	@Override
     	public boolean isHyperlink() {
     		return hyperlink;
     	}
    -	
    +
     	@Override
     	public boolean isIdentifier() {
     		return getType() == IDENTIFIER;
     	}
    -	
    +
     	@Override
     	public boolean isLeftCurly() {
     		return getType() == SEPARATOR && isSingleChar('{');
     	}
    -	
    +
     	@Override
     	public boolean isRightCurly() {
     		return getType() == SEPARATOR && isSingleChar('}');
     	}
    -	
    +
     	@Override
     	public boolean isPaintable() {
     		return getType() > Token.NULL;
     	}
    -	
    +
     	@Override
     	public boolean isSingleChar(char ch) {
     		return textCount == 1 && text[textOffset] == ch;
     	}
    -	
    +
     	@Override
     	public boolean isSingleChar(int type, char ch) {
     		return this.getType() == type && isSingleChar(ch);
     	}
    -	
    +
     	@Override
     	public boolean isWhitespace() {
     		return getType() == WHITESPACE;
     	}
    -	
    +
     	@Override
     	public int length() {
     		return textCount;
     	}
    -	
    +
     	@Override
     	public Rectangle listOffsetToView(RSyntaxTextArea textArea, TabExpander e, int pos, int x0, Rectangle rect) {
     		int stableX = x0; // Cached ending x-coord. of last tab or token.
    @@ -678,49 +659,46 @@ public class TokenImpl implements Token {
     		rect.width = 1;
     		return rect;
     	}
    -	
    +
     	/**
     	 * Makes this token start at the specified offset into the document.
     	 * 

    * - * Note: You should not modify Token instances you - * did not create yourself (e.g., came from an - * RSyntaxDocument). If you do, rendering issues and/or - * runtime exceptions will likely occur. You have been warned! + * Note: You should not modify Token instances you did not + * create yourself (e.g., came from an RSyntaxDocument). If you do, + * rendering issues and/or runtime exceptions will likely occur. You have been + * warned! * - * @param pos - * The offset into the document this token should start at. - * Note that this token must already contain this position; if - * it doesn't, an exception is thrown. - * @throws IllegalArgumentException - * If pos is not already contained by - * this token. + * @param pos The offset into the document this token should start at. Note that + * this token must already contain this position; if it doesn't, an + * exception is thrown. + * @throws IllegalArgumentException If pos is not already contained by this + * token. * @see #moveOffset(int) */ public void makeStartAt(int pos) { if (pos < getOffset() || pos >= (getOffset() + textCount)) { - throw new IllegalArgumentException("pos " + pos + " is not in range " + getOffset() + "-" + (getOffset() + textCount - 1)); + throw new IllegalArgumentException( + "pos " + pos + " is not in range " + getOffset() + "-" + (getOffset() + textCount - 1)); } int shift = pos - getOffset(); setOffset(pos); textOffset += shift; textCount -= shift; } - + /** * Moves the starting offset of this token. *

    * - * Note: You should not modify Token instances you - * did not create yourself (e.g., came from an - * RSyntaxDocument). If you do, rendering issues and/or - * runtime exceptions will likely occur. You have been warned! + * Note: You should not modify Token instances you did not + * create yourself (e.g., came from an RSyntaxDocument). If you do, + * rendering issues and/or runtime exceptions will likely occur. You have been + * warned! * - * @param amt - * The amount to move the starting offset. This should be - * between 0 and textCount, inclusive. - * @throws IllegalArgumentException - * If amt is an invalid value. + * @param amt The amount to move the starting offset. This should be between + * 0 and textCount, inclusive. + * @throws IllegalArgumentException If amt is an invalid value. * @see #makeStartAt(int) */ public void moveOffset(int amt) { @@ -731,21 +709,16 @@ public class TokenImpl implements Token { textOffset += amt; textCount -= amt; } - + /** - * Sets the value of this token to a particular segment of a document. - * The "next token" value is cleared. + * Sets the value of this token to a particular segment of a document. The "next + * token" value is cleared. * - * @param line - * The segment from which to get the token. - * @param beg - * The first character's position in line. - * @param end - * The last character's position in line. - * @param offset - * The offset into the document at which this token begins. - * @param type - * A token type listed as "generic" above. + * @param line The segment from which to get the token. + * @param beg The first character's position in line. + * @param end The last character's position in line. + * @param offset The offset into the document at which this token begins. + * @param type A token type listed as "generic" above. */ public void set(final char[] line, final int beg, final int end, final int offset, final int type) { this.text = line; @@ -755,61 +728,56 @@ public class TokenImpl implements Token { this.setOffset(offset); nextToken = null; } - + /** * Sets whether this token is a hyperlink. * - * @param hyperlink - * Whether this token is a hyperlink. + * @param hyperlink Whether this token is a hyperlink. * @see #isHyperlink() */ @Override public void setHyperlink(boolean hyperlink) { this.hyperlink = hyperlink; } - + /** - * Sets the language index for this token. If this value is positive, it - * denotes a specific "secondary" language this token represents (such as - * JavaScript code or CSS embedded in an HTML file). If this value is - * 0, this token is in the "main" language being edited. - * Negative values are invalid and treated as 0. + * Sets the language index for this token. If this value is positive, it denotes + * a specific "secondary" language this token represents (such as JavaScript + * code or CSS embedded in an HTML file). If this value is 0, this + * token is in the "main" language being edited. Negative values are invalid and + * treated as 0. * - * @param languageIndex - * The new language index. A value of - * 0 denotes the "main" language, any positive value - * denotes a specific secondary language. Negative values will - * be treated as 0. + * @param languageIndex The new language index. A value of 0 + * denotes the "main" language, any positive value denotes + * a specific secondary language. Negative values will be + * treated as 0. * @see #getLanguageIndex() */ @Override public void setLanguageIndex(int languageIndex) { this.languageIndex = languageIndex; } - + /** - * Sets the "next token" pointer of this token to point to the specified - * token. + * Sets the "next token" pointer of this token to point to the specified token. * - * @param nextToken - * The new next token. + * @param nextToken The new next token. * @see #getNextToken() */ public void setNextToken(Token nextToken) { this.nextToken = nextToken; } - + /** * Sets the offset into the document at which this token resides. * - * @param offset - * The new offset into the document. + * @param offset The new offset into the document. * @see #getOffset() */ public void setOffset(int offset) { this.offset = offset; } - + /** * {@inheritDoc} */ @@ -817,7 +785,7 @@ public class TokenImpl implements Token { public void setType(int type) { this.type = type; } - + /** * {@inheritDoc} */ @@ -833,7 +801,7 @@ public class TokenImpl implements Token { } return false; } - + /** * {@inheritDoc} */ @@ -841,18 +809,20 @@ public class TokenImpl implements Token { public int tokenToDocument(int pos) { return pos + (getOffset() - textOffset); } - + /** - * Returns this token as a String, which is useful for - * debugging. + * Returns this token as a String, which is useful for debugging. * * @return A string describing this token. */ @Override public String toString() { - return "[Token: " + (getType() == Token.NULL ? "" - : "text: '" + (text == null ? "" : getLexeme() + "'; " + "offset: " + getOffset() + "; type: " + getType() + "; " - + "isPaintable: " + isPaintable() + "; nextToken==null: " + (nextToken == null))) + return "[Token: " + + (getType() == Token.NULL ? "" + : "text: '" + (text == null ? "" + : getLexeme() + "'; " + "offset: " + getOffset() + "; type: " + getType() + "; " + + "isPaintable: " + isPaintable() + "; nextToken==null: " + + (nextToken == null))) + "]"; } } diff --git a/src/org/fife/ui/rsyntaxtextarea/TokenUtils.java b/src/org/fife/ui/rsyntaxtextarea/TokenUtils.java index 0312c68..6c7caf3 100644 --- a/src/org/fife/ui/rsyntaxtextarea/TokenUtils.java +++ b/src/org/fife/ui/rsyntaxtextarea/TokenUtils.java @@ -9,12 +9,13 @@ import javax.swing.text.TabExpander; * @version 1.0 */ public final class TokenUtils { - - private TokenUtils() {} - + + private TokenUtils() { + } + /** - * Modifies the passed-in token list to start at the specified offset. - * For example, if the token list covered positions 20-60 in the document + * Modifies the passed-in token list to start at the specified offset. For + * example, if the token list covered positions 20-60 in the document * (inclusive) like so: * *

    @@ -22,50 +23,46 @@ public final class TokenUtils {
     	 *   20     30   31     40   41     50   51     60
     	 * 
    * - * and you used this method to make the token list start at position 44, - * then the token list would be modified to be the following: + * and you used this method to make the token list start at position 44, then + * the token list would be modified to be the following: * *
     	 *   [part-of-old-token3] -> [token4]
     	 *   44                 50   51     60
     	 * 
    * - * Tokens that come before the specified position are forever lost, and - * the token containing that position is made to begin at that position if + * Tokens that come before the specified position are forever lost, and the + * token containing that position is made to begin at that position if * necessary. All token types remain the same as they were originally. *

    * - * This method can be useful if you are only interested in part of a token - * list (i.e., the line it represents), but you don't want to modify the - * token list yourself. + * This method can be useful if you are only interested in part of a token list + * (i.e., the line it represents), but you don't want to modify the token list + * yourself. * - * @param tokenList - * The list to make start at the specified position. - * This parameter is modified. - * @param pos - * The position at which the new token list is to start. If - * this position is not in the passed-in token list, - * returned token list will either be null or the - * unpaintable token(s) at the end of the passed-in token list. - * @param e - * How to expand tabs. - * @param textArea - * The text area from which the token list came. - * @param x0 - * The initial x-pixel position of the old token list. + * @param tokenList The list to make start at the specified position. This + * parameter is modified. + * @param pos The position at which the new token list is to start. If + * this position is not in the passed-in token list, returned + * token list will either be null or the + * unpaintable token(s) at the end of the passed-in token list. + * @param e How to expand tabs. + * @param textArea The text area from which the token list came. + * @param x0 The initial x-pixel position of the old token list. * @return Information about the "sub" token list. This will be - * null if pos was not a valid offset - * into the token list. + * null if pos was not a valid offset into the + * token list. * @see #getSubTokenList(Token, int, TabExpander, RSyntaxTextArea, float, * TokenImpl) */ - public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea, float x0) { + public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea, + float x0) { return getSubTokenList(tokenList, pos, e, textArea, x0, null); } - + /** - * Modifies the passed-in token list to start at the specified offset. - * For example, if the token list covered positions 20-60 in the document + * Modifies the passed-in token list to start at the specified offset. For + * example, if the token list covered positions 20-60 in the document * (inclusive) like so: * *

    @@ -73,48 +70,42 @@ public final class TokenUtils {
     	 *   20     30   31     40   41     50   51     60
     	 * 
    * - * and you used this method to make the token list start at position 44, - * then the token list would be modified to be the following: + * and you used this method to make the token list start at position 44, then + * the token list would be modified to be the following: * *
     	 *   [part-of-old-token3] -> [token4]
     	 *   44                 50   51     60
     	 * 
    * - * Tokens that come before the specified position are forever lost, and - * the token containing that position is made to begin at that position if + * Tokens that come before the specified position are forever lost, and the + * token containing that position is made to begin at that position if * necessary. All token types remain the same as they were originally. *

    * - * This method can be useful if you are only interested in part of a token - * list (i.e., the line it represents), but you don't want to modify the - * token list yourself. + * This method can be useful if you are only interested in part of a token list + * (i.e., the line it represents), but you don't want to modify the token list + * yourself. * - * @param tokenList - * The list to make start at the specified position. - * This parameter is modified. - * @param pos - * The position at which the new token list is to start. If - * this position is not in the passed-in token list, - * returned token list will either be null or the - * unpaintable token(s) at the end of the passed-in token list. - * @param e - * How to expand tabs. - * @param textArea - * The text area from which the token list came. - * @param x0 - * The initial x-pixel position of the old token list. - * @param tempToken - * A temporary token to use when creating the token list - * result. This may be null but callers can pass in - * a "buffer" token for performance if desired. + * @param tokenList The list to make start at the specified position. This + * parameter is modified. + * @param pos The position at which the new token list is to start. If + * this position is not in the passed-in token list, returned + * token list will either be null or the + * unpaintable token(s) at the end of the passed-in token list. + * @param e How to expand tabs. + * @param textArea The text area from which the token list came. + * @param x0 The initial x-pixel position of the old token list. + * @param tempToken A temporary token to use when creating the token list + * result. This may be null but callers can pass + * in a "buffer" token for performance if desired. * @return Information about the "sub" token list. This will be - * null if pos was not a valid offset - * into the token list. + * null if pos was not a valid offset into the + * token list. * @see #getSubTokenList(Token, int, TabExpander, RSyntaxTextArea, float) */ - public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea, float x0, - TokenImpl tempToken) { + public static TokenSubList getSubTokenList(Token tokenList, int pos, TabExpander e, final RSyntaxTextArea textArea, + float x0, TokenImpl tempToken) { if (tempToken == null) { tempToken = new TokenImpl(); } @@ -142,23 +133,22 @@ public final class TokenUtils { return new TokenSubList(tokenList, x0); // return null; } - + /** * A sub-list of tokens. */ - @SuppressWarnings({ "checkstyle:visibilitymodifier" }) public static class TokenSubList { - + /** * The "sub" token list. */ public Token tokenList; /** - * The width, in pixels, of the part of the token list "removed from - * the front." This way, you know the x-offset of the "new" token list. + * The width, in pixels, of the part of the token list "removed from the front." + * This way, you know the x-offset of the "new" token list. */ public float x; - + public TokenSubList(Token tokenList, float x) { this.tokenList = tokenList; this.x = x; diff --git a/src/org/fife/ui/rsyntaxtextarea/focusabletip/SizeGrip.java b/src/org/fife/ui/rsyntaxtextarea/focusabletip/SizeGrip.java index 7cc2aeb..d2a9a90 100644 --- a/src/org/fife/ui/rsyntaxtextarea/focusabletip/SizeGrip.java +++ b/src/org/fife/ui/rsyntaxtextarea/focusabletip/SizeGrip.java @@ -34,34 +34,32 @@ import javax.swing.event.MouseInputAdapter; * @author Robert Futrell * @version 1.0 */ -@SuppressWarnings({ "checkstyle:magicnumber" }) class SizeGrip extends JPanel { - + /** * The size grip to use if we're on OS X. */ private transient Image osxSizeGrip; - + SizeGrip() { MouseHandler adapter = new MouseHandler(); addMouseListener(adapter); addMouseMotionListener(adapter); setPreferredSize(new Dimension(16, 16)); } - + /** - * Overridden to ensure that the cursor for this component is appropriate - * for the orientation. + * Overridden to ensure that the cursor for this component is appropriate for + * the orientation. * - * @param o - * The new orientation. + * @param o The new orientation. */ @Override public void applyComponentOrientation(ComponentOrientation o) { possiblyFixCursor(o.isLeftToRight()); super.applyComponentOrientation(o); } - + /** * Creates and returns the OS X size grip image. * @@ -93,12 +91,11 @@ class SizeGrip extends JPanel { } return image; } - + /** * Paints this panel. * - * @param g - * The graphics context. + * @param g The graphics context. */ @Override protected void paintComponent(Graphics g) { @@ -146,13 +143,12 @@ class SizeGrip extends JPanel { g.fillRect(2, height - 9, 2, 2); } } - + /** * Ensures that the cursor for this component is appropriate for the * orientation. * - * @param ltr - * Whether the current component orientation is LTR. + * @param ltr Whether the current component orientation is LTR. */ protected void possiblyFixCursor(boolean ltr) { int cursor = Cursor.NE_RESIZE_CURSOR; @@ -163,7 +159,7 @@ class SizeGrip extends JPanel { setCursor(Cursor.getPredefinedCursor(cursor)); } } - + @Override public void updateUI() { super.updateUI(); @@ -177,23 +173,21 @@ class SizeGrip extends JPanel { osxSizeGrip = null; } } - + /** * Listens for mouse events on this panel and resizes the parent window * appropriately. */ private class MouseHandler extends MouseInputAdapter { - + /* - * NOTE: We use SwingUtilities.convertPointToScreen() instead of just - * using - * the locations relative to the corner component because the latter - * proved - * buggy - stretch the window too wide and some kind of arithmetic error - * started happening somewhere - our window would grow way too large. + * NOTE: We use SwingUtilities.convertPointToScreen() instead of just using the + * locations relative to the corner component because the latter proved buggy - + * stretch the window too wide and some kind of arithmetic error started + * happening somewhere - our window would grow way too large. */ private Point origPos; - + @Override public void mouseDragged(MouseEvent e) { Point newPos = e.getPoint(); @@ -223,13 +217,13 @@ class SizeGrip extends JPanel { } origPos.setLocation(newPos); } - + @Override public void mousePressed(MouseEvent e) { origPos = e.getPoint(); SwingUtilities.convertPointToScreen(origPos, SizeGrip.this); } - + @Override public void mouseReleased(MouseEvent e) { origPos = null; diff --git a/src/org/fife/ui/rtextarea/RTADefaultInputMap.java b/src/org/fife/ui/rtextarea/RTADefaultInputMap.java index 88fffc2..7a0b6d1 100644 --- a/src/org/fife/ui/rtextarea/RTADefaultInputMap.java +++ b/src/org/fife/ui/rtextarea/RTADefaultInputMap.java @@ -24,21 +24,19 @@ import javax.swing.text.DefaultEditorKit; *

  • INSERT key toggles between insert and overwrite modes. *
  • Ctrl+DELETE key deletes all text between the caret and the end of the * current line. - *
  • Ctrl+Shift+Up and Ctrl+Shift+Down move the current line up and - * down, respectively. + *
  • Ctrl+Shift+Up and Ctrl+Shift+Down move the current line up and down, + * respectively. *
  • Ctrl+J joins lines. *
  • Ctrl+Z is undo and Ctrl+Y is redo. - *
  • Ctrl+Up and Ctrl+Down shift the visible area of the text area up and - * down one line, respectively. - *
  • F2 and Shift+F2 moves to the next and previous bookmarks, - * respectively. + *
  • Ctrl+Up and Ctrl+Down shift the visible area of the text area up and down + * one line, respectively. + *
  • F2 and Shift+F2 moves to the next and previous bookmarks, respectively. *
  • Ctrl+F2 toggles whether a bookmark is on the current line. *
  • etc. * */ -@SuppressWarnings({ "checkstyle:linelength" }) public class RTADefaultInputMap extends InputMap { - + /** * Constructs the default input map for an RTextArea. */ @@ -50,12 +48,14 @@ public class RTADefaultInputMap extends InputMap { int shift = InputEvent.SHIFT_MASK; boolean isOSX = RTextArea.isOSX(); int moveByWordMod = isOSX ? alt : defaultModifier; - put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), isOSX ? DefaultEditorKit.beginAction : DefaultEditorKit.beginLineAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), + isOSX ? DefaultEditorKit.beginAction : DefaultEditorKit.beginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, shift), isOSX ? DefaultEditorKit.selectionBeginAction : DefaultEditorKit.selectionBeginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, defaultModifier), DefaultEditorKit.beginAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, defaultModifier | shift), DefaultEditorKit.selectionBeginAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), isOSX ? DefaultEditorKit.endAction : DefaultEditorKit.endLineAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), + isOSX ? DefaultEditorKit.endAction : DefaultEditorKit.endLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_END, shift), isOSX ? DefaultEditorKit.selectionEndAction : DefaultEditorKit.selectionEndLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_END, defaultModifier), DefaultEditorKit.endAction); @@ -63,7 +63,8 @@ public class RTADefaultInputMap extends InputMap { put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), DefaultEditorKit.backwardAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, shift), DefaultEditorKit.selectionBackwardAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, moveByWordMod), DefaultEditorKit.previousWordAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, moveByWordMod | shift), DefaultEditorKit.selectionPreviousWordAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, moveByWordMod | shift), + DefaultEditorKit.selectionPreviousWordAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), DefaultEditorKit.downAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, shift), DefaultEditorKit.selectionDownAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier), RTextAreaEditorKit.rtaScrollDownAction); @@ -78,10 +79,12 @@ public class RTADefaultInputMap extends InputMap { put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt), RTextAreaEditorKit.rtaLineUpAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0), DefaultEditorKit.pageUpAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, shift), RTextAreaEditorKit.rtaSelectionPageUpAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, defaultModifier | shift), RTextAreaEditorKit.rtaSelectionPageLeftAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, defaultModifier | shift), + RTextAreaEditorKit.rtaSelectionPageLeftAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), DefaultEditorKit.pageDownAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, shift), RTextAreaEditorKit.rtaSelectionPageDownAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, defaultModifier | shift), RTextAreaEditorKit.rtaSelectionPageRightAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, defaultModifier | shift), + RTextAreaEditorKit.rtaSelectionPageRightAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_CUT, 0), DefaultEditorKit.cutAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_COPY, 0), DefaultEditorKit.copyAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_PASTE, 0), DefaultEditorKit.pasteAction); @@ -99,7 +102,8 @@ public class RTADefaultInputMap extends InputMap { put(KeyStroke.getKeyStroke(KeyEvent.VK_D, defaultModifier), RTextAreaEditorKit.rtaDeleteLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_J, defaultModifier), RTextAreaEditorKit.rtaJoinLinesAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, shift), DefaultEditorKit.deletePrevCharAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier), RTextAreaEditorKit.rtaDeletePrevWordAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier), + RTextAreaEditorKit.rtaDeletePrevWordAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), DefaultEditorKit.insertTabAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), DefaultEditorKit.insertBreakAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, shift), DefaultEditorKit.insertBreakAction); @@ -114,8 +118,10 @@ public class RTADefaultInputMap extends InputMap { if (isOSX) { put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier), DefaultEditorKit.beginLineAction); put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier), DefaultEditorKit.endLineAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier | shift), DefaultEditorKit.selectionBeginLineAction); - put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier | shift), DefaultEditorKit.selectionEndLineAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier | shift), + DefaultEditorKit.selectionBeginLineAction); + put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier | shift), + DefaultEditorKit.selectionEndLineAction); } /* NOTE: Currently, macros aren't part of the default input map for */ /* RTextArea, as they display their own popup windows, etc. which */ @@ -132,10 +138,10 @@ public class RTADefaultInputMap extends InputMap { * RTextAreaEditorKit.rtaPlaybackLastMacroAction); */ } - + /** - * Returns the default modifier key for a system. For example, on Windows - * this would be the CTRL key (InputEvent.CTRL_MASK). + * Returns the default modifier key for a system. For example, on Windows this + * would be the CTRL key (InputEvent.CTRL_MASK). * * @return The default modifier key. */ diff --git a/src/org/fife/ui/rtextarea/RTATextTransferHandler.java b/src/org/fife/ui/rtextarea/RTATextTransferHandler.java index 1849c30..d92f6f9 100644 --- a/src/org/fife/ui/rtextarea/RTATextTransferHandler.java +++ b/src/org/fife/ui/rtextarea/RTATextTransferHandler.java @@ -37,33 +37,29 @@ import javax.swing.text.Position; * @author Robert Futrell * @version 0.1 */ -@SuppressWarnings("deprecation") public class RTATextTransferHandler extends TransferHandler { - + private JTextComponent exportComp; private boolean shouldRemove; private int p0; private int p1; private boolean withinSameComponent; - + /** - * Try to find a flavor that can be used to import a Transferable to a - * specified text component. - * The set of usable flavors are tried in the following order: + * Try to find a flavor that can be used to import a Transferable to a specified + * text component. The set of usable flavors are tried in the following order: *
      - *
    1. First, an attempt is made to find a flavor matching the content - * tyep of the EditorKit for the component. + *
    2. First, an attempt is made to find a flavor matching the content tyep of + * the EditorKit for the component. *
    3. Second, an attempt to find a text/plain flavor is made. - *
    4. Third, an attempt to find a flavor representing a String - * reference in the same VM is made. + *
    5. Third, an attempt to find a flavor representing a String reference in the + * same VM is made. *
    6. Lastly, DataFlavor.stringFlavor is searched for. *
    * - * @param flavors - * The flavors to check if c will accept them. - * @param c - * The text component to see whether it will accept any of the - * specified data flavors as input. + * @param flavors The flavors to check if c will accept them. + * @param c The text component to see whether it will accept any of the + * specified data flavors as input. */ protected DataFlavor getImportFlavor(DataFlavor[] flavors, JTextComponent c) { DataFlavor refFlavor = null; @@ -86,7 +82,7 @@ public class RTATextTransferHandler extends TransferHandler { } return null; } - + /** * Import the given stream data into the text component. */ @@ -105,38 +101,38 @@ public class RTATextTransferHandler extends TransferHandler { last = 0; for (int counter = 0; counter < nch; counter++) { switch (buff[counter]) { - case '\r': - if (lastWasCR) { - if (counter == 0) { - sbuff.append('\n'); - } else { - buff[counter - 1] = '\n'; - } + case '\r': + if (lastWasCR) { + if (counter == 0) { + sbuff.append('\n'); } else { - lastWasCR = true; + buff[counter - 1] = '\n'; } - break; - case '\n': - if (lastWasCR) { - if (counter > (last + 1)) { - sbuff.append(buff, last, counter - last - 1); - } - // else nothing to do, can skip \r, next write will - // write \n - lastWasCR = false; - last = counter; + } else { + lastWasCR = true; + } + break; + case '\n': + if (lastWasCR) { + if (counter > (last + 1)) { + sbuff.append(buff, last, counter - last - 1); } - break; - default: - if (lastWasCR) { - if (counter == 0) { - sbuff.append('\n'); - } else { - buff[counter - 1] = '\n'; - } - lastWasCR = false; + // else nothing to do, can skip \r, next write will + // write \n + lastWasCR = false; + last = counter; + } + break; + default: + if (lastWasCR) { + if (counter == 0) { + sbuff.append('\n'); + } else { + buff[counter - 1] = '\n'; } - break; + lastWasCR = false; + } + break; } // End fo switch (buff[counter]). } // End of for (int counter = 0; counter < nch; counter++). if (last < nch) { @@ -157,16 +153,15 @@ public class RTATextTransferHandler extends TransferHandler { } c.replaceSelection(sbuff != null ? sbuff.toString() : ""); } - + /** - * This is the type of transfer actions supported by the source. Some - * models are not mutable, so a transfer operation of COPY only should - * be advertised in that case. + * This is the type of transfer actions supported by the source. Some models are + * not mutable, so a transfer operation of COPY only should be advertised in + * that case. * - * @param c - * The component holding the data to be transfered. This - * argument is provided to enable sharing of TransferHandlers by - * multiple components. + * @param c The component holding the data to be transfered. This argument is + * provided to enable sharing of TransferHandlers by multiple + * components. * @return If the text component is editable, COPY_OR_MOVE is returned, * otherwise just COPY is allowed. */ @@ -178,14 +173,13 @@ public class RTATextTransferHandler extends TransferHandler { return COPY; } } - + /** * Create a Transferable to use as the source for a data transfer. * - * @param comp - * The component holding the data to be transfered. This - * argument is provided to enable sharing of TransferHandlers by - * multiple components. + * @param comp The component holding the data to be transfered. This argument is + * provided to enable sharing of TransferHandlers by multiple + * components. * @return The representation of the data to be transfered. * */ @@ -197,18 +191,15 @@ public class RTATextTransferHandler extends TransferHandler { p1 = exportComp.getSelectionEnd(); return (p0 != p1) ? (new TextTransferable(exportComp, p0, p1)) : null; } - + /** - * This method is called after data has been exported. This method should - * remove the data that was transfered if the action was MOVE. + * This method is called after data has been exported. This method should remove + * the data that was transfered if the action was MOVE. * - * @param source - * The component that was the source of the data. - * @param data - * The data that was transferred or possibly null - * if the action is NONE. - * @param action - * The actual action that was performed. + * @param source The component that was the source of the data. + * @param data The data that was transferred or possibly null if the action is + * NONE. + * @param action The actual action that was performed. */ @Override protected void exportDone(JComponent source, Transferable data, int action) { @@ -227,18 +218,15 @@ public class RTATextTransferHandler extends TransferHandler { ClipboardHistory.get().add(((TextTransferable) data).getPlainData()); } } - + /** - * This method causes a transfer to a component from a clipboard or a - * DND drop operation. The Transferable represents the data to be - * imported into the component. + * This method causes a transfer to a component from a clipboard or a DND drop + * operation. The Transferable represents the data to be imported into the + * component. * - * @param comp - * The component to receive the transfer. This - * argument is provided to enable sharing of TransferHandlers by - * multiple components. - * @param t - * The data to import + * @param comp The component to receive the transfer. This argument is provided + * to enable sharing of TransferHandlers by multiple components. + * @param t The data to import * @return true iff the data was inserted into the component. */ @Override @@ -272,17 +260,15 @@ public class RTATextTransferHandler extends TransferHandler { } return imported; } - + /** - * This method indicates if a component would accept an import of the - * given set of data flavors prior to actually attempting to import it. + * This method indicates if a component would accept an import of the given set + * of data flavors prior to actually attempting to import it. * - * @param comp - * The component to receive the transfer. This argument is - * provided to enable sharing of TransferHandlers by multiple - * components. - * @param flavors - * The data formats available. + * @param comp The component to receive the transfer. This argument is + * provided to enable sharing of TransferHandlers by multiple + * components. + * @param flavors The data formats available. * @return true iff the data can be inserted. */ @Override @@ -293,19 +279,19 @@ public class RTATextTransferHandler extends TransferHandler { } return (getImportFlavor(flavors, c) != null); } - + /** * A possible implementation of the Transferable interface for RTextAreas. */ static class TextTransferable implements Transferable { - + private Position p0; private Position p1; private JTextComponent c; protected String plainData; private static DataFlavor[] stringFlavors; private static DataFlavor[] plainFlavors; - + TextTransferable(JTextComponent c, int start, int end) { this.c = c; Document doc = c.getDocument(); @@ -313,31 +299,27 @@ public class RTATextTransferHandler extends TransferHandler { p0 = doc.createPosition(start); p1 = doc.createPosition(end); plainData = c.getSelectedText(); - } catch (BadLocationException ble) {} + } catch (BadLocationException ble) { + } } - + /** * Fetch the data in a text/plain format. */ protected String getPlainData() { return plainData; } - + /** - * Returns an object which represents the data to be transferred. The - * class - * of the object returned is defined by the representation class of the - * flavor. + * Returns an object which represents the data to be transferred. The class of + * the object returned is defined by the representation class of the flavor. * - * @param flavor - * the requested flavor for the data + * @param flavor the requested flavor for the data * @see DataFlavor#getRepresentationClass - * @exception IOException - * if the data is no longer available - * in the requested flavor. - * @exception UnsupportedFlavorException - * if the requested data flavor is - * not supported. + * @exception IOException if the data is no longer available in + * the requested flavor. + * @exception UnsupportedFlavorException if the requested data flavor is not + * supported. */ @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { @@ -359,17 +341,13 @@ public class RTATextTransferHandler extends TransferHandler { } throw new UnsupportedFlavorException(flavor); } - + /** - * Returns an array of DataFlavor objects indicating the flavors the - * data - * can be provided in. The array should be ordered according to - * preference - * for providing the data (from most richly descriptive to least - * descriptive). + * Returns an array of DataFlavor objects indicating the flavors the data can be + * provided in. The array should be ordered according to preference for + * providing the data (from most richly descriptive to least descriptive). * - * @return an array of data flavors in which this data can be - * transferred + * @return an array of data flavors in which this data can be transferred */ @Override public DataFlavor[] getTransferDataFlavors() { @@ -389,15 +367,13 @@ public class RTATextTransferHandler extends TransferHandler { } return flavors; } - + /** - * Returns whether or not the specified data flavor is supported for - * this object. + * Returns whether or not the specified data flavor is supported for this + * object. * - * @param flavor - * the requested flavor for the data - * @return boolean indicating whether or not the data flavor is - * supported + * @param flavor the requested flavor for the data + * @return boolean indicating whether or not the data flavor is supported */ @Override public boolean isDataFlavorSupported(DataFlavor flavor) { @@ -409,16 +385,13 @@ public class RTATextTransferHandler extends TransferHandler { } return false; } - + /** - * Returns whether or not the specified data flavor is an plain flavor - * that - * is supported. + * Returns whether or not the specified data flavor is an plain flavor that is + * supported. * - * @param flavor - * the requested flavor for the data - * @return boolean indicating whether or not the data flavor is - * supported + * @param flavor the requested flavor for the data + * @return boolean indicating whether or not the data flavor is supported */ protected boolean isPlainFlavor(DataFlavor flavor) { DataFlavor[] flavors = plainFlavors; @@ -429,24 +402,21 @@ public class RTATextTransferHandler extends TransferHandler { } return false; } - + /** - * Should the plain text flavors be offered? If so, the method - * getPlainData should be implemented to provide something reasonable. + * Should the plain text flavors be offered? If so, the method getPlainData + * should be implemented to provide something reasonable. */ protected boolean isPlainSupported() { return plainData != null; } - + /** - * Returns whether or not the specified data flavor is a String flavor - * that - * is supported. + * Returns whether or not the specified data flavor is a String flavor that is + * supported. * - * @param flavor - * the requested flavor for the data - * @return boolean indicating whether or not the data flavor is - * supported + * @param flavor the requested flavor for the data + * @return boolean indicating whether or not the data flavor is supported */ protected boolean isStringFlavor(DataFlavor flavor) { DataFlavor[] flavors = stringFlavors; @@ -457,16 +427,17 @@ public class RTATextTransferHandler extends TransferHandler { } return false; } - + void removeText() { if ((p0 != null) && (p1 != null) && (p0.getOffset() != p1.getOffset())) { try { Document doc = c.getDocument(); doc.remove(p0.getOffset(), p1.getOffset() - p0.getOffset()); - } catch (BadLocationException e) {} + } catch (BadLocationException e) { + } } } - + // Initialization of supported flavors. static { try { diff --git a/src/org/fife/ui/rtextarea/RTextAreaEditorKit.java b/src/org/fife/ui/rtextarea/RTextAreaEditorKit.java index affe579..da80e4a 100644 --- a/src/org/fife/ui/rtextarea/RTextAreaEditorKit.java +++ b/src/org/fife/ui/rtextarea/RTextAreaEditorKit.java @@ -49,9 +49,8 @@ import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; // FIXME: Replace Utilities calls with custom versions (in RSyntaxUtilities) to // cut down on all of the modelToViews, as each call causes // a getTokenList => expensive! -@SuppressWarnings({ "checkstyle:constantname" }) public class RTextAreaEditorKit extends DefaultEditorKit { - + /** * The name of the action that begins recording a macro. */ @@ -69,14 +68,13 @@ public class RTextAreaEditorKit extends DefaultEditorKit { */ public static final String rtaDeletePrevWordAction = "RTA.DeletePrevWordAction"; /** - * The name of the action taken to delete the remainder of the line (from - * the caret position to the end of the line). + * The name of the action taken to delete the remainder of the line (from the + * caret position to the end of the line). */ public static final String rtaDeleteRestOfLineAction = "RTA.DeleteRestOfLineAction"; /** - * The name of the action that completes the word at the caret position - * with the last word in the document that starts with the text up to the - * caret. + * The name of the action that completes the word at the caret position with the + * last word in the document that starts with the text up to the caret. */ public static final String rtaDumbCompleteWordAction = "RTA.DumbCompleteWordAction"; /** @@ -136,13 +134,13 @@ public class RTextAreaEditorKit extends DefaultEditorKit { */ public static final String rtaRedoAction = "RTA.RedoAction"; /** - * The name of the action to scroll the text area down one line - * without changing the caret's position. + * The name of the action to scroll the text area down one line without changing + * the caret's position. */ public static final String rtaScrollDownAction = "RTA.ScrollDownAction"; /** - * The name of the action to scroll the text area up one line - * without changing the caret's position. + * The name of the action to scroll the text area up one line without changing + * the caret's position. */ public static final String rtaScrollUpAction = "RTA.ScrollUpAction"; /** @@ -166,13 +164,13 @@ public class RTextAreaEditorKit extends DefaultEditorKit { */ public static final String rtaTimeDateAction = "RTA.TimeDateAction"; /** - * Toggles whether the current line has a bookmark, if this text area - * is in an {@link RTextScrollPane}. + * Toggles whether the current line has a bookmark, if this text area is in an + * {@link RTextScrollPane}. */ public static final String rtaToggleBookmarkAction = "RTA.ToggleBookmarkAction"; /** - * The name of the action taken when the user hits the Insert key (thus - * toggling between insert and overwrite modes). + * The name of the action taken when the user hits the Insert key (thus toggling + * between insert and overwrite modes). */ public static final String rtaToggleTextModeAction = "RTA.ToggleTextModeAction"; /** @@ -180,8 +178,7 @@ public class RTextAreaEditorKit extends DefaultEditorKit { */ public static final String rtaUndoAction = "RTA.UndoAction"; /** - * The name of the action for unselecting any selected text in the text - * area. + * The name of the action for unselecting any selected text in the text area. */ public static final String rtaUnselectAction = "RTA.UnselectAction"; /** @@ -189,21 +186,24 @@ public class RTextAreaEditorKit extends DefaultEditorKit { */ public static final String rtaUpperSelectionCaseAction = "RTA.UpperCaseAction"; /** - * The actions that RTextAreaEditorKit adds to those of - * the default editor kit. + * The actions that RTextAreaEditorKit adds to those of the default + * editor kit. */ private static final RecordableTextAction[] defaultActions = { new BeginAction(beginAction, false), new BeginAction(selectionBeginAction, true), new BeginLineAction(beginLineAction, false), new BeginLineAction(selectionBeginLineAction, true), new BeginRecordingMacroAction(), - new BeginWordAction(beginWordAction, false), new BeginWordAction(selectionBeginWordAction, true), new ClipboardHistoryAction(), - new CopyAction(), new CutAction(), new DefaultKeyTypedAction(), new DeleteLineAction(), new DeleteNextCharAction(), - new DeletePrevCharAction(), new DeletePrevWordAction(), new DeleteRestOfLineAction(), new DumbCompleteWordAction(), - new EndAction(endAction, false), new EndAction(selectionEndAction, true), new EndLineAction(endLineAction, false), - new EndLineAction(selectionEndLineAction, true), new EndRecordingMacroAction(), new EndWordAction(endWordAction, false), - new EndWordAction(endWordAction, true), new InsertBreakAction(), new InsertContentAction(), new InsertTabAction(), - new InvertSelectionCaseAction(), new JoinLinesAction(), new LowerSelectionCaseAction(), new LineMoveAction(rtaLineUpAction, -1), + new BeginWordAction(beginWordAction, false), new BeginWordAction(selectionBeginWordAction, true), + new ClipboardHistoryAction(), new CopyAction(), new CutAction(), new DefaultKeyTypedAction(), + new DeleteLineAction(), new DeleteNextCharAction(), new DeletePrevCharAction(), new DeletePrevWordAction(), + new DeleteRestOfLineAction(), new DumbCompleteWordAction(), new EndAction(endAction, false), + new EndAction(selectionEndAction, true), new EndLineAction(endLineAction, false), + new EndLineAction(selectionEndLineAction, true), new EndRecordingMacroAction(), + new EndWordAction(endWordAction, false), new EndWordAction(endWordAction, true), new InsertBreakAction(), + new InsertContentAction(), new InsertTabAction(), new InvertSelectionCaseAction(), new JoinLinesAction(), + new LowerSelectionCaseAction(), new LineMoveAction(rtaLineUpAction, -1), new LineMoveAction(rtaLineDownAction, 1), new NextBookmarkAction(rtaNextBookmarkAction, true), - new NextBookmarkAction(rtaPrevBookmarkAction, false), new NextVisualPositionAction(forwardAction, false, SwingConstants.EAST), + new NextBookmarkAction(rtaPrevBookmarkAction, false), + new NextVisualPositionAction(forwardAction, false, SwingConstants.EAST), new NextVisualPositionAction(backwardAction, false, SwingConstants.WEST), new NextVisualPositionAction(selectionForwardAction, true, SwingConstants.EAST), new NextVisualPositionAction(selectionBackwardAction, true, SwingConstants.WEST), @@ -213,52 +213,52 @@ public class RTextAreaEditorKit extends DefaultEditorKit { new NextVisualPositionAction(selectionDownAction, true, SwingConstants.SOUTH), new NextOccurrenceAction(rtaNextOccurrenceAction), new PreviousOccurrenceAction(rtaPrevOccurrenceAction), new NextWordAction(nextWordAction, false), new NextWordAction(selectionNextWordAction, true), - new PageAction(rtaSelectionPageLeftAction, true, true), new PageAction(rtaSelectionPageRightAction, false, true), - new PasteAction(), new PlaybackLastMacroAction(), new PreviousWordAction(previousWordAction, false), - new PreviousWordAction(selectionPreviousWordAction, true), new RedoAction(), new ScrollAction(rtaScrollUpAction, -1), - new ScrollAction(rtaScrollDownAction, 1), new SelectAllAction(), new SelectLineAction(), new SelectWordAction(), - new SetReadOnlyAction(), new SetWritableAction(), new ToggleBookmarkAction(), new ToggleTextModeAction(), new UndoAction(), - new UnselectAction(), new UpperSelectionCaseAction(), new VerticalPageAction(pageUpAction, -1, false), - new VerticalPageAction(pageDownAction, 1, false), new VerticalPageAction(rtaSelectionPageUpAction, -1, true), + new PageAction(rtaSelectionPageLeftAction, true, true), + new PageAction(rtaSelectionPageRightAction, false, true), new PasteAction(), new PlaybackLastMacroAction(), + new PreviousWordAction(previousWordAction, false), + new PreviousWordAction(selectionPreviousWordAction, true), new RedoAction(), + new ScrollAction(rtaScrollUpAction, -1), new ScrollAction(rtaScrollDownAction, 1), new SelectAllAction(), + new SelectLineAction(), new SelectWordAction(), new SetReadOnlyAction(), new SetWritableAction(), + new ToggleBookmarkAction(), new ToggleTextModeAction(), new UndoAction(), new UnselectAction(), + new UpperSelectionCaseAction(), new VerticalPageAction(pageUpAction, -1, false), + new VerticalPageAction(pageDownAction, 1, false), + new VerticalPageAction(rtaSelectionPageUpAction, -1, true), new VerticalPageAction(rtaSelectionPageDownAction, 1, true) }; /** * The amount of characters read at a time when reading a file. */ private static final int READBUFFER_SIZE = 32768; - + /** * Constructor. */ public RTextAreaEditorKit() { super(); } - + /** * Creates an icon row header to use in the gutter for a text area. * - * @param textArea - * The text area. + * @param textArea The text area. * @return The icon row header. */ public IconRowHeader createIconRowHeader(RTextArea textArea) { return new IconRowHeader(textArea); } - + /** * Creates a line number list to use in the gutter for a text area. * - * @param textArea - * The text area. + * @param textArea The text area. * @return The line number list. */ public LineNumberList createLineNumberList(RTextArea textArea) { return new LineNumberList(textArea); } - + /** - * Fetches the set of commands that can be used - * on a text component that is using a model and - * view produced by this kit. + * Fetches the set of commands that can be used on a text component that is + * using a model and view produced by this kit. * * @return the command list */ @@ -266,24 +266,18 @@ public class RTextAreaEditorKit extends DefaultEditorKit { public Action[] getActions() { return defaultActions; } - + /** - * Inserts content from the given stream, which will be - * treated as plain text. This method is overridden merely - * so we can increase the number of characters read at a time. + * Inserts content from the given stream, which will be treated as plain text. + * This method is overridden merely so we can increase the number of characters + * read at a time. * - * @param in - * The stream to read from - * @param doc - * The destination for the insertion. - * @param pos - * The location in the document to place the - * content >= 0. - * @exception IOException - * on any I/O error - * @exception BadLocationException - * if pos represents an invalid - * location within the document. + * @param in The stream to read from + * @param doc The destination for the insertion. + * @param pos The location in the document to place the content >= 0. + * @exception IOException on any I/O error + * @exception BadLocationException if pos represents an invalid location within + * the document. */ @Override public void read(Reader in, Document doc, int pos) throws IOException, BadLocationException { @@ -303,44 +297,44 @@ public class RTextAreaEditorKit extends DefaultEditorKit { last = 0; for (int counter = 0; counter < nch; counter++) { switch (buff[counter]) { - case '\r': - if (lastWasCR) { - isCR = true; - if (counter == 0) { - doc.insertString(pos, "\n", null); - pos++; - } else { - buff[counter - 1] = '\n'; - } + case '\r': + if (lastWasCR) { + isCR = true; + if (counter == 0) { + doc.insertString(pos, "\n", null); + pos++; } else { - lastWasCR = true; + buff[counter - 1] = '\n'; } - break; - case '\n': - if (lastWasCR) { - if (counter > (last + 1)) { - doc.insertString(pos, new String(buff, last, counter - last - 1), null); - pos += (counter - last - 1); - } - // else nothing to do, can skip \r, next write will - // write \n - lastWasCR = false; - last = counter; - isCRLF = true; + } else { + lastWasCR = true; + } + break; + case '\n': + if (lastWasCR) { + if (counter > (last + 1)) { + doc.insertString(pos, new String(buff, last, counter - last - 1), null); + pos += (counter - last - 1); } - break; - default: - if (lastWasCR) { - isCR = true; - if (counter == 0) { - doc.insertString(pos, "\n", null); - pos++; - } else { - buff[counter - 1] = '\n'; - } - lastWasCR = false; + // else nothing to do, can skip \r, next write will + // write \n + lastWasCR = false; + last = counter; + isCRLF = true; + } + break; + default: + if (lastWasCR) { + isCR = true; + if (counter == 0) { + doc.insertString(pos, "\n", null); + pos++; + } else { + buff[counter - 1] = '\n'; } - break; + lastWasCR = false; + } + break; } // End of switch (buff[counter]). } // End of for (int counter = 0; counter < nch; counter++). if (last < nch) { @@ -369,39 +363,39 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } } } - + /** * Creates a beep. */ public static class BeepAction extends RecordableTextAction { - + public BeepAction() { super(beepAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } - + @Override public final String getMacroID() { return beepAction; } } - + /** * Moves the caret to the beginning of the document. */ public static class BeginAction extends RecordableTextAction { - + private boolean select; - + public BeginAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (select) { @@ -410,27 +404,27 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.setCaretPosition(0); } } - + @Override public final String getMacroID() { return getName(); } } - + /** - * Toggles the position of the caret between the beginning of the line, - * and the first non-whitespace character on the line. + * Toggles the position of the caret between the beginning of the line, and the + * first non-whitespace character on the line. */ public static class BeginLineAction extends RecordableTextAction { - + private Segment currentLine = new Segment(); // For speed. private boolean select; - + public BeginLineAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int newPos = 0; @@ -485,7 +479,7 @@ public class RTextAreaEditorKit extends DefaultEditorKit { ble.printStackTrace(); } } - + private int getFirstNonWhitespacePos() { int offset = currentLine.offset; int end = offset + currentLine.count - 1; @@ -497,54 +491,54 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } return pos; } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action that begins recording a macro. */ public static class BeginRecordingMacroAction extends RecordableTextAction { - + public BeginRecordingMacroAction() { super(rtaBeginRecordingMacroAction); } - + public BeginRecordingMacroAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RTextArea.beginRecordingMacro(); } - + @Override public boolean isRecordable() { return false; // Never record the recording of a macro! } - + @Override public final String getMacroID() { return rtaBeginRecordingMacroAction; } } - + /** * Positions the caret at the beginning of the word. */ protected static class BeginWordAction extends RecordableTextAction { - + private boolean select; - + protected BeginWordAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { try { @@ -559,35 +553,34 @@ public class RTextAreaEditorKit extends DefaultEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public final String getMacroID() { return getName(); } - + protected int getWordStart(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordStart(textArea, offs); } } - + /** - * Action for displaying a popup with a list of recently pasted text - * snippets. + * Action for displaying a popup with a list of recently pasted text snippets. */ public static class ClipboardHistoryAction extends RecordableTextAction { - + private ClipboardHistory clipboardHistory; - + public ClipboardHistoryAction() { super(clipboardHistoryAction); clipboardHistory = ClipboardHistory.get(); } - + public ClipboardHistoryAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); clipboardHistory = ClipboardHistory.get(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Window owner = SwingUtilities.getWindowAncestor(textArea); @@ -595,81 +588,81 @@ public class RTextAreaEditorKit extends DefaultEditorKit { popup.setContents(clipboardHistory.getHistory()); popup.setVisible(true); } - + @Override public final String getMacroID() { return clipboardHistoryAction; } } - + /** * Action for copying text. */ public static class CopyAction extends RecordableTextAction { - + public CopyAction() { super(DefaultEditorKit.copyAction); } - + public CopyAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.copy(); textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return DefaultEditorKit.copyAction; } } - + /** * Action for cutting text. */ public static class CutAction extends RecordableTextAction { - + public CutAction() { super(DefaultEditorKit.cutAction); } - + public CutAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.cut(); textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return DefaultEditorKit.cutAction; } } - + /** * Action for decreasing the font size. */ public static class DecreaseFontSizeAction extends RecordableTextAction { - + protected float decreaseAmount; protected static final float MINIMUM_SIZE = 2.0f; - + public DecreaseFontSizeAction() { super(rtaDecreaseFontSizeAction); initialize(); } - + public DecreaseFontSizeAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); initialize(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Font font = textArea.getFont(); @@ -690,30 +683,30 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return rtaDecreaseFontSizeAction; } - + protected void initialize() { decreaseAmount = 1.0f; } } - + /** * The action to use when no actions in the input/action map meet the key * pressed. This is actually called from the keymap I believe. */ public static class DefaultKeyTypedAction extends RecordableTextAction { - + private Action delegate; - + public DefaultKeyTypedAction() { super(DefaultEditorKit.defaultKeyTypedAction, null, null, null, null); delegate = new DefaultEditorKit.DefaultKeyTypedAction(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { // DefaultKeyTypedAction *is* different across different JVM's @@ -724,22 +717,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { // implementation, we must delegate to it. delegate.actionPerformed(e); } - + @Override public final String getMacroID() { return DefaultEditorKit.defaultKeyTypedAction; } } - + /** * Deletes the current line(s). */ public static class DeleteLineAction extends RecordableTextAction { - + public DeleteLineAction() { super(RTextAreaEditorKit.rtaDeleteLineAction, null, null, null, null); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -764,27 +757,26 @@ public class RTextAreaEditorKit extends DefaultEditorKit { ble.printStackTrace(); // Never happens } } - + @Override public final String getMacroID() { return RTextAreaEditorKit.rtaDeleteLineAction; } } - + /** - * Deletes the character of content that follows the current caret - * position. + * Deletes the character of content that follows the current caret position. */ public static class DeleteNextCharAction extends RecordableTextAction { - + public DeleteNextCharAction() { super(DefaultEditorKit.deleteNextCharAction, null, null, null, null); } - + public DeleteNextCharAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { boolean beep = true; @@ -810,7 +802,8 @@ public class RTextAreaEditorKit extends DefaultEditorKit { doc.remove(dot, delChars); beep = false; } - } catch (BadLocationException bl) {} + } catch (BadLocationException bl) { + } } if (beep) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); @@ -819,23 +812,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.requestFocusInWindow(); } } - + @Override public final String getMacroID() { return DefaultEditorKit.deleteNextCharAction; } } - + /** - * Deletes the character of content that precedes the current caret - * position. + * Deletes the character of content that precedes the current caret position. */ public static class DeletePrevCharAction extends RecordableTextAction { - + public DeletePrevCharAction() { super(deletePrevCharAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { boolean beep = true; @@ -861,28 +853,29 @@ public class RTextAreaEditorKit extends DefaultEditorKit { doc.remove(dot - delChars, delChars); beep = false; } - } catch (BadLocationException bl) {} + } catch (BadLocationException bl) { + } } if (beep) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public final String getMacroID() { return DefaultEditorKit.deletePrevCharAction; } } - + /** * Action that deletes the previous word in the text area. */ public static class DeletePrevWordAction extends RecordableTextAction { - + public DeletePrevWordAction() { super(rtaDeletePrevWordAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -899,31 +892,30 @@ public class RTextAreaEditorKit extends DefaultEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public String getMacroID() { return rtaDeletePrevWordAction; } - + /** - * Returns the starting offset to delete. Exists so subclasses can - * override. + * Returns the starting offset to delete. Exists so subclasses can override. */ protected int getPreviousWordStart(RTextArea textArea, int end) throws BadLocationException { return Utilities.getPreviousWord(textArea, end); } } - + /** * Action that deletes all text from the caret position to the end of the * caret's line. */ public static class DeleteRestOfLineAction extends RecordableTextAction { - + public DeleteRestOfLineAction() { super(rtaDeleteRestOfLineAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { try { @@ -943,31 +935,31 @@ public class RTextAreaEditorKit extends DefaultEditorKit { ble.printStackTrace(); } } - + @Override public final String getMacroID() { return rtaDeleteRestOfLineAction; } } - + /** - * Finds the most recent word in the document that matches the "word" up - * to the current caret position, and auto-completes the rest. Repeatedly - * calling this action at the same location in the document goes one - * match back each time it is called. + * Finds the most recent word in the document that matches the "word" up to the + * current caret position, and auto-completes the rest. Repeatedly calling this + * action at the same location in the document goes one match back each time it + * is called. */ public static class DumbCompleteWordAction extends RecordableTextAction { - + private int lastWordStart; private int lastDot; private int searchOffs; private String lastPrefix; - + public DumbCompleteWordAction() { super(rtaDumbCompleteWordAction); lastWordStart = searchOffs = lastDot = -1; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1019,52 +1011,50 @@ public class RTextAreaEditorKit extends DefaultEditorKit { ble.printStackTrace(); } } - + @Override public final String getMacroID() { return getName(); } - + protected int getPreviousWord(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getPreviousWord(textArea, offs); } - + protected int getWordEnd(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordEnd(textArea, offs); } - + protected int getWordStart(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordStart(textArea, offs); } - + /** - * Utilities.getWordStart() treats spans of whitespace and - * single non-letter chars as "words." This method is used to filter - * that kind of thing out - non-words should not be suggested by this - * action. + * Utilities.getWordStart() treats spans of whitespace and single + * non-letter chars as "words." This method is used to filter that kind of thing + * out - non-words should not be suggested by this action. * - * @param prefix - * The prefix characters before the caret. - * @return Whether the prefix could be part of a "word" in the context - * of the text area's current content. + * @param prefix The prefix characters before the caret. + * @return Whether the prefix could be part of a "word" in the context of the + * text area's current content. */ protected boolean isAcceptablePrefix(String prefix) { return prefix.length() > 0 && Character.isLetter(prefix.charAt(prefix.length() - 1)); } } - + /** * Moves the caret to the end of the document. */ public static class EndAction extends RecordableTextAction { - + private boolean select; - + public EndAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int dot = getVisibleEnd(textArea); @@ -1074,29 +1064,29 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.setCaretPosition(dot); } } - + @Override public final String getMacroID() { return getName(); } - + protected int getVisibleEnd(RTextArea textArea) { return textArea.getDocument().getLength(); } } - + /** * Positions the caret at the end of the line. */ public static class EndLineAction extends RecordableTextAction { - + private boolean select; - + public EndLineAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); @@ -1123,54 +1113,54 @@ public class RTextAreaEditorKit extends DefaultEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action that ends recording a macro. */ public static class EndRecordingMacroAction extends RecordableTextAction { - + public EndRecordingMacroAction() { super(rtaEndRecordingMacroAction); } - + public EndRecordingMacroAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { RTextArea.endRecordingMacro(); } - + @Override public final String getMacroID() { return rtaEndRecordingMacroAction; } - + @Override public boolean isRecordable() { return false; // Never record the recording of a macro! } } - + /** * Positions the caret at the end of the word. */ protected static class EndWordAction extends RecordableTextAction { - + private boolean select; - + protected EndWordAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { try { @@ -1185,35 +1175,35 @@ public class RTextAreaEditorKit extends DefaultEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public final String getMacroID() { return getName(); } - + protected int getWordEnd(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getWordEnd(textArea, offs); } } - + /** * Action for increasing the font size. */ public static class IncreaseFontSizeAction extends RecordableTextAction { - + protected float increaseAmount; protected static final float MAXIMUM_SIZE = 40.0f; - + public IncreaseFontSizeAction() { super(rtaIncreaseFontSizeAction); initialize(); } - + public IncreaseFontSizeAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); initialize(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Font font = textArea.getFont(); @@ -1234,26 +1224,26 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return rtaIncreaseFontSizeAction; } - + protected void initialize() { increaseAmount = 1.0f; } } - + /** * Action for when the user presses the Enter key. */ public static class InsertBreakAction extends RecordableTextAction { - + public InsertBreakAction() { super(DefaultEditorKit.insertBreakAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1262,15 +1252,15 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.replaceSelection("\n"); } - + @Override public final String getMacroID() { return DefaultEditorKit.insertBreakAction; } - + /* - * Overridden for Sun bug 4515750. Sun fixed this in a more complicated - * way, but I'm not sure why. See BasicTextUI#getActionMap() and + * Overridden for Sun bug 4515750. Sun fixed this in a more complicated way, but + * I'm not sure why. See BasicTextUI#getActionMap() and * BasicTextUI.TextActionWrapper. */ @Override @@ -1279,16 +1269,16 @@ public class RTextAreaEditorKit extends DefaultEditorKit { return (tc == null || tc.isEditable()) ? super.isEnabled() : false; } } - + /** * Action taken when content is to be inserted. */ public static class InsertContentAction extends RecordableTextAction { - + public InsertContentAction() { super(DefaultEditorKit.insertContentAction, null, null, null, null); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1302,23 +1292,23 @@ public class RTextAreaEditorKit extends DefaultEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public final String getMacroID() { return DefaultEditorKit.insertContentAction; } } - + /** - * Places a tab character into the document. If there is a selection, it - * is removed before the tab is added. + * Places a tab character into the document. If there is a selection, it is + * removed before the tab is added. */ public static class InsertTabAction extends RecordableTextAction { - + public InsertTabAction() { super(insertTabAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1327,22 +1317,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.replaceSelection("\t"); } - + @Override public final String getMacroID() { return DefaultEditorKit.insertTabAction; } } - + /** * Action to invert the selection's case. */ public static class InvertSelectionCaseAction extends RecordableTextAction { - + public InvertSelectionCaseAction() { super(rtaInvertSelectionCaseAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1365,22 +1355,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action to join the current line and the following line. */ public static class JoinLinesAction extends RecordableTextAction { - + public JoinLinesAction() { super(rtaJoinLinesAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1408,25 +1398,25 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action that moves a line up or down. */ public static class LineMoveAction extends RecordableTextAction { - + private int moveAmt; - + public LineMoveAction(String name, int moveAmt) { super(name); this.moveAmt = moveAmt; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1464,12 +1454,12 @@ public class RTextAreaEditorKit extends DefaultEditorKit { return; } } - + @Override public final String getMacroID() { return getName(); } - + private void moveLineDown(RTextArea textArea, int line, int lineCount) throws BadLocationException { // If we'd be moving lines past the end of the document, stop. // We could perhaps just decide to move the lines to the end of the @@ -1506,7 +1496,7 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.endAtomicEdit(); } } - + private void moveLineUp(RTextArea textArea, int line, int moveCount) throws BadLocationException { Document doc = textArea.getDocument(); Element root = doc.getDefaultRootElement(); @@ -1542,16 +1532,16 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } } } - + /** * Action to make the selection lower-case. */ public static class LowerSelectionCaseAction extends RecordableTextAction { - + public LowerSelectionCaseAction() { super(rtaLowerSelectionCaseAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -1564,25 +1554,25 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action that moves the caret to the next (or previous) bookmark. */ public static class NextBookmarkAction extends RecordableTextAction { - + private boolean forward; - + public NextBookmarkAction(String name, boolean forward) { super(name); this.forward = forward; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Gutter gutter = RSyntaxUtilities.getGutter(textArea); @@ -1638,22 +1628,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } } } - + @Override public final String getMacroID() { return getName(); } } - + /** * Selects the next occurrence of the text last selected. */ public static class NextOccurrenceAction extends RecordableTextAction { - + public NextOccurrenceAction(String name) { super(name); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { String selectedText = textArea.getSelectedText(); @@ -1673,55 +1663,54 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } RTextArea.setSelectedOccurrenceText(selectedText); } - + @Override public final String getMacroID() { return getName(); } } - + /** - * Action to move the selection and/or caret. Constructor indicates - * direction to use. + * Action to move the selection and/or caret. Constructor indicates direction to + * use. */ public static class NextVisualPositionAction extends RecordableTextAction { - + private boolean select; private int direction; - + public NextVisualPositionAction(String nm, boolean select, int dir) { super(nm); this.select = select; this.direction = dir; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Caret caret = textArea.getCaret(); int dot = caret.getDot(); /* - * Move to the beginning/end of selection on a "non-shifted" - * left- or right-keypress. We shouldn't have to worry about - * navigation filters as, if one is being used, it let us get - * to that position before. + * Move to the beginning/end of selection on a "non-shifted" left- or + * right-keypress. We shouldn't have to worry about navigation filters as, if + * one is being used, it let us get to that position before. */ if (!select) { switch (direction) { - case SwingConstants.EAST: - int mark = caret.getMark(); - if (dot != mark) { - caret.setDot(Math.max(dot, mark)); - return; - } - break; - case SwingConstants.WEST: - mark = caret.getMark(); - if (dot != mark) { - caret.setDot(Math.min(dot, mark)); - return; - } - break; - default: + case SwingConstants.EAST: + int mark = caret.getMark(); + if (dot != mark) { + caret.setDot(Math.max(dot, mark)); + return; + } + break; + case SwingConstants.WEST: + mark = caret.getMark(); + if (dot != mark) { + caret.setDot(Math.min(dot, mark)); + return; + } + break; + default: } } Position.Bias[] bias = new Position.Bias[1]; @@ -1735,7 +1724,8 @@ public class RTextAreaEditorKit extends DefaultEditorKit { if (filter != null) { dot = filter.getNextVisualPositionFrom(textArea, dot, Position.Bias.Forward, direction, bias); } else { - dot = textArea.getUI().getNextVisualPositionFrom(textArea, dot, Position.Bias.Forward, direction, bias); + dot = textArea.getUI().getNextVisualPositionFrom(textArea, dot, Position.Bias.Forward, direction, + bias); } if (select) { caret.moveDot(dot); @@ -1749,25 +1739,25 @@ public class RTextAreaEditorKit extends DefaultEditorKit { ble.printStackTrace(); } } - + @Override public final String getMacroID() { return getName(); } } - + /** * Positions the caret at the next word. */ public static class NextWordAction extends RecordableTextAction { - + private boolean select; - + public NextWordAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); @@ -1796,31 +1786,31 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.setCaretPosition(offs); } } - + @Override public final String getMacroID() { return getName(); } - + protected int getNextWord(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getNextWord(textArea, offs); } } - + /** * Pages one view to the left or right. */ static class PageAction extends RecordableTextAction { - + private boolean select; private boolean left; - + PageAction(String name, boolean left, boolean select) { super(name); this.select = select; this.left = left; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int selectedIndex; @@ -1836,7 +1826,8 @@ public class RTextAreaEditorKit extends DefaultEditorKit { if (left) { selectedIndex = textArea.viewToModel(new Point(visible.x, visible.y)); } else { - selectedIndex = textArea.viewToModel(new Point(visible.x + visible.width - 1, visible.y + visible.height - 1)); + selectedIndex = textArea + .viewToModel(new Point(visible.x + visible.width - 1, visible.y + visible.height - 1)); } Document doc = textArea.getDocument(); if ((selectedIndex != 0) && (selectedIndex > (doc.getLength() - 1))) { @@ -1851,76 +1842,76 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } } } - + @Override public final String getMacroID() { return getName(); } } - + /** * Action for pasting text. */ public static class PasteAction extends RecordableTextAction { - + public PasteAction() { super(DefaultEditorKit.pasteAction); } - + public PasteAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.paste(); textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return DefaultEditorKit.pasteAction; } } - + /** * "Plays back" the last macro recorded. */ public static class PlaybackLastMacroAction extends RecordableTextAction { - + public PlaybackLastMacroAction() { super(rtaPlaybackLastMacroAction); } - + public PlaybackLastMacroAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.playbackLastMacro(); } - + @Override public boolean isRecordable() { return false; // Don't record macro playbacks. } - + @Override public final String getMacroID() { return rtaPlaybackLastMacroAction; } } - + /** * Select the previous occurrence of the text last selected. */ public static class PreviousOccurrenceAction extends RecordableTextAction { - + public PreviousOccurrenceAction(String name) { super(name); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { String selectedText = textArea.getSelectedText(); @@ -1941,25 +1932,25 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } RTextArea.setSelectedOccurrenceText(selectedText); } - + @Override public final String getMacroID() { return getName(); } } - + /** * Positions the caret at the beginning of the previous word. */ public static class PreviousWordAction extends RecordableTextAction { - + private boolean select; - + public PreviousWordAction(String name, boolean select) { super(name); this.select = select; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int offs = textArea.getCaretPosition(); @@ -1987,30 +1978,30 @@ public class RTextAreaEditorKit extends DefaultEditorKit { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } - + @Override public final String getMacroID() { return getName(); } - + protected int getPreviousWord(RTextArea textArea, int offs) throws BadLocationException { return Utilities.getPreviousWord(textArea, offs); } } - + /** * Re-does the last action undone. */ public static class RedoAction extends RecordableTextAction { - + public RedoAction() { super(rtaRedoAction); } - + public RedoAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (textArea.isEnabled() && textArea.isEditable()) { @@ -2018,26 +2009,26 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.requestFocusInWindow(); } } - + @Override public final String getMacroID() { return rtaRedoAction; } } - + /** - * Scrolls the text area one line up or down, without changing - * the caret position. + * Scrolls the text area one line up or down, without changing the caret + * position. */ public static class ScrollAction extends RecordableTextAction { - + private int delta; - + public ScrollAction(String name, int delta) { super(name); this.delta = delta; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Container parent = textArea.getParent(); @@ -2057,158 +2048,158 @@ public class RTextAreaEditorKit extends DefaultEditorKit { viewport.setViewPosition(p); } } - + @Override public final String getMacroID() { return getName(); } } - + /** * Selects the entire document. */ public static class SelectAllAction extends RecordableTextAction { - + public SelectAllAction() { super(selectAllAction); } - + public SelectAllAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Document doc = textArea.getDocument(); textArea.setCaretPosition(0); textArea.moveCaretPosition(doc.getLength()); } - + @Override public final String getMacroID() { return DefaultEditorKit.selectAllAction; } } - + /** * Selects the line around the caret. */ public static class SelectLineAction extends RecordableTextAction { - + private Action start; private Action end; - + public SelectLineAction() { super(selectLineAction); start = new BeginLineAction("pigdog", false); end = new EndLineAction("pigdog", true); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { start.actionPerformed(e); end.actionPerformed(e); } - + @Override public final String getMacroID() { return DefaultEditorKit.selectLineAction; } } - + /** * Selects the word around the caret. */ public static class SelectWordAction extends RecordableTextAction { - + protected Action start; protected Action end; - + public SelectWordAction() { super(selectWordAction); createActions(); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { start.actionPerformed(e); end.actionPerformed(e); } - + protected void createActions() { start = new BeginWordAction("pigdog", false); end = new EndWordAction("pigdog", true); } - + @Override public final String getMacroID() { return DefaultEditorKit.selectWordAction; } } - + /** * Puts the text area into read-only mode. */ public static class SetReadOnlyAction extends RecordableTextAction { - + public SetReadOnlyAction() { super(readOnlyAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.setEditable(false); } - + @Override public final String getMacroID() { return DefaultEditorKit.readOnlyAction; } - + @Override public boolean isRecordable() { return false; // Why would you want to record this? } } - + /** * Puts the text area into writable (from read-only) mode. */ public static class SetWritableAction extends RecordableTextAction { - + public SetWritableAction() { super(writableAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.setEditable(true); } - + @Override public final String getMacroID() { return DefaultEditorKit.writableAction; } - + @Override public boolean isRecordable() { return false; // Why would you want to record this? } } - + /** * The action for inserting a time/date stamp. */ public static class TimeDateAction extends RecordableTextAction { - + public TimeDateAction() { super(rtaTimeDateAction); } - + public TimeDateAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -2220,22 +2211,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { String dateString = timeDateStamp.format(today); textArea.replaceSelection(dateString); } - + @Override public final String getMacroID() { return rtaTimeDateAction; } } - + /** * Toggles whether the current line has a bookmark. */ public static class ToggleBookmarkAction extends RecordableTextAction { - + public ToggleBookmarkAction() { super(rtaToggleBookmarkAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Gutter gutter = RSyntaxUtilities.getGutter(textArea); @@ -2249,22 +2240,22 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } } } - + @Override public final String getMacroID() { return rtaToggleBookmarkAction; } } - + /** * The action for the insert key toggling insert/overwrite modes. */ public static class ToggleTextModeAction extends RecordableTextAction { - + public ToggleTextModeAction() { super(rtaToggleTextModeAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { int textMode = textArea.getTextMode(); @@ -2274,26 +2265,26 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.setTextMode(RTextArea.INSERT_MODE); } } - + @Override public final String getMacroID() { return rtaToggleTextModeAction; } } - + /** * Undoes the last action done. */ public static class UndoAction extends RecordableTextAction { - + public UndoAction() { super(rtaUndoAction); } - + public UndoAction(String name, Icon icon, String desc, Integer mnemonic, KeyStroke accelerator) { super(name, icon, desc, mnemonic, accelerator); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (textArea.isEnabled() && textArea.isEditable()) { @@ -2301,42 +2292,42 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.requestFocusInWindow(); } } - + @Override public final String getMacroID() { return rtaUndoAction; } } - + /** * Removes the selection, if any. */ public static class UnselectAction extends RecordableTextAction { - + public UnselectAction() { super(rtaUnselectAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { textArea.setCaretPosition(textArea.getCaretPosition()); } - + @Override public final String getMacroID() { return rtaUnselectAction; } } - + /** * Action to make the selection upper-case. */ public static class UpperSelectionCaseAction extends RecordableTextAction { - + public UpperSelectionCaseAction() { super(rtaUpperSelectionCaseAction); } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { @@ -2349,28 +2340,28 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.requestFocusInWindow(); } - + @Override public final String getMacroID() { return getName(); } } - + /** - * Scrolls up/down vertically. The select version of this action extends - * the selection, instead of simply moving the caret. + * Scrolls up/down vertically. The select version of this action extends the + * selection, instead of simply moving the caret. */ public static class VerticalPageAction extends RecordableTextAction { - + private boolean select; private int direction; - + public VerticalPageAction(String name, int direction, boolean select) { super(name); this.select = select; this.direction = direction; } - + @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Rectangle visible = textArea.getVisibleRect(); @@ -2392,7 +2383,8 @@ public class RTextAreaEditorKit extends DefaultEditorKit { if (visible.contains(dotBounds.x, dotBounds.y)) { // Dot is currently visible, base the new // location off the old, or - newIndex = textArea.viewToModel(new Point(x, constrainY(textArea, dotBounds.y + yOffset, 0, 0))); + newIndex = textArea + .viewToModel(new Point(x, constrainY(textArea, dotBounds.y + yOffset, 0, 0))); } else { // Dot isn't visible, choose the top or the bottom // for the new location. @@ -2414,7 +2406,8 @@ public class RTextAreaEditorKit extends DefaultEditorKit { textArea.setCaretPosition(newIndex); } } - } catch (BadLocationException ble) {} + } catch (BadLocationException ble) { + } } // End of if (selectedIndex!=-1). else { yOffset = direction * scrollAmount; @@ -2425,7 +2418,7 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } textArea.scrollRectToVisible(newVis); } - + private int constrainY(JTextComponent textArea, int y, int vis, int screenHeight) { if (y < 0) { y = 0; @@ -2435,7 +2428,7 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } return y; } - + private int constrainOffset(JTextComponent text, int offset) { Document doc = text.getDocument(); if ((offset != 0) && (offset > doc.getLength())) { @@ -2446,7 +2439,7 @@ public class RTextAreaEditorKit extends DefaultEditorKit { } return offset; } - + private void adjustScrollIfNecessary(JTextComponent text, Rectangle visible, int initialY, int index) { try { Rectangle dotBounds = text.modelToView(index); @@ -2463,9 +2456,10 @@ public class RTextAreaEditorKit extends DefaultEditorKit { visible.y = y; } } - } catch (BadLocationException ble) {} + } catch (BadLocationException ble) { + } } - + @Override public final String getMacroID() { return getName(); diff --git a/src/org/fife/ui/rtextarea/RTextAreaHighlighter.java b/src/org/fife/ui/rtextarea/RTextAreaHighlighter.java index 9c9add1..00e5a71 100644 --- a/src/org/fife/ui/rtextarea/RTextAreaHighlighter.java +++ b/src/org/fife/ui/rtextarea/RTextAreaHighlighter.java @@ -26,8 +26,8 @@ import javax.swing.text.View; import org.fife.ui.rsyntaxtextarea.DocumentRange; /** - * The highlighter implementation used by {@link RTextArea}s. It knows to - * always paint "mark all" highlights below selection highlights. + * The highlighter implementation used by {@link RTextArea}s. It knows to always + * paint "mark all" highlights below selection highlights. *

    * * Most of this code is copied from javax.swing.text.DefaultHighlighter; @@ -37,24 +37,23 @@ import org.fife.ui.rsyntaxtextarea.DocumentRange; * @version 1.0 */ public class RTextAreaHighlighter extends BasicHighlighter { - + /** * The text component we are the highlighter for. */ protected RTextArea textArea; /** - * The "mark all" highlights (to be painted separately from other - * highlights). + * The "mark all" highlights (to be painted separately from other highlights). */ private List markAllHighlights; - + /** * Constructor. */ public RTextAreaHighlighter() { markAllHighlights = new ArrayList(); } - + /** * Adds a special "marked occurrence" highlight. * @@ -80,7 +79,7 @@ public class RTextAreaHighlighter extends BasicHighlighter { mapper.damageRange(textArea, start, end); return i; } - + /** * Removes all "mark all" highlights from the view. * @@ -95,7 +94,7 @@ public class RTextAreaHighlighter extends BasicHighlighter { } markAllHighlights.clear(); } - + /** * {@inheritDoc} */ @@ -104,20 +103,19 @@ public class RTextAreaHighlighter extends BasicHighlighter { this.textArea = null; markAllHighlights.clear(); } - + /** - * Returns the number of "mark all" highlights currently shown in the - * editor. + * Returns the number of "mark all" highlights currently shown in the editor. * * @return The "mark all" highlight count. */ public int getMarkAllHighlightCount() { return markAllHighlights.size(); } - + /** - * Returns a list of "mark all" highlights in the text area. If there are - * no such highlights, this will be an empty list. + * Returns a list of "mark all" highlights in the text area. If there are no + * such highlights, this will be an empty list. * * @return The list of "mark all" highlight ranges. */ @@ -131,7 +129,7 @@ public class RTextAreaHighlighter extends BasicHighlighter { } return list; } - + /** * {@inheritDoc} */ @@ -140,33 +138,27 @@ public class RTextAreaHighlighter extends BasicHighlighter { super.install(c); this.textArea = (RTextArea) c; } - + /** - * When leaf Views (such as LabelView) are rendering they should - * call into this method. If a highlight is in the given region it will - * be drawn immediately. + * When leaf Views (such as LabelView) are rendering they should call into this + * method. If a highlight is in the given region it will be drawn immediately. * - * @param g - * Graphics used to draw - * @param lineStart - * starting offset of view - * @param lineEnd - * ending offset of view - * @param viewBounds - * Bounds of View - * @param editor - * JTextComponent - * @param view - * View instance being rendered + * @param g Graphics used to draw + * @param lineStart starting offset of view + * @param lineEnd ending offset of view + * @param viewBounds Bounds of View + * @param editor JTextComponent + * @param view View instance being rendered */ @Override - public void paintLayeredHighlights(Graphics g, int lineStart, int lineEnd, Shape viewBounds, JTextComponent editor, View view) { + public void paintLayeredHighlights(Graphics g, int lineStart, int lineEnd, Shape viewBounds, JTextComponent editor, + View view) { paintListLayered(g, lineStart, lineEnd, viewBounds, editor, view, markAllHighlights); super.paintLayeredHighlights(g, lineStart, lineEnd, viewBounds, editor, view); } - - protected void paintListLayered(Graphics g, int lineStart, int lineEnd, Shape viewBounds, JTextComponent editor, View view, - List highlights) { + + protected void paintListLayered(Graphics g, int lineStart, int lineEnd, Shape viewBounds, JTextComponent editor, + View view, List highlights) { for (int i = highlights.size() - 1; i >= 0; i--) { HighlightInfo tag = highlights.get(i); if (tag instanceof LayeredHighlightInfo) { @@ -175,13 +167,14 @@ public class RTextAreaHighlighter extends BasicHighlighter { int highlightEnd = lhi.getEndOffset() + 1; // "+1" workaround // for Java // highlight issues - if ((lineStart < highlightStart && lineEnd > highlightStart) || (lineStart >= highlightStart && lineStart < highlightEnd)) { + if ((lineStart < highlightStart && lineEnd > highlightStart) + || (lineStart >= highlightStart && lineStart < highlightEnd)) { lhi.paintLayeredHighlights(g, lineStart, lineEnd, viewBounds, editor, view); } } } } - + protected void repaintListHighlight(HighlightInfo info) { // Note: We're relying on implementation here, not interface. Yuck... if (info instanceof LayeredHighlightInfoImpl) { @@ -195,89 +188,85 @@ public class RTextAreaHighlighter extends BasicHighlighter { // safeDamageRange(info.p0, info.p1); } } - + /** * Information about a highlight being painted by this highlighter. */ - public interface HighlightInfo extends Highlighter.Highlight {} - + public interface HighlightInfo extends Highlighter.Highlight { + } + /** * Information about a layered highlight being painted by this highlighter. */ public interface LayeredHighlightInfo extends HighlightInfo { - + /** - * Restricts the region based on the receivers offsets and messages - * the painter to paint the region. + * Restricts the region based on the receivers offsets and messages the painter + * to paint the region. */ void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view); } - + /** * A straightforward implementation of HighlightInfo. */ protected static class HighlightInfoImpl implements HighlightInfo { - + private Position p0; private Position p1; private Highlighter.HighlightPainter painter; - + /** To be extended by subclasses. */ public Color getColor() { return null; } - + @Override public int getStartOffset() { return p0.getOffset(); } - + @Override public int getEndOffset() { return p1.getOffset(); } - + @Override public Highlighter.HighlightPainter getPainter() { return painter; } - + public void setStartOffset(Position startOffset) { this.p0 = startOffset; } - + public void setEndOffset(Position endOffset) { this.p1 = endOffset; } - + public void setPainter(Highlighter.HighlightPainter painter) { this.painter = painter; } } - + /** - * A straightforward implementation of HighlightInfo for - * painting layered highlights. + * A straightforward implementation of HighlightInfo for painting + * layered highlights. */ - @SuppressWarnings({ "checkstyle:visibilitymodifier" }) protected static class LayeredHighlightInfoImpl extends HighlightInfoImpl implements LayeredHighlightInfo { - + /* - * NOTE: This implementation is a "hack" so typing at the "end" of the - * highlight - * does not extend it to include the newly-typed chars, which is the - * standard - * behavior of Swing Highlights. It assumes that the "p1" Position set - * is - * actually 1 char too short, and will render the selection as if that - * "extra" + * NOTE: This implementation is a "hack" so typing at the "end" of the highlight + * does not extend it to include the newly-typed chars, which is the standard + * behavior of Swing Highlights. It assumes that the "p1" Position set is + * actually 1 char too short, and will render the selection as if that "extra" * char should be highlighted. */ public int x; public int y; public int width; public int height; - + void union(Shape bounds) { if (bounds == null) { return; @@ -297,12 +286,13 @@ public class RTextAreaHighlighter extends BasicHighlighter { height -= y; } } - + /** * {@inheritDoc} */ @Override - public void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) { + public void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, + View view) { int start = getStartOffset(); int end = getEndOffset(); end++; // Workaround for Java highlight issues diff --git a/src/org/fife/ui/rtextarea/SearchEngine.java b/src/org/fife/ui/rtextarea/SearchEngine.java index eb5cf85..94f0003 100644 --- a/src/org/fife/ui/rtextarea/SearchEngine.java +++ b/src/org/fife/ui/rtextarea/SearchEngine.java @@ -22,9 +22,9 @@ import org.fife.ui.rsyntaxtextarea.DocumentRange; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; /** - * A singleton class that can perform advanced find/replace operations - * in an {@link RTextArea}. Simply create a {@link SearchContext} and call - * one of the following methods: + * A singleton class that can perform advanced find/replace operations in an + * {@link RTextArea}. Simply create a {@link SearchContext} and call one of the + * following methods: * *

      *
    • {@link #find(JTextArea, SearchContext)} @@ -38,25 +38,22 @@ import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; * @see SearchContext */ public final class SearchEngine { - + /** * Private constructor to prevent instantiation. */ - private SearchEngine() {} - + private SearchEngine() { + } + /** - * Finds the next instance of the string/regular expression specified - * from the caret position. If a match is found, it is selected in this - * text area. + * Finds the next instance of the string/regular expression specified from the + * caret position. If a match is found, it is selected in this text area. * - * @param textArea - * The text area in which to search. - * @param context - * What to search for and all search options. + * @param textArea The text area in which to search. + * @param context What to search for and all search options. * @return The result of the operation. - * @throws PatternSyntaxException - * If this is a regular expression search - * but the search text is an invalid regular expression. + * @throws PatternSyntaxException If this is a regular expression search but the + * search text is an invalid regular expression. * @see #replace(RTextArea, SearchContext) * @see #replaceAll(RTextArea, SearchContext) */ @@ -106,21 +103,17 @@ public final class SearchEngine { result.setMarkedCount(markAllCount); return result; } - + /** - * Finds the next instance of the string/regular expression specified - * from the caret position. If a match is found, it is selected in this - * text area. + * Finds the next instance of the string/regular expression specified from the + * caret position. If a match is found, it is selected in this text area. * - * @param findIn - * The text to search in. - * @param context - * The search context. - * @return The result of the operation. "Mark all" will always be zero, - * since this method does not perform that operation. - * @throws PatternSyntaxException - * If this is a regular expression search - * but the search text is an invalid regular expression. + * @param findIn The text to search in. + * @param context The search context. + * @return The result of the operation. "Mark all" will always be zero, since + * this method does not perform that operation. + * @throws PatternSyntaxException If this is a regular expression search but the + * search text is an invalid regular expression. */ private static SearchResult findImpl(String findIn, SearchContext context) { String text = context.getSearchFor(); @@ -140,7 +133,8 @@ public final class SearchEngine { Point regExPos = null; int start = 0; do { - regExPos = getNextMatchPosRegEx(text, findIn.substring(start), forward, context.getMatchCase(), context.getWholeWord()); + regExPos = getNextMatchPosRegEx(text, findIn.substring(start), forward, context.getMatchCase(), + context.getWholeWord()); if (regExPos != null) { if (regExPos.x != regExPos.y) { regExPos.translate(start, start); @@ -157,20 +151,17 @@ public final class SearchEngine { } return new SearchResult(); } - + /** - * Returns a CharSequence for a text area that doesn't make a - * copy of its contents for iteration. This conserves memory but is likely - * just a tad slower. + * Returns a CharSequence for a text area that doesn't make a copy + * of its contents for iteration. This conserves memory but is likely just a tad + * slower. * - * @param textArea - * The text area whose document is the basis for the - * CharSequence. - * @param start - * The starting offset of the sequence (or ending offset if - * forward is false). - * @param forward - * Whether we're searching forward or backward. + * @param textArea The text area whose document is the basis for the + * CharSequence. + * @param start The starting offset of the sequence (or ending offset if + * forward is false). + * @param forward Whether we're searching forward or backward. * @return The character sequence. */ private static CharSequence getFindInCharSequence(RTextArea textArea, int start, boolean forward) { @@ -186,10 +177,10 @@ public final class SearchEngine { } return new RDocumentCharSequence(doc, csStart, csEnd); } - + /** - * Returns the text in which to search, as a string. This is used - * internally to grab the smallest buffer possible in which to search. + * Returns the text in which to search, as a string. This is used internally to + * grab the smallest buffer possible in which to search. */ private static String getFindInText(JTextArea textArea, int start, boolean forward) { // Be smart about the text we grab to search in. We grab more than @@ -208,42 +199,36 @@ public final class SearchEngine { } return findIn; } - + /** - * This method is called internally by - * getNextMatchPosRegExImpl and is used to get the locations - * of all regular-expression matches, and possibly their replacement - * strings. + * This method is called internally by getNextMatchPosRegExImpl and + * is used to get the locations of all regular-expression matches, and possibly + * their replacement strings. *

      * * Returns either: *

        - *
      • A list of points representing the starting and ending positions - * of all matches returned by the specified matcher, or - *
      • A list of RegExReplaceInfos describing the matches - * found by the matcher and the replacement strings for each. + *
      • A list of points representing the starting and ending positions of all + * matches returned by the specified matcher, or + *
      • A list of RegExReplaceInfos describing the matches found by + * the matcher and the replacement strings for each. *
      * - * If replacement is null, this method call is - * assumed to be part of a "find" operation and points are returned. If - * if is non-null, it is assumed to be part of a "replace" - * operation and the RegExReplaceInfos are returned. + * If replacement is null, this method call is assumed + * to be part of a "find" operation and points are returned. If if is + * non-null, it is assumed to be part of a "replace" operation and + * the RegExReplaceInfos are returned. *

      * - * @param m - * The matcher. - * @param replaceStr - * The string to replace matches with. This is a - * "template" string and can contain captured group references in - * the form "${digit}". + * @param m The matcher. + * @param replaceStr The string to replace matches with. This is a "template" + * string and can contain captured group references in the + * form "${digit}". * @return A list of result objects. - * @throws IndexOutOfBoundsException - * If replaceStr references - * an invalid group (less than zero or greater than the number - * of - * groups matched). + * @throws IndexOutOfBoundsException If replaceStr references an + * invalid group (less than zero or greater + * than the number of groups matched). */ - @SuppressWarnings({ "rawtypes", "unchecked" }) private static List getMatches(Matcher m, String replaceStr) { ArrayList matches = new ArrayList(); while (m.find()) { @@ -256,63 +241,53 @@ public final class SearchEngine { } return matches; } - + /** - * Searches searchIn for an occurrence of - * searchFor either forwards or backwards, matching - * case or not. + * Searches searchIn for an occurrence of searchFor + * either forwards or backwards, matching case or not. *

      * * Most clients will have no need to call this method directly. * - * @param searchFor - * The string to look for. - * @param searchIn - * The string to search in. - * @param forward - * Whether to search forward or backward in - * searchIn. - * @param matchCase - * If true, do a case-sensitive search for - * searchFor. - * @param wholeWord - * If true, searchFor - * occurrences embedded in longer words in searchIn - * don't count as matches. - * @return The starting position of a match, or -1 if no - * match was found. + * @param searchFor The string to look for. + * @param searchIn The string to search in. + * @param forward Whether to search forward or backward in + * searchIn. + * @param matchCase If true, do a case-sensitive search for + * searchFor. + * @param wholeWord If true, searchFor occurrences + * embedded in longer words in searchIn don't + * count as matches. + * @return The starting position of a match, or -1 if no match was + * found. */ - public static int getNextMatchPos(String searchFor, String searchIn, boolean forward, boolean matchCase, boolean wholeWord) { + public static int getNextMatchPos(String searchFor, String searchIn, boolean forward, boolean matchCase, + boolean wholeWord) { // Make our variables lower case if we're ignoring case. if (!matchCase) { return getNextMatchPosImpl(searchFor.toLowerCase(), searchIn.toLowerCase(), forward, matchCase, wholeWord); } return getNextMatchPosImpl(searchFor, searchIn, forward, matchCase, wholeWord); } - + /** - * Actually does the work of matching; assumes searchFor and searchIn - * are already upper/lower-cased appropriately.
      + * Actually does the work of matching; assumes searchFor and searchIn are + * already upper/lower-cased appropriately.
      * The reason this method is here is to attempt to speed up - * FindInFilesDialog; since it repeatedly calls - * this method instead of getNextMatchPos, it gets better - * performance as it no longer has to allocate a lower-cased string for - * every call. + * FindInFilesDialog; since it repeatedly calls this method instead + * of getNextMatchPos, it gets better performance as it no longer + * has to allocate a lower-cased string for every call. * - * @param searchFor - * The string to search for. - * @param searchIn - * The string to search in. - * @param goForward - * Whether the search is forward or backward. - * @param matchCase - * Whether the search is case-sensitive. - * @param wholeWord - * Whether only whole words should be matched. - * @return The location of the next match, or -1 if no - * match was found. + * @param searchFor The string to search for. + * @param searchIn The string to search in. + * @param goForward Whether the search is forward or backward. + * @param matchCase Whether the search is case-sensitive. + * @param wholeWord Whether only whole words should be matched. + * @return The location of the next match, or -1 if no match was + * found. */ - private static int getNextMatchPosImpl(String searchFor, String searchIn, boolean goForward, boolean matchCase, boolean wholeWord) { + private static int getNextMatchPosImpl(String searchFor, String searchIn, boolean goForward, boolean matchCase, + boolean wholeWord) { if (wholeWord) { int len = searchFor.length(); int temp = goForward ? 0 : searchIn.length(); @@ -337,80 +312,63 @@ public final class SearchEngine { return goForward ? searchIn.indexOf(searchFor) : searchIn.lastIndexOf(searchFor); } } - + /** - * Searches searchIn for an occurrence of regEx - * either forwards or backwards, matching case or not. + * Searches searchIn for an occurrence of regEx either + * forwards or backwards, matching case or not. * - * @param regEx - * The regular expression to look for. - * @param searchIn - * The string to search in. - * @param goForward - * Whether to search forward. If false, - * search backward. - * @param matchCase - * Whether or not to do a case-sensitive search for - * regEx. - * @param wholeWord - * If true, regEx - * occurrences embedded in longer words in searchIn - * don't count as matches. - * @return A Point representing the starting and ending - * position of the match, or null if no match was - * found. - * @throws PatternSyntaxException - * If regEx is an invalid - * regular expression. + * @param regEx The regular expression to look for. + * @param searchIn The string to search in. + * @param goForward Whether to search forward. If false, search + * backward. + * @param matchCase Whether or not to do a case-sensitive search for + * regEx. + * @param wholeWord If true, regEx occurrences + * embedded in longer words in searchIn don't + * count as matches. + * @return A Point representing the starting and ending position of + * the match, or null if no match was found. + * @throws PatternSyntaxException If regEx is an invalid regular + * expression. * @see #getNextMatchPos */ private static Point getNextMatchPosRegEx(String regEx, CharSequence searchIn, boolean goForward, boolean matchCase, boolean wholeWord) { return (Point) getNextMatchPosRegExImpl(regEx, searchIn, goForward, matchCase, wholeWord, null); } - + /** - * Searches searchIn for an occurrence of regEx - * either forwards or backwards, matching case or not. + * Searches searchIn for an occurrence of regEx either + * forwards or backwards, matching case or not. * - * @param regEx - * The regular expression to look for. - * @param searchIn - * The string to search in. - * @param goForward - * Whether to search forward. If false, - * search backward. - * @param matchCase - * Whether or not to do a case-sensitive search for - * regEx. - * @param wholeWord - * If true, regEx - * occurrences embedded in longer words in searchIn - * don't count as matches. - * @param replaceStr - * The string that will replace the match found (if - * a match is found). The object returned will contain the - * replacement string with matched groups substituted. If this - * value is null, it is assumed this call is part of - * a - * "find" instead of a "replace" operation. - * @return If replaceStr is null, a - * Point representing the starting and ending points - * of the match. If it is non-null, an object with - * information about the match and the morphed string to replace - * it with. If no match is found, null is returned. - * @throws PatternSyntaxException - * If regEx is an invalid - * regular expression. - * @throws IndexOutOfBoundsException - * If replaceStr references - * an invalid group (less than zero or greater than the number - * of - * groups matched). + * @param regEx The regular expression to look for. + * @param searchIn The string to search in. + * @param goForward Whether to search forward. If false, search + * backward. + * @param matchCase Whether or not to do a case-sensitive search for + * regEx. + * @param wholeWord If true, regEx occurrences + * embedded in longer words in searchIn don't + * count as matches. + * @param replaceStr The string that will replace the match found (if a match is + * found). The object returned will contain the replacement + * string with matched groups substituted. If this value is + * null, it is assumed this call is part of a + * "find" instead of a "replace" operation. + * @return If replaceStr is null, a Point + * representing the starting and ending points of the match. If it is + * non-null, an object with information about the match and + * the morphed string to replace it with. If no match is found, + * null is returned. + * @throws PatternSyntaxException If regEx is an invalid regular + * expression. + * @throws IndexOutOfBoundsException If replaceStr references an + * invalid group (less than zero or greater + * than the number of groups matched). * @see #getNextMatchPos */ - private static Object getNextMatchPosRegExImpl(String regEx, CharSequence searchIn, boolean goForward, boolean matchCase, - boolean wholeWord, String replaceStr) { + private static Object getNextMatchPosRegExImpl(String regEx, CharSequence searchIn, boolean goForward, + boolean matchCase, boolean wholeWord, String replaceStr) { if (wholeWord) { regEx = "\\b" + regEx + "\\b"; } @@ -444,24 +402,20 @@ public final class SearchEngine { } return null; // No match found } - + /** - * Returns information on how to implement a regular expression "replace" - * action in the specified text with the specified replacement string. + * Returns information on how to implement a regular expression "replace" action + * in the specified text with the specified replacement string. * - * @param searchIn - * The string to search in. - * @param context - * The search options. - * @return A RegExReplaceInfo object describing how to - * implement the replace. - * @throws PatternSyntaxException - * If the search text is an invalid regular - * expression. - * @throws IndexOutOfBoundsException - * If the replacement text references an - * invalid group (less than zero or greater than the number of - * groups matched). + * @param searchIn The string to search in. + * @param context The search options. + * @return A RegExReplaceInfo object describing how to implement + * the replace. + * @throws PatternSyntaxException If the search text is an invalid regular + * expression. + * @throws IndexOutOfBoundsException If the replacement text references an + * invalid group (less than zero or greater + * than the number of groups matched). * @see #getNextMatchPos */ private static RegExReplaceInfo getRegExReplaceInfo(CharSequence searchIn, SearchContext context) { @@ -476,39 +430,34 @@ public final class SearchEngine { boolean goForward = context.getSearchForward(); boolean matchCase = context.getMatchCase(); boolean wholeWord = context.getWholeWord(); - return (RegExReplaceInfo) getNextMatchPosRegExImpl(regex, searchIn, goForward, matchCase, wholeWord, replacement); + return (RegExReplaceInfo) getNextMatchPosRegExImpl(regex, searchIn, goForward, matchCase, wholeWord, + replacement); } - + /** - * Called internally by getMatches(). This method assumes - * that the specified matcher has just found a match, and that you want - * to get the string with which to replace that match. + * Called internally by getMatches(). This method assumes that the + * specified matcher has just found a match, and that you want to get the string + * with which to replace that match. *

      * - * Escapes simply insert the escaped character, except for \n - * and \t, which insert a newline and tab respectively. - * Substrings of the form $\d+ are considered to be matched - * groups. To include a literal dollar sign in your template, escape it - * (i.e. \$). + * Escapes simply insert the escaped character, except for \n and + * \t, which insert a newline and tab respectively. Substrings of + * the form $\d+ are considered to be matched groups. To include a + * literal dollar sign in your template, escape it (i.e. \$). *

      * * Most clients will have no need to call this method directly. * - * @param m - * The matcher. - * @param template - * The template for the replacement string. For example, - * "foo" would yield the replacement string - * "foo", while "$1 is the greatest" - * would yield different values depending on the value of the - * first - * captured group in the match. + * @param m The matcher. + * @param template The template for the replacement string. For example, + * "foo" would yield the replacement string + * "foo", while "$1 is the greatest" + * would yield different values depending on the value of the + * first captured group in the match. * @return The string to replace the match with. - * @throws IndexOutOfBoundsException - * If template references - * an invalid group (less than zero or greater than the number - * of - * groups matched). + * @throws IndexOutOfBoundsException If template references an + * invalid group (less than zero or greater + * than the number of groups matched). */ public static String getReplacementText(Matcher m, CharSequence template) { // NOTE: This code was mostly ripped off from J2SE's Matcher @@ -521,12 +470,12 @@ public final class SearchEngine { if (nextChar == '\\') { // Escape character. nextChar = template.charAt(++cursor); switch (nextChar) { // Special cases. - case 'n': - nextChar = '\n'; - break; - case 't': - nextChar = '\t'; - break; + case 'n': + nextChar = '\n'; + break; + case 't': + nextChar = '\t'; + break; } result.append(nextChar); cursor++; @@ -570,11 +519,11 @@ public final class SearchEngine { } return result.toString(); } - + /** * Returns whether the characters on either side of - * substr(searchIn, startPos, startPos+searchStringLength) - * are not letters or digits. + * substr(searchIn, startPos, startPos+searchStringLength) are + * not letters or digits. */ private static boolean isWholeWord(CharSequence searchIn, int offset, int len) { boolean wsBefore, wsAfter; @@ -590,17 +539,15 @@ public final class SearchEngine { } return wsBefore && wsAfter; } - + /** - * Makes the caret's dot and mark the same location so that, for the - * next search in the specified direction, a match will be found even - * if it was within the original dot and mark's selection. + * Makes the caret's dot and mark the same location so that, for the next search + * in the specified direction, a match will be found even if it was within the + * original dot and mark's selection. * - * @param textArea - * The text area. - * @param forward - * Whether the search will be forward through the - * document (false means backward). + * @param textArea The text area. + * @param forward Whether the search will be forward through the document + * (false means backward). * @return The new dot and mark position. */ private static int makeMarkAndDotEqual(JTextArea textArea, boolean forward) { @@ -609,21 +556,18 @@ public final class SearchEngine { c.setDot(val); return val; } - + /** - * Marks all instances of the specified text in this text area. This - * method is typically only called directly in response to search events - * of type SearchEvent.Type.MARK_ALL. "Mark all" behavior - * is automatically performed when {@link #find(JTextArea, SearchContext)} - * or {@link #replace(RTextArea, SearchContext)} is called. + * Marks all instances of the specified text in this text area. This method is + * typically only called directly in response to search events of type + * SearchEvent.Type.MARK_ALL. "Mark all" behavior is automatically + * performed when {@link #find(JTextArea, SearchContext)} or + * {@link #replace(RTextArea, SearchContext)} is called. * - * @param textArea - * The text area in which to mark occurrences. - * @param context - * The search context specifying the text to search for. - * It is assumed that context.getMarkAll() has - * already - * been checked and returns true. + * @param textArea The text area in which to mark occurrences. + * @param context The search context specifying the text to search for. It is + * assumed that context.getMarkAll() has already + * been checked and returns true. * @return The results of the operation. */ public static SearchResult markAll(RTextArea textArea, SearchContext context) { @@ -633,21 +577,18 @@ public final class SearchEngine { // } // return new SearchResult(); } - + /** - * Marks all instances of the specified text in this text area. This - * method is typically only called directly in response to search events - * of type SearchEvent.Type.MARK_ALL. "Mark all" behavior - * is automatically performed when {@link #find(JTextArea, SearchContext)} - * or #replace(RTextArea, SearchContext) is called. + * Marks all instances of the specified text in this text area. This method is + * typically only called directly in response to search events of type + * SearchEvent.Type.MARK_ALL. "Mark all" behavior is automatically + * performed when {@link #find(JTextArea, SearchContext)} or #replace(RTextArea, + * SearchContext) is called. * - * @param textArea - * The text area in which to mark occurrences. - * @param context - * The search context specifying the text to search for. - * It is assumed that context.getMarkAll() has - * already - * been checked and returns true. + * @param textArea The text area in which to mark occurrences. + * @param context The search context specifying the text to search for. It is + * assumed that context.getMarkAll() has already + * been checked and returns true. * @return The results of the operation. */ private static SearchResult markAllImpl(RTextArea textArea, SearchContext context) { @@ -698,25 +639,22 @@ public final class SearchEngine { } return new SearchResult(null, 0, markAllCount); } - + /** - * Finds the next instance of the regular expression specified from - * the caret position. If a match is found, it is replaced with - * the specified replacement string. + * Finds the next instance of the regular expression specified from the caret + * position. If a match is found, it is replaced with the specified replacement + * string. * - * @param textArea - * The text area in which to search. - * @param context - * What to search for and all search options. + * @param textArea The text area in which to search. + * @param context What to search for and all search options. * @return The result of the operation. - * @throws PatternSyntaxException - * If this is a regular expression search - * but the search text is an invalid regular expression. - * @throws IndexOutOfBoundsException - * If this is a regular expression search - * but the replacement text references an invalid group (less - * than - * zero or greater than the number of groups matched). + * @throws PatternSyntaxException If this is a regular expression search but + * the search text is an invalid regular + * expression. + * @throws IndexOutOfBoundsException If this is a regular expression search but + * the replacement text references an invalid + * group (less than zero or greater than the + * number of groups matched). * @see #replace(RTextArea, SearchContext) * @see #find(JTextArea, SearchContext) */ @@ -776,25 +714,22 @@ public final class SearchEngine { int count = range != null ? 1 : 0; return new SearchResult(range, count, markAllCount); } - + /** - * Finds the next instance of the text/regular expression specified from - * the caret position. If a match is found, it is replaced with the - * specified replacement string. + * Finds the next instance of the text/regular expression specified from the + * caret position. If a match is found, it is replaced with the specified + * replacement string. * - * @param textArea - * The text area in which to search. - * @param context - * What to search for and all search options. + * @param textArea The text area in which to search. + * @param context What to search for and all search options. * @return The result of the operation. - * @throws PatternSyntaxException - * If this is a regular expression search - * but the search text is an invalid regular expression. - * @throws IndexOutOfBoundsException - * If this is a regular expression search - * but the replacement text references an invalid group (less - * than - * zero or greater than the number of groups matched). + * @throws PatternSyntaxException If this is a regular expression search but + * the search text is an invalid regular + * expression. + * @throws IndexOutOfBoundsException If this is a regular expression search but + * the replacement text references an invalid + * group (less than zero or greater than the + * number of groups matched). * @see #replaceAll(RTextArea, SearchContext) * @see #find(JTextArea, SearchContext) */ @@ -847,24 +782,21 @@ public final class SearchEngine { textArea.endAtomicEdit(); } } - + /** - * Replaces all instances of the text/regular expression specified in - * the specified document with the specified replacement. + * Replaces all instances of the text/regular expression specified in the + * specified document with the specified replacement. * - * @param textArea - * The text area in which to search. - * @param context - * What to search for and all search options. + * @param textArea The text area in which to search. + * @param context What to search for and all search options. * @return The result of the operation. - * @throws PatternSyntaxException - * If this is a regular expression search - * but the replacement text is an invalid regular expression. - * @throws IndexOutOfBoundsException - * If this is a regular expression search - * but the replacement text references an invalid group (less - * than - * zero or greater than the number of groups matched). + * @throws PatternSyntaxException If this is a regular expression search but + * the replacement text is an invalid regular + * expression. + * @throws IndexOutOfBoundsException If this is a regular expression search but + * the replacement text references an invalid + * group (less than zero or greater than the + * number of groups matched). * @see #replace(RTextArea, SearchContext) * @see #find(JTextArea, SearchContext) */